githttp-fs 1.5.1

A git-backed content management database served over HTTP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! Every git operation in the system, built on libgit2 (the `git2` crate,
//! compiled with `vendored-libgit2` so no system git is needed).
//!
//! All functions here are **synchronous** and must be called through
//! `util::run_blocking`; mutating functions must additionally be called
//! while holding the tenant write lock (see `state.rs`).
//!
//! The module is organised into stateless namespace structs:
//!
//! - `GitUtils` — private low-level helpers (signatures, repo open/init,
//!   blob reads, tree building)
//! - `GitLocks` — stale `.git/index.lock` cleanup
//! - `GitMaintenance` — consolidating repack, optional prune, reflog
//!   expiry, index refresh
//! - `GitFiles` — file CRUD (list / read / exists / write / delete / move)
//! - `GitCommits` — history listing, commit detail, revert
//! - `GitTenant` — tenant repository deletion
//!
//! Two invariants shape everything below:
//!
//! **HEAD is authoritative; the working tree is a courtesy.** Every
//! existence check, content read, and commit tree is derived from HEAD's
//! tree — never from files on disk. The working tree is still kept in sync
//! (so a human can `ls` and inspect a repo), but if a past operation died
//! halfway and left stray files behind, they can never alter an operation's
//! outcome or get silently swept into a later commit. Each commit contains
//! exactly the intended change and nothing else.
//!
//! **Commits are built with `TreeUpdateBuilder`, not the git index.** The
//! classic index route (`add_path` → `write_tree`) costs O(repository size)
//! per commit because the whole index is rewritten. `TreeUpdateBuilder`
//! instead grafts a single change onto HEAD's existing tree, costing
//! O(touched path depth): only the trees along the changed path are
//! rewritten, everything else is shared with the previous commit by oid.
//! Large repositories therefore commit as fast as small ones, and moves and
//! reverts reuse existing blob oids outright (no content rehash).

use chrono::{DateTime, Utc};
use git2::build::TreeUpdateBuilder;
use git2::{
    Delta, DiffFindOptions, DiffFormat, DiffOptions, FileMode, Oid, Repository, Signature, Sort,
};
use serde::Serialize;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};

use crate::error::AppError;
use crate::seek::SeekFilter;

/// A node in the repository file tree returned by the list endpoint.
/// Serialises with a `"type"` discriminant field so clients can distinguish
/// files from directories without inspecting the presence of `children`.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TreeNode {
    File {
        name: String,
    },
    Directory {
        name: String,
        children: Vec<TreeNode>,
    },
}

/// File and directory totals returned by the count endpoint. Directories
/// are counted as visited — the extension restriction only narrows which
/// files count, never which directories are entered.
#[derive(Debug, Default)]
pub struct FileCounts {
    pub files: usize,
    pub directories: usize,
}

#[derive(Debug, Serialize)]
pub struct CommitAuthor {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize)]
pub struct CommitSummary {
    pub sha: String,
    pub message: String,
    pub author: CommitAuthor,
    pub committed_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub statistics: Option<CommitStatistics>,
}

/// Aggregate insertion/deletion/file counts for a single commit, computed
/// against its first parent (or, for the root commit, against an empty
/// tree). Renames are similarity-detected first so a pure rename does not
/// register as a full delete+add of the file's content.
#[derive(Debug, Serialize)]
pub struct CommitStatistics {
    pub insertions: usize,
    pub deletions: usize,
    pub files_changed: usize,
}

#[derive(Debug, Serialize)]
pub struct CommitDetail {
    pub sha: String,
    pub message: String,
    pub author: CommitAuthor,
    pub committed_at: DateTime<Utc>,
    pub files: Vec<CommitFileDetail>,
    pub statistics: CommitStatistics,
}

#[derive(Debug, Serialize)]
pub struct CommitFileDetail {
    pub path: String,
    /// "created" | "updated" | "deleted" | "moved"
    pub change: String,
    /// Only present for moved files — the previous path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_path: Option<String>,
    /// Full file content at this commit. Empty string for deleted files.
    pub content: String,
    /// Unified diff for this file.
    pub diff: String,
}

/// Describes a single file change that occurred in a commit.
/// Used internally to drive hook delivery.
///
/// `Created`/`Updated`/`Moved` carry the resulting content so the hook
/// payload can be built later without re-opening the repository — by the
/// time the hook consumer runs, further commits may already have landed.
#[derive(Debug, Clone)]
pub enum FileChange {
    Created {
        path: String,
        content: String,
    },
    Updated {
        path: String,
        content: String,
    },
    Deleted {
        path: String,
    },
    Moved {
        from_path: String,
        to_path: String,
        content: String,
    },
}

/// Internal record used while building per-file commit details.
/// An owned snapshot of one `git2::DiffDelta` — copied out because the
/// diff object cannot be borrowed while also being consumed by `print`.
struct DeltaRecord {
    status: Delta,
    old_oid: Oid,
    new_oid: Oid,
    old_path: Option<PathBuf>,
    new_path: Option<PathBuf>,
}

// ---------------------------------------------------------------------------
// GitUtils — private low-level helpers shared across all operation groups
// ---------------------------------------------------------------------------

struct GitUtils;

impl GitUtils {
    /// Builds the git author/committer signature from the caller-supplied
    /// identity, timestamped "now". This is the single place where the
    /// non-empty checks on `author.name`/`author.email` are enforced — every
    /// commit path funnels through here.
    fn git_signature<'a>(
        author_name: &'a str,
        author_email: &'a str,
    ) -> Result<Signature<'a>, AppError> {
        if author_name.trim().is_empty() {
            return Err(AppError::InvalidOperation {
                reason: "author.name must not be empty".to_string(),
            });
        }
        if author_email.trim().is_empty() {
            return Err(AppError::InvalidOperation {
                reason: "author.email must not be empty".to_string(),
            });
        }

        tracing::trace!(author_name = %author_name, author_email = %author_email, "creating git signature");

        Signature::now(author_name, author_email).map_err(AppError::Git)
    }

    /// Converts a git commit timestamp (unix seconds + offset) into the UTC
    /// `DateTime` used in API responses. An out-of-range value — only
    /// possible with a corrupted repository — degrades to the epoch rather
    /// than failing the whole request.
    fn timestamp_from_git_time(git_time: git2::Time) -> DateTime<Utc> {
        DateTime::from_timestamp(git_time.seconds(), 0).unwrap_or(DateTime::UNIX_EPOCH)
    }

    /// Opens an existing tenant repository, mapping a missing directory to a
    /// 404-friendly `TenantNotFound` error rather than a generic git failure.
    fn open_tenant_repo(repo_path: &Path, tenant_id: &str) -> Result<Repository, AppError> {
        if !repo_path.exists() {
            tracing::debug!(tenant_id = %tenant_id, "tenant repository not found");

            return Err(AppError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            });
        }

        tracing::trace!(tenant_id = %tenant_id, path = %repo_path.display(), "opening tenant repository");

        Repository::open(repo_path).map_err(AppError::Git)
    }

    /// Opens an existing repo or initialises a new one with an empty root commit
    /// so that HEAD is always valid for subsequent operations.
    ///
    /// This is what makes tenant provisioning implicit: the first PUT to a
    /// brand-new tenant lands here and creates the repository on the fly.
    /// The immediate `"chore: initialize"` root commit matters — every other
    /// function in this module assumes `repo.head()` resolves to a commit,
    /// and an initialised-but-commitless repository would break that.
    fn open_or_init_repo(
        repo_path: &Path,
        author_name: &str,
        author_email: &str,
    ) -> Result<Repository, AppError> {
        if repo_path.join(".git").exists() {
            tracing::trace!(path = %repo_path.display(), "opening existing repository");

            return Repository::open(repo_path).map_err(AppError::Git);
        }

        tracing::info!(path = %repo_path.display(), "initialising new tenant repository");

        std::fs::create_dir_all(repo_path)?;

        let repo = Repository::init(repo_path)?;
        let signature = Self::git_signature(author_name, author_email)?;

        // An empty tree is required for the root commit so that HEAD is valid.
        tracing::trace!(path = %repo_path.display(), "writing empty tree for root commit");

        let empty_tree_id = repo.treebuilder(None)?.write()?;
        let empty_tree = repo.find_tree(empty_tree_id)?;

        let root_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            "chore: initialize",
            &empty_tree,
            &[],
        )?;

        tracing::debug!(path = %repo_path.display(), sha = %root_oid, "root commit created");

        drop(empty_tree);

        Ok(repo)
    }

    /// Reads a blob's content from `tree` at `file_path` and decodes it as
    /// UTF-8. The UTF-8 requirement exists because content travels in JSON
    /// string fields (API responses and hook payloads) — binary blobs have
    /// no representation there, so they surface as a 422 instead.
    fn blob_content_from_tree(
        repo: &Repository,
        tree: &git2::Tree<'_>,
        file_path: &str,
    ) -> Result<String, AppError> {
        tracing::trace!(path = %file_path, "reading blob from tree");

        let tree_entry =
            tree.get_path(Path::new(file_path))
                .map_err(|_err| AppError::FileNotFound {
                    path: file_path.to_string(),
                })?;

        let blob = repo.find_blob(tree_entry.id())?;

        tracing::trace!(path = %file_path, blob_id = %tree_entry.id(), size = blob.size(), "blob found");

        std::str::from_utf8(blob.content())
            .map(|text| text.to_string())
            .map_err(|_err| AppError::InvalidUtf8 {
                path: file_path.to_string(),
            })
    }

    /// Resolves `file_path` to its blob oid in `tree`, or `None` when the
    /// path is absent or resolves to a folder — "not a file" either way.
    fn blob_oid_in_tree(tree: &git2::Tree<'_>, file_path: &str) -> Option<Oid> {
        let tree_entry = tree.get_path(Path::new(file_path)).ok()?;

        if tree_entry.kind() != Some(git2::ObjectType::Blob) {
            return None;
        }

        Some(tree_entry.id())
    }

    /// Reads a blob's content with the seek window applied — or whole when
    /// the filter is a no-op. Shared by the single and batch read paths.
    ///
    /// Windowed reads prefer a streaming ODB read (`git_odb_open_rstream`),
    /// so on loose objects — every blob written since the last maintenance
    /// repack — inflation stops as soon as the window is complete. Packed
    /// objects cannot be streamed by libgit2 (the packfile backend stores
    /// them delta'd, so it implements no `readstream`); those fall back to
    /// scanning the blob borrowed from the object cache. Either way only
    /// the selected window is allocated — the full content is never copied
    /// into a `String`.
    fn windowed_blob_content(
        repo: &Repository,
        oid: Oid,
        file_path: &str,
        seek: &SeekFilter,
    ) -> Result<String, AppError> {
        if seek.is_noop() {
            let blob = repo.find_blob(oid)?;

            return std::str::from_utf8(blob.content())
                .map(|text| text.to_string())
                .map_err(|_err| AppError::InvalidUtf8 {
                    path: file_path.to_string(),
                });
        }

        let odb = repo.odb()?;

        // Bound to a local so the stream (which borrows `odb`) is dropped
        // before `odb` itself at the end of the function.
        let window = match odb.reader(oid) {
            Ok((reader, _size, _object_type)) => {
                tracing::trace!(path = %file_path, blob_id = %oid, "seek-reading blob via odb stream");

                seek.apply_reader(std::io::BufReader::new(reader), file_path)
            }

            // The backend holding this object does not support streaming
            // reads (packed objects) — scan the whole inflated blob instead.
            Err(_stream_unsupported) => {
                tracing::trace!(path = %file_path, blob_id = %oid, "seek-reading blob in memory (streaming unsupported)");

                let blob = repo.find_blob(oid)?;

                seek.apply_reader(std::io::Cursor::new(blob.content()), file_path)
            }
        };

        window
    }

    fn path_string(path: Option<&Path>) -> String {
        path.map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default()
    }

    /// Builds a recursive `TreeNode` tree from a flat list of file paths plus
    /// an explicit list of directory stub paths (directories whose contents
    /// were not walked due to a depth limit). Directories are sorted before files
    /// at each level; entries within each group are sorted alphabetically.
    ///
    /// The two-phase approach (flat paths in, nested tree out) exists
    /// because the tree *walk* (`collect_subtree`) and the tree *shape*
    /// wanted by the API differ: git walks entries in its own order, while
    /// the response needs directories-before-files with alphabetical
    /// sorting within each group.
    fn build_tree(
        flat: Vec<String>,
        stubs: Vec<String>,
        max_depth: Option<usize>,
    ) -> Vec<TreeNode> {
        // Intermediate mutable representation. A BTreeMap keyed by entry
        // name gives alphabetical iteration for free; the dir-before-file
        // ordering is applied later, in `convert`.
        enum NodeBuilder {
            File,
            Dir(BTreeMap<String, NodeBuilder>),
        }

        // Threads one slash-separated path into the nested map, creating
        // intermediate directories as needed. When the depth limit is hit,
        // the directory at the limit is recorded as an empty stub and the
        // remainder of the path is dropped.
        fn insert(
            dir: &mut BTreeMap<String, NodeBuilder>,
            components: &[&str],
            max_depth: Option<usize>,
            current_depth: usize,
        ) {
            match components {
                [] => {}
                [name] => {
                    dir.insert(name.to_string(), NodeBuilder::File);
                }
                [name, rest @ ..] => {
                    if let Some(max) = max_depth {
                        if current_depth >= max {
                            dir.entry(name.to_string())
                                .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                            return;
                        }
                    }
                    let child = dir
                        .entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));

                    if let NodeBuilder::Dir(children) = child {
                        insert(children, rest, max_depth, current_depth + 1);
                    }
                }
            }
        }

        // Inserts a depth-limited directory as an (empty) directory node.
        // Kept separate from `insert` because a stub's final component is a
        // directory, whereas `insert`'s final component is always a file.
        fn insert_stub(dir: &mut BTreeMap<String, NodeBuilder>, components: &[&str]) {
            match components {
                [] => {}
                [name] => {
                    dir.entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                }
                [name, rest @ ..] => {
                    let child = dir
                        .entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                    if let NodeBuilder::Dir(children) = child {
                        insert_stub(children, rest);
                    }
                }
            }
        }

        // Recursively converts the builder map into the serialisable
        // `TreeNode` shape, applying the directories-first ordering at
        // every level (the BTreeMap already yields names alphabetically).
        fn convert(name: String, node: NodeBuilder) -> TreeNode {
            match node {
                NodeBuilder::File => TreeNode::File { name },
                NodeBuilder::Dir(children) => {
                    let mut dirs: Vec<TreeNode> = Vec::new();
                    let mut files: Vec<TreeNode> = Vec::new();

                    for (child_name, child_node) in children {
                        match child_node {
                            NodeBuilder::Dir(_) => dirs.push(convert(child_name, child_node)),
                            NodeBuilder::File => files.push(convert(child_name, child_node)),
                        }
                    }

                    TreeNode::Directory {
                        name,
                        children: dirs.into_iter().chain(files).collect(),
                    }
                }
            }
        }

        let mut root: BTreeMap<String, NodeBuilder> = BTreeMap::new();

        for path in flat {
            let components: Vec<&str> = path.split('/').collect();
            insert(&mut root, &components, max_depth, 1);
        }

        for stub_path in stubs {
            let components: Vec<&str> = stub_path.split('/').collect();
            insert_stub(&mut root, &components);
        }

        let mut dirs: Vec<TreeNode> = Vec::new();
        let mut files: Vec<TreeNode> = Vec::new();

        for (name, node) in root {
            match node {
                NodeBuilder::Dir(_) => dirs.push(convert(name, node)),
                NodeBuilder::File => files.push(convert(name, node)),
            }
        }

        dirs.into_iter().chain(files).collect()
    }
}

// ---------------------------------------------------------------------------
// GitLocks — stale lock file detection and cleanup
// ---------------------------------------------------------------------------

/// Cleanup of stale `.git/index.lock` files.
///
/// libgit2 creates `index.lock` while writing the index and removes it when
/// done; a process killed in between leaves the lock behind forever, and any
/// future index write fails until it is removed. The write path no longer
/// touches the index at all (commits go through `TreeUpdateBuilder`), so
/// only maintenance's index refresh can be blocked — but that still warrants
/// cleaning locks up at startup and before each refresh.
pub struct GitLocks;

impl GitLocks {
    /// Removes `.git/index.lock` if it is older than 30 seconds.
    /// A stale lock is left behind when a process is killed mid-operation.
    ///
    /// The age threshold is the safety margin: a lock younger than 30 s
    /// *could* belong to a live external process (say, an operator running
    /// `git` by hand inside the repo), so it is left alone. No internal
    /// operation holds the index lock anywhere near that long.
    pub fn cleanup_stale_index_lock(repo_path: &Path) -> Result<(), AppError> {
        const STALE_LOCK_THRESHOLD_SECS: u64 = 30;

        let lock_path = repo_path.join(".git").join("index.lock");

        let metadata = match std::fs::metadata(&lock_path) {
            Ok(metadata) => metadata,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(err) => return Err(AppError::Io(err)),
        };

        let modified_time = metadata.modified()?;

        let lock_age = std::time::SystemTime::now()
            .duration_since(modified_time)
            .unwrap_or_default();

        if lock_age.as_secs() > STALE_LOCK_THRESHOLD_SECS {
            tracing::warn!(
                "Removing stale git lock file at {:?} (age: {}s)",
                lock_path,
                lock_age.as_secs()
            );

            if let Err(err) = std::fs::remove_file(&lock_path) {
                // Another worker may have cleaned the lock in the meantime.
                if err.kind() != std::io::ErrorKind::NotFound {
                    return Err(AppError::Io(err));
                }
            }
        }

        Ok(())
    }

    /// Walks `repos_root` once on startup and removes any leftover `.git/index.lock`
    /// regardless of age — no live operation can hold a lock at boot.
    ///
    /// The directory layout being walked is `repos_root/<collection>/<tenant>/.git`.
    /// Every error along the way is swallowed on purpose: lock cleanup is
    /// best-effort hygiene and must never prevent the server from starting.
    pub fn cleanup_all_stale_locks(repos_root: &Path) {
        let collections_dir = match std::fs::read_dir(repos_root) {
            Ok(d) => d,
            Err(_) => return,
        };

        for collection_entry_result in collections_dir {
            let Ok(collection_entry) = collection_entry_result else {
                continue;
            };

            let collection_path = collection_entry.path();

            if !collection_path.is_dir() {
                continue;
            }

            let tenants_dir = match std::fs::read_dir(&collection_path) {
                Ok(d) => d,
                Err(_) => continue,
            };

            for tenant_entry_result in tenants_dir {
                let Ok(tenant_entry) = tenant_entry_result else {
                    continue;
                };

                let lock_path = tenant_entry.path().join(".git").join("index.lock");

                if lock_path.exists() {
                    tracing::warn!(
                        "Removing stale git lock file found on startup: {:?}",
                        lock_path
                    );

                    if let Err(remove_err) = std::fs::remove_file(&lock_path) {
                        tracing::error!(
                            "Failed to remove stale lock {:?}: {}",
                            lock_path,
                            remove_err
                        );
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// GitMaintenance — background repack, optional prune, reflog expiry, index refresh
// ---------------------------------------------------------------------------

/// Summary of what one maintenance pass did, consumed by the scheduler's log
/// line in `maintenance.rs`.
#[derive(Debug, Default)]
pub struct MaintenanceReport {
    /// Reachable objects written into the consolidated packfile
    /// (0 when the repack was skipped because nothing had changed).
    pub packed_objects: usize,
    /// Loose object files deleted. All of them live on in the new pack —
    /// except, when `destructive_prune` is enabled, unreachable ones, which
    /// are thereby pruned.
    pub loose_objects_removed: usize,
    /// Superseded packfiles deleted after consolidation.
    pub old_packs_removed: usize,
}

/// The maintenance pass itself (the *when* lives in `maintenance.rs`; this
/// is the *what*). Equivalent in spirit to `git repack -a -d` + `git reflog
/// expire --all` + `git read-tree HEAD` — plus `git prune` when
/// `destructive_prune` is enabled — implemented directly against libgit2 so
/// the binary stays self-contained.
pub struct GitMaintenance;

impl GitMaintenance {
    /// Runs one full housekeeping pass over a tenant repository:
    ///
    /// 1. **Reflog expiry** — reflogs are pure bloat here: history is never
    ///    rewritten and the API never exposes them, yet every commit appends
    ///    an entry, so they grow without bound. They are simply deleted (and
    ///    start accumulating again until the next pass).
    /// 2. **Consolidating repack** — one new packfile is written, then *all*
    ///    loose objects and *all* superseded packfiles are deleted. What
    ///    goes into that pack depends on `destructive_prune`:
    ///    - `false` (default): every object in the store, reachable or not.
    ///      Maintenance can then never destroy data under any circumstance;
    ///      orphaned garbage (e.g. blobs from writes that failed between
    ///      blob creation and commit) is retained forever.
    ///    - `true`: only objects reachable from a ref. Orphaned garbage is
    ///      permanently pruned. Note this never touches *history*: commits
    ///      are append-only in this system, so every past file version —
    ///      including versions of since-deleted files — stays reachable
    ///      through its commit and is always carried over.
    ///    Skipped entirely when the repository is already consolidated (no
    ///    loose objects, at most one pack).
    /// 3. **Index refresh** — the on-disk index is reset to HEAD so
    ///    `git status` stays meaningful for humans (the write path never
    ///    touches the index).
    ///
    /// Must be called while holding the tenant write lock. That lock is also
    /// why pruning needs no grace period, unlike `git gc` with its two-week
    /// default: objects are only ever created under the same lock, so there
    /// can be no in-flight object that is "not referenced *yet*" — anything
    /// unreachable now is unreachable forever (the write path derives every
    /// commit from HEAD, never from pre-existing stray objects).
    ///
    /// Concurrent reads are safe throughout: readers hold their own
    /// `Repository` handles, deleting a pack file that a reader has mapped
    /// does not invalidate the mapping (POSIX unlink semantics), and on a
    /// missed lookup libgit2 rescans the pack directory and finds the new
    /// consolidated pack.
    pub fn run(repo_path: &Path, destructive_prune: bool) -> Result<MaintenanceReport, AppError> {
        // The tenant may have been deleted while the timer was armed.
        if !repo_path.join(".git").exists() {
            tracing::debug!(path = %repo_path.display(), "repository gone, skipping maintenance");

            return Ok(MaintenanceReport::default());
        }

        let repo = Repository::open(repo_path)?;

        Self::expire_reflogs(&repo);

        let loose_objects = Self::enumerate_loose_objects(repo_path)?;
        let packs_before = Self::enumerate_pack_stems(repo_path)?;

        tracing::debug!(
            path = %repo_path.display(),
            loose_objects = loose_objects.len(),
            packs = packs_before.len(),
            destructive_prune = destructive_prune,
            "running repository maintenance"
        );

        // Already consolidated (single pack, no loose objects) means no write
        // has landed since the previous pass — every write creates loose
        // objects — so the repack would just rebuild the identical pack.
        let report = if loose_objects.is_empty() && packs_before.len() <= 1 {
            MaintenanceReport::default()
        } else {
            Self::repack(
                &repo,
                repo_path,
                destructive_prune,
                &loose_objects,
                &packs_before,
            )?
        };

        // Refresh the on-disk index to HEAD. Clean a stale index.lock first —
        // this is the only code path left that writes the index.
        GitLocks::cleanup_stale_index_lock(repo_path)?;

        let head_tree = repo.head()?.peel_to_commit()?.tree()?;
        let mut index = repo.index()?;

        index.read_tree(&head_tree)?;
        index.write()?;

        Ok(report)
    }

    /// Writes one consolidated packfile — holding either every object or
    /// only the reachable ones, per `destructive_prune` — then deletes the
    /// now-redundant loose objects and superseded packs.
    ///
    /// Crash safety: the new pack is fully written and committed to the ODB
    /// *before* anything is deleted, so a failure at any point never loses
    /// objects — at worst it leaves redundant copies that the next pass
    /// cleans up.
    fn repack(
        repo: &Repository,
        repo_path: &Path,
        destructive_prune: bool,
        loose_objects: &[(Oid, PathBuf)],
        packs_before: &HashSet<PathBuf>,
    ) -> Result<MaintenanceReport, AppError> {
        let odb = repo.odb()?;
        let mut pack_builder = repo.packbuilder()?;

        if destructive_prune {
            Self::insert_reachable_objects(repo, &mut pack_builder)?;
        } else {
            // Non-destructive mode: carry over every object in the store —
            // loose and packed, reachable or not. The ODB iterator visits
            // all backends; duplicates are deduplicated by the packbuilder.
            odb.foreach(|oid| pack_builder.insert_object(*oid, None).is_ok())?;
        }

        // Stream the pack straight into the ODB — this writes both the
        // .pack and its .idx under .git/objects/pack.
        let mut pack_writer = odb.packwriter()?;

        pack_builder.foreach(|chunk| {
            use std::io::Write;

            pack_writer.write_all(chunk).is_ok()
        })?;

        pack_writer.commit()?;

        let mut report = MaintenanceReport {
            packed_objects: pack_builder.object_count(),
            ..Default::default()
        };

        // From here on the new pack is durable; deletions are best-effort
        // (a leftover file is redundant data, not corruption).
        for (_, loose_path) in loose_objects {
            let _ = std::fs::remove_file(loose_path);
        }

        report.loose_objects_removed = loose_objects.len();

        // Empty fan-out directories are pruned best-effort (`remove_dir`
        // refuses non-empty directories).
        let fanout_dirs: HashSet<PathBuf> = loose_objects
            .iter()
            .filter_map(|(_, loose_path)| loose_path.parent().map(PathBuf::from))
            .collect();

        for fanout_dir in fanout_dirs {
            let _ = std::fs::remove_dir(fanout_dir);
        }

        // Superseded packs are identified by directory diff rather than by
        // predicting the new pack's name (a libgit2 implementation detail).
        // If no new stem appeared, the consolidated pack was byte-identical
        // to an existing one — possible when only unreachable garbage
        // accumulated since the last pass — and the ODB just rewrote that
        // file in place. In that case nothing is deleted: we cannot tell
        // which old pack is the keeper, and redundant packs are merely
        // wasteful, never wrong. The next pass after a real write (distinct
        // pack name guaranteed by the new commit) sweeps them.
        let packs_after = Self::enumerate_pack_stems(repo_path)?;
        let new_pack_appeared = packs_after.difference(packs_before).next().is_some();

        if new_pack_appeared {
            for stem in packs_before {
                // libgit2 writes only .pack/.idx, but a human running `git
                // repack` inside the repo may have produced auxiliary files
                // sharing the stem — remove those too, not just the pair.
                for extension in ["pack", "idx", "rev", "mtimes", "keep", "bitmap"] {
                    let _ = std::fs::remove_file(stem.with_extension(extension));
                }

                report.old_packs_removed += 1;
            }
        }

        Ok(report)
    }

    /// Feeds the packbuilder with the complete reachable object set: every
    /// commit reachable from any ref, plus all trees and blobs those commits
    /// reference. Objects *not* collected here are the ones a destructive
    /// prune drops, so this must err on the side of keeping things.
    fn insert_reachable_objects(
        repo: &Repository,
        pack_builder: &mut git2::PackBuilder<'_>,
    ) -> Result<(), AppError> {
        let mut revwalk = repo.revwalk()?;

        // Reachability roots: HEAD plus every ref. The service itself only
        // ever creates HEAD/master, but a human may have added branches or
        // tags while inspecting a repo — a destructive prune must honour
        // those, not silently corrupt them.
        revwalk.push_head()?;

        for reference in repo.references()?.flatten() {
            if let Ok(name) = reference.name() {
                let _ = revwalk.push_ref(name);
            }

            // `push_ref` peels an annotated tag down to its commit for the
            // walk; the tag *object* itself must be packed separately or the
            // ref would dangle after the prune.
            if let Some(oid) = reference.target() {
                if let Ok(object) = repo.find_object(oid, None) {
                    if object.kind() == Some(git2::ObjectType::Tag) {
                        let _ = pack_builder.insert_object(oid, None);
                    }
                }
            }
        }

        // Inserts every commit in the walk plus all trees and blobs they
        // reference, deduplicated — the complete reachable object set.
        pack_builder.insert_walk(&mut revwalk)?;

        Ok(())
    }

    /// Deletes the reflogs for HEAD and the branch it points at. Best-effort:
    /// a missing reflog is fine, and reflog loss is never worth failing a
    /// maintenance pass over.
    fn expire_reflogs(repo: &Repository) {
        // Resolve the branch name before deleting anything (`repo.head()`
        // resolves the HEAD symref to e.g. `refs/heads/master`).
        let branch_ref_name = repo
            .head()
            .ok()
            .and_then(|head_ref| head_ref.name().ok().map(str::to_owned));

        let _ = repo.reflog_delete("HEAD");

        if let Some(name) = branch_ref_name {
            tracing::trace!(reference = %name, "expiring reflog");

            let _ = repo.reflog_delete(&name);
        }
    }

    /// Lists the packfiles under `.git/objects/pack` as extension-less path
    /// stems (each pack is a family of files — `.pack`, `.idx`, ... —
    /// sharing one stem).
    fn enumerate_pack_stems(repo_path: &Path) -> Result<HashSet<PathBuf>, AppError> {
        let pack_dir = repo_path.join(".git").join("objects").join("pack");
        let mut stems: HashSet<PathBuf> = HashSet::new();

        // A repository that has never been packed has no pack directory.
        let entries = match std::fs::read_dir(&pack_dir) {
            Ok(entries) => entries,
            Err(_) => return Ok(stems),
        };

        for entry in entries.flatten() {
            let path = entry.path();

            if path.extension().and_then(|extension| extension.to_str()) == Some("pack") {
                stems.insert(path.with_extension(""));
            }
        }

        Ok(stems)
    }

    /// Walks `.git/objects/` and returns every loose object with its file
    /// path. Non-object entries (`pack/`, `info/`, temporary files) are
    /// skipped by the hex-name filters.
    ///
    /// Loose objects live at `.git/objects/<2-hex-chars>/<38-hex-chars>` —
    /// the object's SHA split after two characters (the "fan-out" scheme
    /// that keeps any single directory from holding every object).
    /// Re-joining the directory name and file name reconstructs the oid.
    fn enumerate_loose_objects(repo_path: &Path) -> Result<Vec<(Oid, PathBuf)>, AppError> {
        let objects_dir = repo_path.join(".git").join("objects");
        let mut loose_objects: Vec<(Oid, PathBuf)> = Vec::new();

        let fanout_entries = match std::fs::read_dir(&objects_dir) {
            Ok(entries) => entries,
            Err(_) => return Ok(loose_objects),
        };

        for fanout_entry in fanout_entries.flatten() {
            let fanout_name = fanout_entry.file_name();

            let Some(prefix) = fanout_name.to_str() else {
                continue;
            };

            if prefix.len() != 2 || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                continue;
            }

            let Ok(object_entries) = std::fs::read_dir(fanout_entry.path()) else {
                continue;
            };

            for object_entry in object_entries.flatten() {
                let object_name = object_entry.file_name();

                let Some(suffix) = object_name.to_str() else {
                    continue;
                };

                if let Ok(oid) = Oid::from_str(&format!("{}{}", prefix, suffix)) {
                    loose_objects.push((oid, object_entry.path()));
                }
            }
        }

        Ok(loose_objects)
    }
}

// ---------------------------------------------------------------------------
// GitFiles — file CRUD operations
// ---------------------------------------------------------------------------

pub struct GitFiles;

impl GitFiles {
    /// Lists the repository as a tree of `TreeNode`s, rooted at
    /// `path_prefix` (or the repo root), paginated over root-level entries,
    /// and optionally depth-limited.
    ///
    /// When `file_name_starts_with` is set, the listing is narrowed to files
    /// whose leaf name begins with any of those prefixes (case-insensitively);
    /// see `search_by_file_name` for the exact semantics. In that mode the
    /// "off-page directories are never walked" optimisation below does not
    /// apply — matches can be nested anywhere, so the whole in-scope tree is
    /// walked before pagination.
    ///
    /// The performance contract (search mode aside): **no blob is ever
    /// opened**. Names and entry kinds come entirely from git tree objects,
    /// so listing cost scales with the number of tree entries actually
    /// visited — and the pagination below is designed to keep that number
    /// small even on huge repositories.
    pub fn list_files(
        repo_path: &Path,
        tenant_id: &str,
        path_prefix: Option<&str>,
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        file_name_starts_with: Option<&[String]>,
        page: usize,
        per_page: usize,
    ) -> Result<(Vec<TreeNode>, bool), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, file_name_starts_with = ?file_name_starts_with, page = page, per_page = per_page, "listing files");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for file listing");

        let head_tree = head_commit.tree()?;

        // Resolve the prefix subtree directly so the walk never visits unrelated
        // directories. An absent or non-directory prefix yields an empty result.
        let walk_tree: git2::Tree<'_> = match path_prefix.filter(|p| !p.is_empty()) {
            Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
                Ok(entry) => match repo.find_tree(entry.id()) {
                    Ok(tree) => tree,
                    Err(_) => return Ok((vec![], false)),
                },
                Err(_) => return Ok((vec![], false)),
            },
            None => head_tree,
        };

        // Name search takes a different route entirely: matches may be nested
        // arbitrarily deep, so the "decide the page window before opening any
        // subtree" optimisation cannot hold — the in-scope tree is walked in
        // full, then the *filtered* result is paginated.
        if let Some(needles) = file_name_starts_with {
            return Self::search_by_file_name(
                &walk_tree,
                needles,
                maximum_depth,
                include_hidden_files,
                page,
                per_page,
            );
        }

        // The listing root's immediate entries are already in memory as part
        // of the tree object — no further object reads are needed to
        // enumerate them. Sorting mirrors the response order (directories
        // first, then files, both alphabetical), so the page window is
        // decided before a single subtree is opened: off-page directories
        // are never visited at all.
        let mut root_dirs: Vec<(String, Oid)> = Vec::new();
        let mut root_files: Vec<String> = Vec::new();

        for entry in walk_tree.iter() {
            let Ok(name) = entry.name() else {
                continue;
            };

            // Hidden entries (Unix dot convention) are dropped before the
            // page window is computed, so pagination counts visible entries
            // only. Hidden directories are pruned wholesale: their subtrees
            // are never opened.
            if !include_hidden_files && name.starts_with('.') {
                continue;
            }

            match entry.kind() {
                Some(git2::ObjectType::Tree) => root_dirs.push((name.to_string(), entry.id())),
                Some(git2::ObjectType::Blob) => root_files.push(name.to_string()),
                _ => {}
            }
        }

        root_dirs.sort_by(|left, right| left.0.cmp(&right.0));
        root_files.sort();

        // Page arithmetic over the combined (dirs-then-files) root sequence.
        // `has_more` comes from the total count directly — no "fetch one
        // extra" trick needed here since all root names are already known.
        let total = root_dirs.len() + root_files.len();
        let offset = ((page - 1) * per_page).min(total);
        let has_more = total > offset + per_page;

        enum RootEntry {
            Directory(String, Oid),
            File(String),
        }

        let page_entries: Vec<RootEntry> = root_dirs
            .into_iter()
            .map(|(name, oid)| RootEntry::Directory(name, oid))
            .chain(root_files.into_iter().map(RootEntry::File))
            .skip(offset)
            .take(per_page)
            .collect();

        let mut nodes: Vec<TreeNode> = Vec::with_capacity(page_entries.len());

        for root_entry in page_entries {
            match root_entry {
                RootEntry::File(name) => nodes.push(TreeNode::File { name }),
                RootEntry::Directory(name, oid) => {
                    // maximum_depth counts levels from the listing root, so a
                    // depth-1 listing renders every directory as a childless
                    // stub without opening its subtree.
                    if maximum_depth == Some(1) {
                        nodes.push(TreeNode::Directory {
                            name,
                            children: Vec::new(),
                        });

                        continue;
                    }

                    let subtree = repo.find_tree(oid)?;

                    // Depth limits below are relative to this subtree, which
                    // sits one level down from the listing root.
                    let subtree_max_depth = maximum_depth.map(|max| max - 1);
                    let children =
                        Self::collect_subtree(&subtree, subtree_max_depth, include_hidden_files)?;

                    nodes.push(TreeNode::Directory { name, children });
                }
            }
        }

        tracing::debug!(tenant_id = %tenant_id, page = page, returned = nodes.len(), has_more = has_more, "file listing complete");

        Ok((nodes, has_more))
    }

    /// Recursively walks one paged root directory and builds its child nodes.
    /// Only directories inside the requested page window ever reach this
    /// point. Blob objects are never opened — names and kinds come from the
    /// tree objects alone.
    fn collect_subtree(
        subtree: &git2::Tree<'_>,
        max_depth: Option<usize>,
        include_hidden_files: bool,
    ) -> Result<Vec<TreeNode>, AppError> {
        let mut flat: Vec<String> = Vec::new();
        let mut dir_stubs: Vec<String> = Vec::new();

        subtree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            // Hidden entries (Unix dot convention) are excluded at the walk
            // level: `Skip` prunes a hidden directory's whole subtree, so
            // libgit2 never descends into it.
            if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
                return if entry.kind() == Some(git2::ObjectType::Tree) {
                    git2::TreeWalkResult::Skip
                } else {
                    git2::TreeWalkResult::Ok
                };
            }

            // Depth of this entry relative to the subtree: "" = depth 1, "a/" = depth 2, …
            let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;

            if entry.kind() == Some(git2::ObjectType::Tree) {
                if let Some(max) = max_depth {
                    if entry_depth >= max {
                        // Record as a stub and skip descending.
                        let name = entry.name().unwrap_or("");
                        dir_stubs.push(format!("{}{}", root, name));
                        return git2::TreeWalkResult::Skip;
                    }
                }
                return git2::TreeWalkResult::Ok;
            }

            if entry.kind() != Some(git2::ObjectType::Blob) {
                return git2::TreeWalkResult::Ok;
            }

            let name = entry.name().unwrap_or("");
            flat.push(format!("{}{}", root, name));

            git2::TreeWalkResult::Ok
        })?;

        Ok(GitUtils::build_tree(flat, dir_stubs, max_depth))
    }

    /// Walks `walk_tree` in full and returns the tree of entries whose *leaf
    /// name* begins with any of `needles`, compared case-insensitively (Unicode
    /// lower-casing, so `Intro` matches `intro.md`). Both files *and*
    /// directories are matched:
    ///
    /// - a matching **file** is returned as a leaf, with its ancestor
    ///   directories present purely as the structure leading to it;
    /// - a matching **directory** is returned with its whole subtree expanded
    ///   (every descendant file, whether or not its own name matches), so the
    ///   caller sees what is inside the folder they searched for.
    ///
    /// A directory that neither matches nor contains a match is pruned, so the
    /// result never carries a dead-end empty directory (a matched directory
    /// whose only visible content is filtered out still shows, as a childless
    /// node — it is itself the match).
    ///
    /// `maximum_depth` and `include_hidden_files` carry the same meaning as on
    /// the plain listing, and bound the whole operation uniformly: descent
    /// stops at the depth limit — a match deeper than it is never found, and a
    /// directory sitting *at* the limit renders as a childless stub even when
    /// it matched (exactly as the plain listing stubs depth-limited
    /// directories) — and hidden entries are skipped, a hidden directory's
    /// whole subtree along with them. Pagination is parent-based, as
    /// everywhere else: `page`/`per_page` window over the matched tree's
    /// root-level entries. Same performance contract otherwise — **no blob is
    /// ever opened**, matching is on names alone.
    fn search_by_file_name(
        walk_tree: &git2::Tree<'_>,
        needles: &[String],
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        page: usize,
        per_page: usize,
    ) -> Result<(Vec<TreeNode>, bool), AppError> {
        let needles: Vec<String> = needles.iter().map(|needle| needle.to_lowercase()).collect();
        let mut flat: Vec<String> = Vec::new();
        let mut dir_stubs: Vec<String> = Vec::new();

        // While walking inside a directory whose name matched, this holds that
        // directory's path with a trailing slash. Every descendant is then
        // collected unconditionally (the whole matched subtree is expanded);
        // the trailing slash keeps the prefix test from leaking across sibling
        // names (`docs/` must not swallow `docs2/`). Cleared the moment the
        // pre-order walk steps back out of that subtree.
        let mut inside_matched: Option<String> = None;

        walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            // Left the matched subtree? (Pre-order visits all of a directory's
            // descendants contiguously, so one prefix test per entry suffices.)
            if let Some(prefix) = &inside_matched {
                if !root.starts_with(prefix.as_str()) {
                    inside_matched = None;
                }
            }

            // Hidden entries (Unix dot convention) are excluded at the walk
            // level, even inside a matched subtree: `Skip` prunes a hidden
            // directory's whole subtree, so libgit2 never descends into it.
            if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
                return if entry.kind() == Some(git2::ObjectType::Tree) {
                    git2::TreeWalkResult::Skip
                } else {
                    git2::TreeWalkResult::Ok
                };
            }

            let Ok(name) = entry.name() else {
                return git2::TreeWalkResult::Ok;
            };
            let full_path = format!("{}{}", root, name);
            let in_matched = inside_matched.is_some();
            let lower_name = name.to_lowercase();
            let self_matches = needles.iter().any(|needle| lower_name.starts_with(needle));

            match entry.kind() {
                Some(git2::ObjectType::Tree) => {
                    let matched = in_matched || self_matches;

                    // Depth of this entry relative to the listing root:
                    // "" = depth 1, "a/" = depth 2, … A directory sitting at
                    // the depth limit is not descended into; when it is part
                    // of the result (it or an ancestor matched) it renders as
                    // a childless stub, mirroring the plain listing.
                    if let Some(max) = maximum_depth {
                        let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;

                        if entry_depth >= max {
                            if matched {
                                dir_stubs.push(full_path);
                            }

                            return git2::TreeWalkResult::Skip;
                        }
                    }

                    // Entering a freshly matched directory: record it so its
                    // descendants are collected wholesale, and stub it so it
                    // still appears if every descendant turns out hidden.
                    if self_matches && !in_matched {
                        inside_matched = Some(format!("{}/", full_path));
                        dir_stubs.push(full_path);
                    }
                }
                Some(git2::ObjectType::Blob) => {
                    if in_matched || self_matches {
                        flat.push(full_path);
                    }
                }
                _ => {}
            }

            git2::TreeWalkResult::Ok
        })?;

        // The walk already bounded depth, so every collected path is within
        // scope and `build_tree` needs no depth handling of its own (`None`);
        // the stubs it receives are matched directories that were not (or
        // could not be) expanded. The matched tree is then paginated over its
        // root-level entries, exactly like the plain listing.
        let tree = GitUtils::build_tree(flat, dir_stubs, None);

        let total = tree.len();
        let offset = ((page - 1) * per_page).min(total);
        let has_more = total > offset + per_page;

        let nodes: Vec<TreeNode> = tree.into_iter().skip(offset).take(per_page).collect();

        Ok((nodes, has_more))
    }

    /// Counts files and directories reachable from the listing root, with
    /// the exact scoping semantics of `list_files`: `path_prefix` roots the
    /// count at a sub-directory (absent or non-directory prefix yields zero
    /// counts), `maximum_depth` bounds how many levels are descended
    /// (directories sitting at the limit are counted but never entered),
    /// and hidden entries are excluded unless `include_hidden_files` is set
    /// (a hidden directory's whole subtree is pruned).
    ///
    /// `restrict_file_extensions`, when set, narrows the *file* count to
    /// files carrying one of the given extensions (compared
    /// case-insensitively; extension-less files never match). Directories
    /// are counted regardless — they have no extension to compare.
    ///
    /// Same performance contract as the listing: **no blob is ever opened**.
    /// Names and entry kinds come entirely from git tree objects.
    pub fn count_files(
        repo_path: &Path,
        tenant_id: &str,
        path_prefix: Option<&str>,
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        restrict_file_extensions: Option<&[String]>,
    ) -> Result<FileCounts, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, restrict_file_extensions = ?restrict_file_extensions, "counting files");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for file counting");

        let head_tree = head_commit.tree()?;

        // Resolve the prefix subtree directly so the walk never visits unrelated
        // directories. An absent or non-directory prefix yields zero counts.
        let walk_tree: git2::Tree<'_> = match path_prefix.filter(|p| !p.is_empty()) {
            Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
                Ok(entry) => match repo.find_tree(entry.id()) {
                    Ok(tree) => tree,
                    Err(_) => return Ok(FileCounts::default()),
                },
                Err(_) => return Ok(FileCounts::default()),
            },
            None => head_tree,
        };

        let mut counts = FileCounts::default();

        walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            // Hidden entries (Unix dot convention) are excluded at the walk
            // level: `Skip` prunes a hidden directory's whole subtree, so
            // libgit2 never descends into it.
            if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
                return if entry.kind() == Some(git2::ObjectType::Tree) {
                    git2::TreeWalkResult::Skip
                } else {
                    git2::TreeWalkResult::Ok
                };
            }

            match entry.kind() {
                Some(git2::ObjectType::Tree) => {
                    counts.directories += 1;

                    // Depth of this entry relative to the listing root:
                    // "" = depth 1, "a/" = depth 2, … A directory sitting at
                    // the depth limit is counted (it exists at a visible
                    // level, matching the listing's childless stubs) but its
                    // subtree is never entered.
                    if let Some(max) = maximum_depth {
                        let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;

                        if entry_depth >= max {
                            return git2::TreeWalkResult::Skip;
                        }
                    }
                }
                Some(git2::ObjectType::Blob) => {
                    let counted = match restrict_file_extensions {
                        None => true,
                        Some(allowed) => entry
                            .name()
                            .ok()
                            .and_then(|name| Path::new(name).extension())
                            .and_then(|extension| extension.to_str())
                            .is_some_and(|extension| {
                                allowed
                                    .iter()
                                    .any(|entry| entry.eq_ignore_ascii_case(extension))
                            }),
                    };

                    if counted {
                        counts.files += 1;
                    }
                }
                _ => {}
            }

            git2::TreeWalkResult::Ok
        })?;

        tracing::debug!(tenant_id = %tenant_id, files = counts.files, directories = counts.directories, "file counting complete");

        Ok(counts)
    }

    /// Returns the file content as recorded in HEAD's tree (not from the working
    /// tree) so the response always reflects the last successfully committed state.
    ///
    /// A path resolving to a folder answers the same 404 as a missing file —
    /// consistent with the HEAD existence endpoint. See
    /// `GitUtils::windowed_blob_content` for how seek windows are read.
    pub fn read_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
        seek: &SeekFilter,
    ) -> Result<String, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, "reading file");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, head_sha = %head_commit.id(), "resolved HEAD for read");

        let head_tree = head_commit.tree()?;

        let blob_oid = GitUtils::blob_oid_in_tree(&head_tree, file_path).ok_or_else(|| {
            AppError::FileNotFound {
                path: file_path.to_string(),
            }
        })?;

        GitUtils::windowed_blob_content(&repo, blob_oid, file_path, seek)
    }

    /// Reads several files from HEAD's tree in one repository pass. The
    /// returned vector is index-aligned with `file_reads`: `None` marks a
    /// path that is absent (or a folder), `Some` carries the content with
    /// that entry's seek window applied (the route resolves each entry's
    /// effective window upfront). Unreadable content (invalid UTF-8) is a
    /// hard error for the whole batch, so `None` strictly means "not
    /// found".
    pub fn batch_read_files(
        repo_path: &Path,
        tenant_id: &str,
        file_reads: &[(String, SeekFilter)],
    ) -> Result<Vec<Option<String>>, AppError> {
        tracing::debug!(tenant_id = %tenant_id, count = file_reads.len(), "batch reading files");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for batch read");

        let head_tree = head_commit.tree()?;

        file_reads
            .iter()
            .map(
                |(file_path, seek)| match GitUtils::blob_oid_in_tree(&head_tree, file_path) {
                    None => Ok(None),

                    Some(blob_oid) => {
                        GitUtils::windowed_blob_content(&repo, blob_oid, file_path, seek).map(Some)
                    }
                },
            )
            .collect()
    }

    /// Checks that a file exists in HEAD's tree without reading its content.
    /// Returns `FileNotFound` when the path is absent or resolves to a folder.
    pub fn file_exists(repo_path: &Path, tenant_id: &str, file_path: &str) -> Result<(), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, "checking file existence");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, head_sha = %head_commit.id(), "resolved HEAD for existence check");

        let head_tree = head_commit.tree()?;

        let tree_entry =
            head_tree
                .get_path(Path::new(file_path))
                .map_err(|_err| AppError::FileNotFound {
                    path: file_path.to_string(),
                })?;

        if tree_entry.kind() != Some(git2::ObjectType::Blob) {
            return Err(AppError::FileNotFound {
                path: file_path.to_string(),
            });
        }

        Ok(())
    }

    /// Writes a file to disk, stages it, and creates a commit.
    /// Returns the commit SHA and the type of change (created vs updated).
    ///
    /// Writing content identical to what HEAD already holds is a no-op:
    /// no commit is created, nothing touches disk, and the change slot is
    /// `None` so the caller knows not to fire hooks. Clients that blindly
    /// re-PUT unchanged files thus cannot pollute history with empty
    /// commits. The comparison hashes the incoming content and compares
    /// blob oids, so the existing blob is never even read.
    ///
    /// Order of operations matters: the working-tree write happens *before*
    /// the commit, so if the process dies in between, HEAD still points at
    /// the last good commit and the stray on-disk file is harmless (it will
    /// simply be overwritten or ignored — never committed — because commit
    /// trees are built from HEAD, not from disk).
    pub fn write_file(
        repo_path: &Path,
        file_path: &str,
        content: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, Option<FileChange>), AppError> {
        tracing::debug!(path = %file_path, author_name = %author_name, author_email = %author_email, "writing file");

        let repo = GitUtils::open_or_init_repo(repo_path, author_name, author_email)?;

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree,
        // so leftovers from a previously failed operation cannot change the
        // outcome (created vs updated) or the hook event that is emitted.
        // Writing *onto* a directory path is rejected outright — git would
        // technically allow replacing a tree with a blob, but for a CMS that
        // is almost certainly a caller mistake that would delete a whole
        // folder of content in one PUT.
        let is_new_file = match head_tree.get_path(Path::new(file_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => {
                // Hashing the incoming content yields the oid the new blob
                // *would* get; if it matches the entry already in HEAD, the
                // write changes nothing and short-circuits before any disk
                // or object-database activity.
                let incoming_oid =
                    git2::Oid::hash_object(git2::ObjectType::Blob, content.as_bytes())?;

                if entry.id() == incoming_oid {
                    tracing::debug!(path = %file_path, "content unchanged, skipping commit");

                    return Ok((parent_commit.id().to_string(), None));
                }

                false
            }
            Ok(_) => {
                return Err(AppError::InvalidOperation {
                    reason: format!("path is a folder: {}", file_path),
                })
            }
            Err(_) => true,
        };

        tracing::debug!(path = %file_path, is_new_file = is_new_file, "staging file write");

        let absolute_path = repo_path.join(file_path);

        if let Some(parent_dir) = absolute_path.parent() {
            std::fs::create_dir_all(parent_dir)?;
        }

        std::fs::write(&absolute_path, content)?;

        tracing::trace!(path = %file_path, "building updated tree");

        // The commit tree is HEAD's tree plus this single change — O(path
        // depth) instead of the O(repository size) an index round-trip costs,
        // and stray state from a failed past operation can never leak in.
        let blob_oid = repo.blob(content.as_bytes())?;

        let tree_id = TreeUpdateBuilder::new()
            .upsert(file_path, blob_oid, FileMode::Blob)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = if is_new_file {
            format!("create: {}", file_path)
        } else {
            format!("update: {}", file_path)
        };
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(path = %file_path, message = %message, "committing file write");

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(path = %file_path, sha = %commit_oid, is_new_file = is_new_file, "file write committed");

        let change = if is_new_file {
            FileChange::Created {
                path: file_path.to_string(),
                content: content.to_string(),
            }
        } else {
            FileChange::Updated {
                path: file_path.to_string(),
                content: content.to_string(),
            }
        };

        Ok((commit_oid.to_string(), Some(change)))
    }

    /// Removes a file from disk, stages the deletion, and creates a commit.
    ///
    /// Unlike `write_file`, this opens the repo with `open_tenant_repo` (no
    /// auto-init): deleting a file from a tenant that never existed is a
    /// 404, not a reason to create an empty repository.
    pub fn delete_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, FileChange), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, author_name = %author_name, author_email = %author_email, "deleting file");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree.
        match head_tree.get_path(Path::new(file_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => {}
            _ => {
                tracing::debug!(tenant_id = %tenant_id, path = %file_path, "file not found for deletion");

                return Err(AppError::FileNotFound {
                    path: file_path.to_string(),
                });
            }
        }

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, "building updated tree without path");

        // A file already missing from the working tree just means the working
        // tree had diverged from HEAD; there is nothing left to clean up.
        let absolute_path = repo_path.join(file_path);

        match std::fs::remove_file(&absolute_path) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(AppError::Io(err)),
        }

        // The commit tree is HEAD's tree minus this single entry — O(path
        // depth) instead of the O(repository size) an index round-trip costs.
        let tree_id = TreeUpdateBuilder::new()
            .remove(file_path)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("delete: {}", file_path);
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, message = %message, "committing file deletion");

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(tenant_id = %tenant_id, path = %file_path, sha = %commit_oid, "file deletion committed");

        Ok((
            commit_oid.to_string(),
            FileChange::Deleted {
                path: file_path.to_string(),
            },
        ))
    }

    /// Renames a file on disk, stages both sides, and creates a single commit.
    /// This preserves rename semantics so hook receivers know an entity was moved.
    ///
    /// Doing the remove and the insert in *one* commit is the whole point:
    /// two separate commits (delete + create) would fire two hooks and make
    /// the downstream receiver treat the file as a brand-new entity, losing
    /// whatever metadata it had attached to the old path.
    pub fn move_file(
        repo_path: &Path,
        tenant_id: &str,
        from_path: &str,
        to_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, FileChange), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            author_email = %author_email,
            "moving file"
        );

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        if from_path == to_path {
            tracing::debug!(tenant_id = %tenant_id, path = %from_path, "move rejected: source and destination are identical");

            return Err(AppError::InvalidOperation {
                reason: "destination must differ from source path".to_string(),
            });
        }

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree.
        // The blob oid is kept so the destination entry reuses it verbatim.
        let source_blob_oid = match head_tree.get_path(Path::new(from_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => entry.id(),
            _ => {
                tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source file not found for move");

                return Err(AppError::FileNotFound {
                    path: from_path.to_string(),
                });
            }
        };

        // Refuse to clobber an existing destination — the user must delete first.
        if head_tree.get_path(Path::new(to_path)).is_ok() {
            tracing::debug!(tenant_id = %tenant_id, to_path = %to_path, "move rejected: destination already exists");

            return Err(AppError::InvalidOperation {
                reason: format!("destination already exists: {}", to_path),
            });
        }

        // The moved content comes from HEAD's blob — the authoritative state —
        // rather than whatever the working tree currently holds.
        let content = GitUtils::blob_content_from_tree(&repo, &head_tree, from_path)?;

        let absolute_from = repo_path.join(from_path);
        let absolute_to = repo_path.join(to_path);

        match std::fs::remove_file(&absolute_from) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(AppError::Io(err)),
        }

        if let Some(parent_dir) = absolute_to.parent() {
            std::fs::create_dir_all(parent_dir)?;
        }

        std::fs::write(&absolute_to, &content)?;

        tracing::trace!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            "building updated tree for move"
        );

        // The commit tree is HEAD's tree with the entry relocated, reusing the
        // existing blob — no content rehash, no index round-trip.
        let tree_id = TreeUpdateBuilder::new()
            .remove(from_path)
            .upsert(to_path, source_blob_oid, FileMode::Blob)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("move: {} -> {}", from_path, to_path);
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            message = %message,
            "committing file move"
        );

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            sha = %commit_oid,
            "file move committed"
        );

        Ok((
            commit_oid.to_string(),
            FileChange::Moved {
                from_path: from_path.to_string(),
                to_path: to_path.to_string(),
                content,
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// GitCommits — commit history and revert
// ---------------------------------------------------------------------------

pub struct GitCommits;

impl GitCommits {
    /// Lists commits newest-first, paginated. With a `file_path` filter the
    /// work is delegated to [`Self::list_commits_by_file`], which follows
    /// the file backward through renames.
    pub fn list_commits(
        repo_path: &Path,
        tenant_id: &str,
        page: usize,
        per_page: usize,
        file_path: Option<&str>,
        include_statistics: bool,
    ) -> Result<(Vec<CommitSummary>, bool), AppError> {
        if let Some(path) = file_path {
            return Self::list_commits_by_file(
                repo_path,
                tenant_id,
                page,
                per_page,
                path,
                include_statistics,
            );
        }

        tracing::debug!(tenant_id = %tenant_id, page = page, per_page = per_page, include_statistics = include_statistics, "listing commits");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let mut revwalk = repo.revwalk()?;

        revwalk.push_head()?;

        // TIME | TOPOLOGICAL gives stable ordering across commits sharing a timestamp.
        revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;

        let skip_count = page.saturating_sub(1).saturating_mul(per_page);

        tracing::trace!(tenant_id = %tenant_id, skip_count = skip_count, per_page = per_page, "walking commit graph");

        // Fetch one extra to detect whether a next page exists without a full count.
        // When line stats are requested, that extra commit is diffed too — one
        // wasted diff per page is an acceptable trade for keeping this branch
        // free of a second, stats-only pass.
        let mut commits: Vec<CommitSummary> = revwalk
            .skip(skip_count)
            .take(per_page + 1)
            .filter_map(|oid_result| oid_result.ok())
            .filter_map(|oid| repo.find_commit(oid).ok())
            .map(|commit| {
                let statistics = if include_statistics {
                    Some(Self::statistics_for_commit(&repo, &commit)?)
                } else {
                    None
                };

                Ok(CommitSummary {
                    sha: commit.id().to_string(),
                    message: commit.message().unwrap_or("").to_string(),
                    author: CommitAuthor {
                        name: commit.author().name().unwrap_or("").to_string(),
                        email: commit.author().email().unwrap_or("").to_string(),
                    },
                    committed_at: GitUtils::timestamp_from_git_time(commit.time()),
                    statistics,
                })
            })
            .collect::<Result<Vec<CommitSummary>, AppError>>()?;

        let has_more = commits.len() > per_page;

        commits.truncate(per_page);

        tracing::debug!(tenant_id = %tenant_id, page = page, returned = commits.len(), has_more = has_more, "commit listing complete");

        Ok((commits, has_more))
    }

    /// Walks the commit graph from HEAD, diffing each commit against its parent
    /// with rename detection enabled, and collects only commits that touched
    /// `file_path` (following the file backward through any renames).
    ///
    /// Pagination is applied after matching: we collect up to
    /// `(page-1)*per_page + per_page + 1` matching commits, then slice.
    ///
    /// How the walk stays cheap: for each commit, two O(path depth) tree
    /// lookups (does the file exist in this commit? in its parent? same
    /// oid?) decide whether the commit touched the file. This answers the
    /// overwhelmingly common "untouched" case without ever loading content.
    /// Only when a commit *introduced* the path (present in commit, absent
    /// in parent) is a full rename-detecting diff computed, to distinguish
    /// "created here" from "renamed from an older path" — and in the rename
    /// case, `current_path` is rewritten so the walk keeps following the
    /// file under its previous name.
    fn list_commits_by_file(
        repo_path: &Path,
        tenant_id: &str,
        page: usize,
        per_page: usize,
        file_path: &str,
        include_statistics: bool,
    ) -> Result<(Vec<CommitSummary>, bool), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            page = page,
            per_page = per_page,
            file_path = %file_path,
            include_statistics = include_statistics,
            "listing commits by file path"
        );

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let mut revwalk = repo.revwalk()?;

        revwalk.push_head()?;
        revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;

        let skip_count = page.saturating_sub(1).saturating_mul(per_page);
        // Collect one extra beyond what we need so we can detect has_more.
        let need = skip_count + per_page + 1;

        // The name of the file we are tracking. Updated when we cross a rename.
        let mut current_path = file_path.to_string();
        let mut matching: Vec<CommitSummary> = Vec::new();

        for oid_result in revwalk {
            if matching.len() >= need {
                break;
            }

            let oid = match oid_result {
                Ok(id) => id,
                Err(_) => continue,
            };

            let commit = match repo.find_commit(oid) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let commit_tree = match commit.tree() {
                Ok(t) => t,
                Err(_) => continue,
            };

            // For the root commit there is no parent tree to diff against — the
            // file is "created" here if it exists in the tree under the current name.
            let (is_match, rename_from) = if commit.parent_count() == 0 {
                let exists = commit_tree.get_path(Path::new(&current_path)).is_ok();

                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %commit.id(),
                    path = %current_path,
                    exists = exists,
                    "checking root commit for file"
                );

                (exists, None)
            } else {
                let parent_tree = match commit.parent(0).and_then(|p| p.tree()) {
                    Ok(t) => t,
                    Err(_) => continue,
                };

                // Two O(path depth) tree lookups decide whether this commit
                // touched the file at all. A rename-detecting diff (which loads
                // blob contents to score similarity) is only computed for the
                // rare commit that introduced the file under its current name.
                let commit_entry = commit_tree.get_path(Path::new(&current_path)).ok();
                let parent_entry = parent_tree.get_path(Path::new(&current_path)).ok();

                match (commit_entry, parent_entry) {
                    // Untouched by this commit — the overwhelmingly common case.
                    (Some(in_commit), Some(in_parent))
                        if in_commit.id() == in_parent.id()
                            && in_commit.filemode() == in_parent.filemode() =>
                    {
                        (false, None)
                    }
                    // Modified in this commit.
                    (Some(_), Some(_)) => (true, None),
                    // Deleted by this commit (the file was re-created later).
                    (None, Some(_)) => (true, None),
                    // Not present under this name on either side.
                    (None, None) => (false, None),
                    // Introduced by this commit — either created, or renamed
                    // from an older path that must be followed backward.
                    (Some(_), None) => (
                        true,
                        Self::rename_source(&repo, &parent_tree, &commit_tree, &current_path),
                    ),
                }
            };

            if is_match {
                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %commit.id(),
                    path = %current_path,
                    "commit matched file path filter"
                );

                matching.push(CommitSummary {
                    sha: commit.id().to_string(),
                    message: commit.message().unwrap_or("").to_string(),
                    author: CommitAuthor {
                        name: commit.author().name().unwrap_or("").to_string(),
                        email: commit.author().email().unwrap_or("").to_string(),
                    },
                    committed_at: GitUtils::timestamp_from_git_time(commit.time()),
                    statistics: None,
                });

                if let Some(old_name) = rename_from {
                    current_path = old_name;
                }
            }
        }

        let has_more = matching.len() > skip_count + per_page;

        // Line stats are only computed for the final page window, not for
        // every matching commit found while walking history — the match
        // scan already runs a rename-detecting diff per introduction, so
        // deferring this avoids doubling that cost across unpaginated rows.
        let commits: Vec<CommitSummary> = matching
            .into_iter()
            .skip(skip_count)
            .take(per_page)
            .map(|mut summary| {
                if include_statistics {
                    let oid = Oid::from_str(&summary.sha)?;
                    let commit = repo.find_commit(oid)?;

                    summary.statistics = Some(Self::statistics_for_commit(&repo, &commit)?);
                }

                Ok(summary)
            })
            .collect::<Result<Vec<CommitSummary>, AppError>>()?;

        tracing::debug!(
            tenant_id = %tenant_id,
            page = page,
            returned = per_page,
            has_more = has_more,
            "commit listing by file complete"
        );

        Ok((commits, has_more))
    }

    /// Runs a rename-detecting diff of a single commit and returns the prior
    /// path when `current_path` was renamed (rather than freshly created) by
    /// it. Only invoked for commits that introduced the file under its
    /// current name, so the similarity scan stays off the hot path.
    fn rename_source(
        repo: &Repository,
        parent_tree: &git2::Tree<'_>,
        commit_tree: &git2::Tree<'_>,
        current_path: &str,
    ) -> Option<String> {
        let mut diff_opts = DiffOptions::new();

        diff_opts.include_untracked(false);

        let mut diff = repo
            .diff_tree_to_tree(Some(parent_tree), Some(commit_tree), Some(&mut diff_opts))
            .ok()?;

        let mut find_opts = DiffFindOptions::new();

        find_opts.renames(true);

        diff.find_similar(Some(&mut find_opts)).ok()?;

        for index in 0..diff.deltas().count() {
            let Some(delta) = diff.get_delta(index) else {
                continue;
            };

            if delta.status() != Delta::Renamed {
                continue;
            }

            let new = delta
                .new_file()
                .path()
                .map(|path| path.to_string_lossy().into_owned());

            if new.as_deref() == Some(current_path) {
                let old = delta
                    .old_file()
                    .path()
                    .map(|path| path.to_string_lossy().into_owned());

                tracing::trace!(
                    from = ?old,
                    to = %current_path,
                    "rename detected, following path backward"
                );

                return old;
            }
        }

        None
    }

    /// Computes aggregate line-change stats for one commit against its first
    /// parent (or an empty tree for the root commit). Rename detection runs
    /// first so a pure rename doesn't count as a full delete+add of its
    /// content. Only called when a caller opts in via `include_statistics`,
    /// since it requires an actual content diff rather than the cheap
    /// oid/tree comparisons the rest of commit listing relies on.
    fn statistics_for_commit(
        repo: &Repository,
        commit: &git2::Commit,
    ) -> Result<CommitStatistics, AppError> {
        let commit_tree = commit.tree()?;

        let parent_tree = if commit.parent_count() > 0 {
            Some(commit.parent(0)?.tree()?)
        } else {
            None
        };

        let mut diff_options = DiffOptions::new();

        diff_options.include_untracked(false);

        let mut diff = repo.diff_tree_to_tree(
            parent_tree.as_ref(),
            Some(&commit_tree),
            Some(&mut diff_options),
        )?;

        let mut find_options = DiffFindOptions::new();

        find_options.renames(true);

        diff.find_similar(Some(&mut find_options))?;

        let stats = diff.stats()?;

        Ok(CommitStatistics {
            insertions: stats.insertions(),
            deletions: stats.deletions(),
            files_changed: stats.files_changed(),
        })
    }

    /// Builds the full detail view of one commit: metadata, and for every
    /// file it touched a change label, the post-commit content, and a
    /// unified diff. The `sha` may be abbreviated — the validation layer has
    /// already guaranteed it is plain hexadecimal, so the `revparse_single`
    /// call can only ever resolve it as an object id prefix, never as a
    /// revspec expression.
    pub fn get_commit(
        repo_path: &Path,
        tenant_id: &str,
        sha: &str,
    ) -> Result<CommitDetail, AppError> {
        tracing::debug!(tenant_id = %tenant_id, sha = %sha, "fetching commit detail");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let object = repo
            .revparse_single(sha)
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let commit = object
            .peel_to_commit()
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let commit_tree = commit.tree()?;

        // The root commit has no parent; diffing against `None` yields every
        // file in the commit as "created", which is exactly right.
        let parent_tree = if commit.parent_count() > 0 {
            Some(commit.parent(0)?.tree()?)
        } else {
            None
        };

        tracing::trace!(
            tenant_id = %tenant_id,
            sha = %sha,
            has_parent = parent_tree.is_some(),
            "diffing commit against parent"
        );

        let mut diff_options = DiffOptions::new();

        diff_options.include_untracked(false);

        let mut diff = repo.diff_tree_to_tree(
            parent_tree.as_ref(),
            Some(&commit_tree),
            Some(&mut diff_options),
        )?;

        // Enable rename detection so moved files are identified correctly.
        let mut find_options = DiffFindOptions::new();

        find_options.renames(true);

        diff.find_similar(Some(&mut find_options))?;

        let diff_stats = diff.stats()?;
        let statistics = CommitStatistics {
            insertions: diff_stats.insertions(),
            deletions: diff_stats.deletions(),
            files_changed: diff_stats.files_changed(),
        };

        let records: Vec<DeltaRecord> = (0..diff.deltas().count())
            .filter_map(|index| diff.get_delta(index))
            .map(|delta| {
                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %sha,
                    status = ?delta.status(),
                    old_path = ?delta.old_file().path(),
                    new_path = ?delta.new_file().path(),
                    "processing diff delta"
                );
                DeltaRecord {
                    status: delta.status(),
                    old_oid: delta.old_file().id(),
                    new_oid: delta.new_file().id(),
                    old_path: delta.old_file().path().map(PathBuf::from),
                    new_path: delta.new_file().path().map(PathBuf::from),
                }
            })
            .collect();

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = records.len(), "building per-file diffs");

        // Walk the entire patch once and route each line to its delta's bucket.
        // Linear scan via `position` is fine — commits hold a handful of files.
        // `diff.print` streams the whole patch through one callback with no
        // per-file grouping of its own, so each line is matched back to its
        // delta by the (old oid, new oid) pair.
        let mut per_file_diffs: Vec<String> = vec![String::new(); records.len()];

        diff.print(DiffFormat::Patch, |delta, _hunk, line| {
            let key = (delta.old_file().id(), delta.new_file().id());

            if let Some(idx) = records
                .iter()
                .position(|record| (record.old_oid, record.new_oid) == key)
            {
                let bucket = &mut per_file_diffs[idx];

                // Content lines get their +/-/space marker re-attached
                // (libgit2 strips it from `line.content()`); structural
                // lines (hunk headers, file headers) pass through as-is.
                match line.origin() {
                    '+' | '-' | ' ' | '\\' => bucket.push(line.origin()),
                    _ => {}
                }

                bucket.push_str(std::str::from_utf8(line.content()).unwrap_or(""));
            }

            true
        })?;

        let mut file_details: Vec<CommitFileDetail> = Vec::with_capacity(records.len());

        for (index, record) in records.iter().enumerate() {
            // Map git's Delta status onto the API's four change labels. The
            // catch-all arm collapses the exotic statuses (typechange,
            // copied, ...) into "updated" — for a store that only ever holds
            // regular text files they cannot meaningfully occur.
            let (change_label, file_path, from_path) = match record.status {
                Delta::Added => (
                    "created",
                    GitUtils::path_string(record.new_path.as_deref()),
                    None,
                ),
                Delta::Deleted => (
                    "deleted",
                    GitUtils::path_string(record.old_path.as_deref()),
                    None,
                ),
                Delta::Renamed => (
                    "moved",
                    GitUtils::path_string(record.new_path.as_deref()),
                    record
                        .old_path
                        .as_deref()
                        .map(|path| path.to_string_lossy().into_owned()),
                ),
                _ => (
                    "updated",
                    GitUtils::path_string(record.new_path.as_deref()),
                    None,
                ),
            };

            tracing::trace!(
                tenant_id = %tenant_id,
                sha = %sha,
                path = %file_path,
                change = %change_label,
                "assembling commit file detail"
            );

            let content = if record.status == Delta::Deleted {
                String::new()
            } else {
                GitUtils::blob_content_from_tree(&repo, &commit_tree, &file_path)?
            };

            file_details.push(CommitFileDetail {
                path: file_path,
                change: change_label.to_string(),
                from_path,
                content,
                diff: std::mem::take(&mut per_file_diffs[index]),
            });
        }

        // Materialise borrowed values before the struct literal so that the
        // `Signature` temporary returned by `commit.author()` is dropped while
        // `commit` (and the underlying `repo`) is still alive.
        let sha = commit.id().to_string();
        let message = commit.message().unwrap_or("").to_string();

        let author = CommitAuthor {
            name: commit.author().name().unwrap_or("").to_string(),
            email: commit.author().email().unwrap_or("").to_string(),
        };

        let committed_at = GitUtils::timestamp_from_git_time(commit.time());

        tracing::debug!(tenant_id = %tenant_id, sha = %sha, file_count = file_details.len(), "commit detail ready");

        Ok(CommitDetail {
            sha,
            message,
            author,
            committed_at,
            files: file_details,
            statistics,
        })
    }

    /// Reverts all changes introduced by the given commit by applying their inverse,
    /// then records the result as a new commit. Returns the new commit SHA and
    /// the list of file changes (for hook delivery).
    ///
    /// How the inverse is computed: diff `parent(target) → target` to learn
    /// what the target commit introduced, then apply each delta *backwards*
    /// on top of the **current HEAD** (added → remove, deleted → restore,
    /// modified → restore old version, renamed → rename back). Restored
    /// content and blob oids come from the target's parent tree — the exact
    /// pre-commit state — so no content is ever rehashed.
    ///
    /// Note this is a "blind" revert of the git-revert family: if commits
    /// *after* the target modified the same files, their changes are
    /// overwritten by the restored versions (last-write-wins, consistent
    /// with the rest of the API's semantics). Reverting the root commit is
    /// rejected since there is no parent state to restore.
    pub fn revert_commit(
        repo_path: &Path,
        tenant_id: &str,
        sha: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, sha = %sha, author_name = %author_name, author_email = %author_email, "reverting commit");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let object = repo
            .revparse_single(sha)
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let target_commit = object
            .peel_to_commit()
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        if target_commit.parent_count() == 0 {
            tracing::warn!(tenant_id = %tenant_id, sha = %sha, "cannot revert root commit");

            return Err(AppError::InvalidOperation {
                reason: "cannot revert the initial commit".to_string(),
            });
        }

        let parent_commit = target_commit.parent(0)?;
        let commit_tree = target_commit.tree()?;
        let parent_tree = parent_commit.tree()?;

        // Diff from parent → commit tells us what the commit introduced.
        // Reverting means applying each change in reverse.
        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "computing diff for revert");

        let mut diff = repo.diff_tree_to_tree(Some(&parent_tree), Some(&commit_tree), None)?;

        let mut find_options = DiffFindOptions::new();

        find_options.renames(true);

        diff.find_similar(Some(&mut find_options))?;

        let raw_deltas: Vec<DeltaRecord> = (0..diff.deltas().count())
            .filter_map(|index| diff.get_delta(index))
            .map(|delta| DeltaRecord {
                status: delta.status(),
                old_oid: delta.old_file().id(),
                new_oid: delta.new_file().id(),
                old_path: delta.old_file().path().map(PathBuf::from),
                new_path: delta.new_file().path().map(PathBuf::from),
            })
            .collect();

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = raw_deltas.len(), "applying revert deltas");

        let head_commit = repo.head()?.peel_to_commit()?;
        let head_tree = head_commit.tree()?;

        // The revert tree is HEAD's tree plus the inverse of each delta,
        // reusing parent-tree blob oids — no index round-trip, no rehashing.
        let mut tree_update = TreeUpdateBuilder::new();

        let mut file_changes: Vec<FileChange> = Vec::new();

        // For each delta: mirror the inverse change onto the working tree
        // (best-effort human-visible state), stage it into the tree builder
        // (the authoritative commit state), and record the corresponding
        // FileChange (drives one hook per file, in this order).
        for raw_delta in &raw_deltas {
            match raw_delta.status {
                Delta::Added => {
                    // Commit added this file → revert removes it.
                    if let Some(new_path) = &raw_delta.new_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %new_path.display(),
                            "revert: removing added file"
                        );

                        let absolute_path = repo_path.join(new_path);

                        if absolute_path.exists() {
                            std::fs::remove_file(&absolute_path)?;
                        }

                        tree_update.remove(new_path);

                        file_changes.push(FileChange::Deleted {
                            path: new_path.to_string_lossy().into_owned(),
                        });
                    }
                }
                Delta::Deleted => {
                    // Commit deleted this file → revert restores it from the parent tree.
                    if let Some(old_path) = &raw_delta.old_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %old_path.display(),
                            "revert: restoring deleted file"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_path = repo_path.join(old_path);

                        if let Some(parent_dir) = absolute_path.parent() {
                            std::fs::create_dir_all(parent_dir)?;
                        }

                        std::fs::write(&absolute_path, &content)?;

                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Created {
                            path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                Delta::Modified => {
                    // Commit modified this file → revert restores the old version.
                    if let Some(old_path) = &raw_delta.old_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %old_path.display(),
                            "revert: restoring modified file to previous version"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_path = repo_path.join(old_path);

                        std::fs::write(&absolute_path, &content)?;

                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Updated {
                            path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                Delta::Renamed => {
                    // Commit renamed old → new; revert renames new → old.
                    if let (Some(old_path), Some(new_path)) =
                        (&raw_delta.old_path, &raw_delta.new_path)
                    {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            from_path = %new_path.display(),
                            to_path = %old_path.display(),
                            "revert: reversing rename"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_old = repo_path.join(old_path);
                        let absolute_new = repo_path.join(new_path);

                        if absolute_new.exists() {
                            std::fs::remove_file(&absolute_new)?;
                        }

                        if let Some(parent_dir) = absolute_old.parent() {
                            std::fs::create_dir_all(parent_dir)?;
                        }

                        std::fs::write(&absolute_old, &content)?;

                        tree_update.remove(new_path);
                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Moved {
                            from_path: new_path.to_string_lossy().into_owned(),
                            to_path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                _ => {}
            }
        }

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "building revert tree and committing");

        let tree_id = tree_update.create_updated(&repo, &head_tree)?;
        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("revert: {}", target_commit.message().unwrap_or("unknown"));
        let revert_message = commit_message.unwrap_or(&auto_message);

        let new_commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            revert_message,
            &tree,
            &[&head_commit],
        )?;

        tracing::debug!(
            tenant_id = %tenant_id,
            reverted_sha = %sha,
            new_sha = %new_commit_oid,
            file_change_count = file_changes.len(),
            "revert committed"
        );

        Ok((new_commit_oid.to_string(), file_changes))
    }
}

// ---------------------------------------------------------------------------
// GitTenant — tenant repository lifecycle
// ---------------------------------------------------------------------------

pub struct GitTenant;

impl GitTenant {
    /// Permanently deletes a tenant's repository — working tree, `.git`
    /// directory, full history, everything. There is no soft-delete or
    /// trash: the API contract is that tenant deletion is irreversible.
    /// Must be called under the tenant write lock (the route handler holds
    /// it) so no commit can be in flight while the directory disappears.
    pub fn delete_repo(repo_path: &Path, tenant_id: &str) -> Result<(), AppError> {
        tracing::debug!(tenant_id = %tenant_id, "deleting tenant repository");

        if !repo_path.exists() {
            tracing::debug!(tenant_id = %tenant_id, "tenant repository not found for deletion");

            return Err(AppError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            });
        }

        std::fs::remove_dir_all(repo_path).map_err(|err| {
            tracing::error!(
                tenant_id = %tenant_id,
                path = %repo_path.display(),
                err = %err,
                "failed to remove tenant repository directory"
            );

            AppError::Io(err)
        })?;

        tracing::info!(tenant_id = %tenant_id, "tenant repository deleted");

        Ok(())
    }
}