githttp-fs 1.13.0

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
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
// 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
//! - `GitStaging` — tenant repositories created and deleted atomically, as
//!   far as a concurrent reader can tell
//! - `GitMaintenance` — consolidating repack, optional prune, reflog
//!   expiry, index refresh
//! - `GitFiles` — file CRUD (list / read / exists / write / delete / move)
//! - `GitOrder` — the per-directory file-order index (read / write / reorder
//!   one entry / delete, plus the implicit upkeep that keeps an index honest
//!   across file deletes and moves)
//! - `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::{CheckoutBuilder, TreeUpdateBuilder};
use git2::{
    Delta, DiffFindOptions, DiffFormat, DiffOptions, FileMode, Oid, Repository, Signature, Sort,
};
use serde::Serialize;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

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

/// 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>,
    },
}

impl TreeNode {
    /// The node's leaf name, whichever kind it is. Used to rank a node against
    /// a directory's stored order.
    fn name(&self) -> &str {
        match self {
            Self::File { name } | Self::Directory { name, .. } => name,
        }
    }
}

/// What a listing answers with: one page of entries, whether more follow it,
/// and whether the answer is everything the request asked for.
///
/// `partial` is only ever true of a date-filtered listing whose history walk
/// spent the `limits.date_filter_maximum_ms` budget: entries are then missing
/// from the page, and — unlike `has_more`, which is about the next page —
/// nothing the caller can ask for will bring them back except a narrower
/// request or a larger budget.
pub struct Listing {
    pub nodes: Vec<TreeNode>,
    pub has_more: bool,
    pub partial: bool,
}

impl Listing {
    /// Nothing to list — a prefix that names no directory. Complete, not
    /// partial: the question was answered in full, the answer is empty.
    fn empty() -> Self {
        Self {
            nodes: vec![],
            has_more: false,
            partial: false,
        }
    }
}

/// 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,
}

/// Where a reorder request wants its entry to sit in its parent directory's
/// order index. The two variants are the two halves of what the read route
/// reports as `position`, so the same value a caller read back is a value it can
/// send: a zero-based index, or [`order::UNLISTED_POSITION`] (`-1`) meaning the
/// entry should not be in the index at all.
#[derive(Debug, Clone, Copy)]
pub enum OrderPosition {
    /// Zero-based index, clamped to the tail when it lands past the end.
    At(usize),
    /// Dropped from the index entirely, leaving the entry implicitly ordered
    /// again. Not a deletion of anything else: the file (or folder) itself is
    /// untouched, exactly as it is when the entry is merely moved.
    Unlisted,
}

/// One file as the read route returns it: its content, already narrowed to any
/// seek window, plus where it sits in its parent directory's file-order index.
///
/// `position` is zero-based, or [`order::UNLISTED_POSITION`] when the index does
/// not name the file — including when the directory has no index at all, which
/// is the same answer from the caller's point of view (nothing pins this file).
/// It is reported unconditionally because a client rendering one file usually
/// needs to know where it belongs among its siblings, and the cost is one small
/// blob read, paid only when the parent directory actually has an index.
#[derive(Debug)]
pub struct FileRead {
    pub content: String,
    pub position: i64,
}

/// What a path resolves to in HEAD's tree. Answered from tree objects alone
/// — a tree entry already carries its kind, so no blob is opened and the
/// working tree is never consulted (HEAD is authoritative everywhere in this
/// API, and a folder is a `Tree` entry exactly like a file is a `Blob` one).
///
/// `Missing` covers both "no such entry" and "an entry of some other kind"
/// (a submodule, a symlink target git records as a commit): neither a file
/// nor a folder this API can act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathKind {
    File,
    Directory,
    Missing,
}

/// Which git date a listing's date-range filter keys off. Both are derived
/// from commit history (a tree object carries no timestamp), so any listing
/// carrying a date bound pays for a history walk — see
/// [`GitFiles::file_dates`].
#[derive(Debug, Clone, Copy)]
pub enum DateKind {
    /// The oldest commit that introduced the file under its current path
    /// (renames are *not* followed). Requires walking to the root of history.
    Created,
    /// The most recent commit that touched the file. The walk can stop as
    /// soon as every in-scope file has been dated.
    Updated,
}

/// A date-range filter applied to a file listing: only files whose
/// [`DateKind`] date falls inside the window survive. The window is
/// half-open — `from` inclusive, `to` exclusive (`[from, to)`) — and each
/// bound is independently optional (an open-ended range). A file's date is
/// compared at whole-second (git commit) resolution, in UTC.
///
/// `budget` is the safety timer from `limits.date_filter_maximum_ms`. It
/// rides on the filter rather than travelling as its own argument because it
/// is only ever spent on this filter's work: a listing that carries no date
/// filter never walks history and so has nothing to time. Unset, the walk
/// runs to completion — the only behaviour there was before the key existed.
#[derive(Debug, Clone, Copy)]
pub struct DateFilter {
    pub from: Option<DateTime<Utc>>,
    pub to: Option<DateTime<Utc>>,
    pub kind: DateKind,
    pub budget: Option<Duration>,
}

impl DateFilter {
    /// Whether `date` falls inside the half-open window.
    fn matches(&self, date: DateTime<Utc>) -> bool {
        if let Some(from) = self.from {
            if date < from {
                return false;
            }
        }

        if let Some(to) = self.to {
            if date >= to {
                return false;
            }
        }

        true
    }
}

/// How a listing applies the per-directory file-order index. Its presence is
/// the opt-in itself — `None` means "do not order at all", which is what keeps
/// the blob-free listing contract for every caller that never asks.
///
/// `implicit_default_index` decides where the entries an index does *not* name
/// land. Left unset they rank behind every listed entry, which is the original
/// (and default) behaviour: a sparse index pins what it names and everything
/// else follows. Set, it is the index unlisted entries are treated as holding —
/// so `0` (or any negative value) lifts everything unordered *above* the
/// ordered entries, and `2` slots them between the index's second and third
/// entries. An unlisted entry always sorts before a listed entry holding the
/// same index, which is what makes `0` mean "on top" rather than "tied with the
/// first".
#[derive(Debug, Clone, Copy)]
pub struct OrderOptions {
    pub implicit_default_index: Option<i64>,
}

/// Sort key of one entry against a directory's stored order: its index, plus
/// whether the index actually names it. The `bool` is the tie-break — `false`
/// sorts first, so an unlisted entry falling on an occupied index goes above
/// it rather than after it.
type OrderRank = (i64, bool);

#[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.
    ///
    /// "Missing" also covers a directory that is not a repository and a
    /// repository with no commit yet. [`GitStaging`] keeps readers from ever
    /// seeing either while this process creates or deletes a tenant, but a
    /// store can still hold one — a replica's first import interrupted by an
    /// older build, an operator removing a tenant by hand — and neither holds
    /// anything a caller could read, so neither is a server error.
    fn open_tenant_repo(repo_path: &Path, tenant_id: &str) -> Result<Repository, AppError> {
        let not_found = || {
            tracing::debug!(tenant_id = %tenant_id, "tenant repository not found");

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

        if !repo_path.exists() {
            return Err(not_found());
        }

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

        let repo = match Repository::open(repo_path) {
            Ok(repo) => repo,
            Err(err) if err.code() == git2::ErrorCode::NotFound => return Err(not_found()),
            Err(err) => return Err(AppError::Git(err)),
        };

        if let Err(err) = repo.head() {
            if err.code() == git2::ErrorCode::UnbornBranch {
                return Err(not_found());
            }
        }

        Ok(repo)
    }

    /// 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.
    ///
    /// A new repository is built through [`GitStaging::create`], so a reader
    /// finds either no tenant or one already holding its root commit. A
    /// directory that exists without being a repository is adopted in place
    /// instead, as it always was: renaming over it would fail, and removing
    /// whatever it holds is not this function's call.
    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");

        let signature = Self::git_signature(author_name, author_email)?;

        if repo_path.exists() {
            Self::init_with_root_commit(repo_path, &signature)?;
        } else {
            GitStaging::create(repo_path, |staging| {
                Self::init_with_root_commit(staging, &signature)
            })?;
        }

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

    /// Initialises a repository at `path` with the empty `"chore: initialize"`
    /// root commit, leaving nothing open on it.
    fn init_with_root_commit(path: &Path, signature: &Signature) -> Result<(), AppError> {
        let repo = Repository::init(path)?;

        // An empty tree is required for the root commit so that HEAD is valid.
        tracing::trace!(path = %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 = %path.display(), sha = %root_oid, "root commit created");

        Ok(())
    }

    /// 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
    }

    /// Resolves `dir_path` to a tree in `tree` and collects every blob
    /// beneath it, recursively, as `(full path from the repo root, blob oid)`
    /// pairs in git's own tree order.
    ///
    /// Drives the recursive delete and move: the oids are what let the new
    /// commit reuse existing blobs verbatim (no content rehash), and the paths
    /// are what the per-file hooks are built from. Blob *content* is never
    /// read here — only entry names, kinds and oids, all already in the tree
    /// objects. Non-blob leaves (submodules) are skipped: this API has no
    /// representation for them, so a folder holding one moves or deletes its
    /// files and leaves the submodule entry to be dropped with the subtree.
    fn subtree_blob_paths(
        repo: &Repository,
        tree: &git2::Tree<'_>,
        dir_path: &str,
    ) -> Result<Vec<(String, Oid)>, AppError> {
        let tree_entry =
            tree.get_path(Path::new(dir_path))
                .map_err(|_err| AppError::FileNotFound {
                    path: dir_path.to_string(),
                })?;

        let subtree = repo
            .find_tree(tree_entry.id())
            .map_err(|_err| AppError::FileNotFound {
                path: dir_path.to_string(),
            })?;

        let mut blobs: Vec<(String, Oid)> = Vec::new();

        subtree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            if entry.kind() == Some(git2::ObjectType::Blob) {
                if let Ok(name) = entry.name() {
                    // `root` is the path relative to `subtree`, already
                    // slash-terminated ("" at the top level, "sub/" below).
                    blobs.push((format!("{}/{}{}", dir_path, root, name), entry.id()));
                }
            }

            git2::TreeWalkResult::Ok
        })?;

        tracing::trace!(path = %dir_path, file_count = blobs.len(), "collected subtree blobs");

        Ok(blobs)
    }

    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()
    }
}

// ---------------------------------------------------------------------------
// WorkingTree — the best-effort on-disk mirror of HEAD
// ---------------------------------------------------------------------------

/// The working tree as this codebase treats it: a *courtesy copy* of HEAD
/// kept on disk so a human can `ls` a tenant repository, and nothing else.
///
/// Every read resolves content from HEAD's tree and the object database, and
/// every commit tree is derived from HEAD's tree plus the intended change, so
/// nothing here can decide the outcome of an operation. That is what lets the
/// whole mirror be switched off with `server.checkout_files = false`, which is
/// worth real disk: git compresses blobs, so for markdown the files on disk
/// are several times larger than the `.git` holding their entire history, and
/// each one occupies at least a filesystem block.
///
/// Gathering the three operations here rather than repeating them at each
/// site is what makes that switch a single `if` instead of a dozen, and it
/// also puts the "a file that is already gone is not an error" rule — the
/// working tree may always have diverged from HEAD, which is HEAD's
/// prerogative — in one place.
struct WorkingTree<'a> {
    root: &'a Path,
    enabled: bool,
}

impl<'a> WorkingTree<'a> {
    fn new(root: &'a Path, enabled: bool) -> Self {
        Self { root, enabled }
    }

    /// Writes a file, creating its parent directories.
    fn write(&self, relative_path: impl AsRef<Path>, content: &[u8]) -> Result<(), AppError> {
        if !self.enabled {
            return Ok(());
        }

        let absolute_path = self.root.join(relative_path);

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

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

        Ok(())
    }

    /// Removes a file. Already absent is success: the working tree had
    /// diverged from HEAD, and HEAD is what counts.
    fn remove_file(&self, relative_path: impl AsRef<Path>) -> Result<(), AppError> {
        if !self.enabled {
            return Ok(());
        }

        match std::fs::remove_file(self.root.join(relative_path)) {
            Ok(()) => Ok(()),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(err) => Err(AppError::Io(err)),
        }
    }

    /// Removes a directory and everything under it, with the same tolerance.
    fn remove_directory(&self, relative_path: impl AsRef<Path>) -> Result<(), AppError> {
        if !self.enabled {
            return Ok(());
        }

        match std::fs::remove_dir_all(self.root.join(relative_path)) {
            Ok(()) => Ok(()),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(err) => Err(AppError::Io(err)),
        }
    }
}

// ---------------------------------------------------------------------------
// 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
                        );
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// GitStaging — tenant repositories appear and disappear in one step
// ---------------------------------------------------------------------------

/// What a staging directory is for, spelled into its name.
const STAGING_CREATING: &str = "creating";
const STAGING_DELETING: &str = "deleting";

/// Keeps staging names unique within this process. Uniqueness across
/// processes is not needed: whatever a previous process left behind is
/// swept at startup, and one found in the way anyway is discarded first.
static STAGING_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Creation and deletion of a whole tenant repository, made atomic with
/// respect to readers.
///
/// Reads never take the tenant write lock, so whatever a reader finds at
/// `<collection>/<tenant>` must be either nothing or a complete repository.
/// Building one in place breaks that twice over: between `create_dir_all`
/// and `Repository::init` the directory exists but is not a repository, and
/// on a replica HEAD then stays unborn for as long as the first pack takes
/// to import. `remove_dir_all` breaks it in the other direction, deleting
/// `.git` piecemeal under a reader that already found the directory. Each
/// of those windows answers a read with a raw git error — a `500` where
/// "no such tenant" is the only true answer.
///
/// So a repository is built in a dot-prefixed sibling and renamed into
/// place once it is complete, and removed by being renamed away first and
/// deleted where nobody looks. A rename inside one directory is atomic and
/// never crosses a filesystem, which is why the staging directory is a
/// sibling in the collection directory rather than somewhere under the
/// store root. The dot prefix is what keeps it invisible: no collection or
/// tenant id can start with one, so the repository scan and every route
/// skip it without knowing it exists.
///
/// Both operations must run under the tenant write lock, which is what
/// makes a per-tenant staging name free of collisions.
pub struct GitStaging;

impl GitStaging {
    /// The staging sibling of `repo_path`: `.<tenant>.<purpose>-<sequence>`.
    fn sibling(repo_path: &Path, purpose: &str) -> Result<PathBuf, AppError> {
        let (Some(parent), Some(name)) = (
            repo_path.parent(),
            repo_path.file_name().and_then(|name| name.to_str()),
        ) else {
            return Err(AppError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("not a tenant repository path: {}", repo_path.display()),
            )));
        };

        let sequence = STAGING_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        Ok(parent.join(format!(".{}.{}-{}", name, purpose, sequence)))
    }

    /// Whether `name` is a staging directory this module could have created.
    /// Parsed exactly rather than matched loosely, so the startup sweep can
    /// never remove anything else an operator keeps beside the tenants.
    fn is_staging_name(name: &str) -> bool {
        let Some((tenant, suffix)) = name
            .strip_prefix('.')
            .and_then(|rest| rest.rsplit_once('.'))
        else {
            return false;
        };

        let Some((purpose, sequence)) = suffix.split_once('-') else {
            return false;
        };

        validate::tenant_id(tenant).is_ok()
            && (purpose == STAGING_CREATING || purpose == STAGING_DELETING)
            && !sequence.is_empty()
            && sequence.bytes().all(|byte| byte.is_ascii_digit())
    }

    /// Best-effort removal of a staging directory. Absent is success.
    fn discard(path: &Path) {
        match std::fs::remove_dir_all(path) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => {
                tracing::warn!(
                    path = %path.display(),
                    err = %err,
                    "cannot remove staging directory, it is cleared at the next start"
                );
            }
        }
    }

    /// Builds a repository with `build` in a staging directory, then renames
    /// it to `repo_path`. `build` receives the staging path and must leave
    /// nothing open on it (every `Repository` it created dropped) by the time
    /// it returns. Nothing is left behind on failure.
    ///
    /// `repo_path` must not exist: the rename would fail on a non-empty
    /// directory, and a directory already there is the caller's to adopt.
    pub fn create<T>(
        repo_path: &Path,
        build: impl FnOnce(&Path) -> Result<T, AppError>,
    ) -> Result<T, AppError> {
        let staging = Self::sibling(repo_path, STAGING_CREATING)?;

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

        Self::discard(&staging);

        std::fs::create_dir(&staging)?;

        let outcome = build(&staging).and_then(|value| {
            std::fs::rename(&staging, repo_path)?;

            Ok(value)
        });

        if outcome.is_err() {
            Self::discard(&staging);
        }

        outcome
    }

    /// Removes the repository at `repo_path`: renamed away first, so readers
    /// see it vanish at once, then deleted. Once the rename has happened the
    /// tenant is gone as far as anything is concerned, so a failure to delete
    /// the renamed copy is logged rather than returned — the startup sweep
    /// finishes the job.
    pub fn remove(repo_path: &Path) -> Result<(), AppError> {
        let trash = Self::sibling(repo_path, STAGING_DELETING)?;

        Self::discard(&trash);

        std::fs::rename(repo_path, &trash)?;

        Self::discard(&trash);

        Ok(())
    }

    /// Walks `repos_root/<collection>/` once on startup and removes every
    /// staging directory a previous process left behind: a creation that
    /// never reached its rename, or a deletion that never finished. At boot
    /// nothing can be in flight, so everything found is abandoned. Errors
    /// are swallowed, as for the stale lock sweep: this is hygiene, and must
    /// never prevent the server from starting.
    pub fn cleanup_abandoned(repos_root: &Path) {
        let Ok(collections) = std::fs::read_dir(repos_root) else {
            return;
        };

        for collection_entry in collections.flatten() {
            let collection_path = collection_entry.path();

            if !collection_path.is_dir() {
                continue;
            }

            let Ok(tenants) = std::fs::read_dir(&collection_path) else {
                continue;
            };

            for tenant_entry in tenants.flatten() {
                let name = tenant_entry.file_name();

                if !name.to_str().is_some_and(Self::is_staging_name) {
                    continue;
                }

                let path = tenant_entry.path();

                tracing::warn!(
                    path = %path.display(),
                    "removing tenant staging directory abandoned by a previous process"
                );

                Self::discard(&path);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// 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). Skipped when `checkout_files` is off: with no
    ///    files on disk there is nothing for the index to be meaningful
    ///    *against*, so writing one would only add a file the node was asked
    ///    not to keep.
    ///
    /// 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,
        checkout_files: 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, so `git status` compares the
        // files on disk against the commit they came from. A node keeping no
        // files has nothing to compare, so it keeps no index either. Clean a
        // stale index.lock first — this is the only code path left that writes
        // the index.
        if checkout_files {
            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);
        }
    }

    /// How many packfiles a repository currently holds. One directory read,
    /// no repository open — cheap enough to run after every write when
    /// `[maintenance] maximum_packs` asks for a pack-count trigger.
    pub fn pack_count(repo_path: &Path) -> usize {
        Self::enumerate_pack_stems(repo_path)
            .map(|stems| stems.len())
            .unwrap_or(0)
    }

    /// 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.
    ///
    /// When `file_paths` is set, the listing is narrowed to exactly those paths
    /// (relative to `path_prefix`, and absent from the result when HEAD does not
    /// hold them); see `select_by_file_paths`. It is mutually exclusive with
    /// `file_name_starts_with` — the route rejects both together — and it is the
    /// one mode that walks nothing it was not asked for.
    ///
    /// When `date_filter` is set, the listing is narrowed to files whose git
    /// created/updated date falls inside the window (see `file_dates`). Like
    /// name search it forgoes the off-page optimisation — a file's date can
    /// move it in or out, so the whole in-scope tree must be examined before
    /// pagination — and it additionally walks commit history (still no blob
    /// opened, but cost scales with history length rather than page size).
    ///
    /// When `order_options` is set, each level of the result is reordered by the
    /// stored order index of the directory it belongs to (see
    /// [`Self::apply_order`]), with its `implicit_default_index` deciding where
    /// unlisted entries land. This is the one mode that opens blobs — one small
    /// index per directory actually rendered.
    ///
    /// The performance contract (search, date-filter and order modes 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.
    ///
    /// Order indexes themselves are never listed, whatever
    /// `include_hidden_files` says: they are a separate resource with their own
    /// route, not content.
    #[allow(clippy::too_many_arguments)]
    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]>,
        file_paths: Option<&[String]>,
        date_filter: Option<DateFilter>,
        order_options: Option<OrderOptions>,
        page: usize,
        per_page: usize,
    ) -> Result<Listing, 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, file_paths = ?file_paths, date_filter = ?date_filter, order_options = ?order_options, 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(Listing::empty()),
                },
                Err(_) => return Ok(Listing::empty()),
            },
            None => head_tree,
        };

        // An exact-path selection needs no walk at all: every entry it can
        // return is named, so it is one tree lookup per path and the result is
        // paginated like any other filtered listing.
        if let Some(wanted) = file_paths {
            return Self::select_by_file_paths(
                &repo,
                &walk_tree,
                path_prefix,
                wanted,
                maximum_depth,
                include_hidden_files,
                date_filter,
                order_options,
                page,
                per_page,
            );
        }

        // 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(
                &repo,
                &walk_tree,
                path_prefix,
                needles,
                maximum_depth,
                include_hidden_files,
                date_filter,
                order_options,
                page,
                per_page,
            );
        }

        // A date filter (without a name search) likewise walks the whole
        // in-scope tree, dates each file against commit history, and paginates
        // the surviving set — the off-page optimisation cannot hold.
        if let Some(date_filter) = date_filter {
            return Self::list_with_date_filter(
                &repo,
                &walk_tree,
                path_prefix,
                maximum_depth,
                include_hidden_files,
                date_filter,
                order_options,
                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())),

                // The order index is a separate resource, not content: it is
                // dropped unconditionally, even when hidden entries are asked
                // for, so it can only ever be reached through `/order`.
                Some(git2::ObjectType::Blob) if name != order::ORDER_FILE_NAME => {
                    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 mut root_entries: Vec<RootEntry> = root_dirs
            .into_iter()
            .map(|(name, oid)| RootEntry::Directory(name, oid))
            .chain(root_files.into_iter().map(RootEntry::File))
            .collect();

        // The listing root's own order is applied *before* the page window is
        // sliced — pagination is over root-level entries, so ordering them
        // afterwards would page over the wrong sequence. Only one index is
        // read here; off-page directories are still never opened.
        if let Some(order_options) = order_options {
            if let Some(order) = GitOrder::stored_order(&repo, &walk_tree, "") {
                let ranks = Self::order_ranks(&order);

                root_entries.sort_by_key(|root_entry| {
                    let name = match root_entry {
                        RootEntry::Directory(name, _oid) => name.as_str(),
                        RootEntry::File(name) => name.as_str(),
                    };

                    Self::order_rank(&ranks, name, &order_options)
                });
            }
        }

        let page_entries: Vec<RootEntry> = root_entries
            .into_iter()
            .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 });
                }
            }
        }

        // The root level was ordered before pagination; every level *below* it
        // is ordered here, walking only the subtrees that made the page.
        if let Some(order_options) = order_options {
            for node in nodes.iter_mut() {
                if let TreeNode::Directory { name, children } = node {
                    Self::apply_order(&repo, &walk_tree, name, children, &order_options);
                }
            }
        }

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

        // Nothing here walks history, so nothing here can run out of time.
        Ok(Listing {
            nodes,
            has_more,
            partial: false,
        })
    }

    /// Position of each name in a stored order, so a *stable* sort by rank
    /// puts listed entries in index order and leaves everything else in the
    /// order it already had — which is what makes a sparse index pin only what
    /// it names.
    ///
    /// Names are compared with any directory-marking trailing slash stripped.
    /// A duplicate keeps its first position; writes reject duplicates, but a
    /// hand-edited index must still rank deterministically.
    fn order_ranks(order: &[String]) -> HashMap<&str, i64> {
        let mut ranks: HashMap<&str, i64> = HashMap::with_capacity(order.len());

        for (position, entry) in order.iter().enumerate() {
            ranks
                .entry(order::entry_name(entry))
                .or_insert(position as i64);
        }

        ranks
    }

    /// Sort key of `name` against `ranks`: its stored index when the index
    /// names it, and `order_options.implicit_default_index` when it does not —
    /// falling back to "behind everything listed" when no implicit index is
    /// configured, which is the default sparse-index behaviour.
    ///
    /// The `false` on the unlisted side is what makes an implicit index of `0`
    /// mean "above the ordered entries" instead of "tied with the first one":
    /// on an equal index, unlisted sorts before listed.
    fn order_rank(
        ranks: &HashMap<&str, i64>,
        name: &str,
        order_options: &OrderOptions,
    ) -> OrderRank {
        match ranks.get(name) {
            Some(position) => (*position, true),
            None => (
                order_options.implicit_default_index.unwrap_or(i64::MAX),
                false,
            ),
        }
    }

    /// Reorders `nodes` — the rendered children of `directory`, itself
    /// relative to `base_tree` — by that directory's stored order index, then
    /// recurses into every directory child.
    ///
    /// Best-effort by design: a directory with no index, or with one that
    /// cannot be parsed, is left in its ordinary order, and an index entry
    /// naming something absent from `nodes` simply ranks nothing. That is what
    /// makes a stale index harmless — a revert can restore an index older than
    /// the files it names, and no listing should fail because of it.
    ///
    /// This is the only place in the listing path that opens a blob: one index
    /// per directory actually rendered.
    fn apply_order(
        repo: &Repository,
        base_tree: &git2::Tree<'_>,
        directory: &str,
        nodes: &mut [TreeNode],
        order_options: &OrderOptions,
    ) {
        // Nothing rendered at this level, so no index is worth reading — a
        // depth-limited stub costs no blob read.
        if nodes.is_empty() {
            return;
        }

        // A directory with no index is left in its ordinary order, whatever
        // `implicit_default_index` says: with nothing listed, every entry is
        // implicit, so a common fallback index cannot reorder any of them.
        if let Some(order) = GitOrder::stored_order(repo, base_tree, directory) {
            let ranks = Self::order_ranks(&order);

            nodes.sort_by_key(|node| Self::order_rank(&ranks, node.name(), order_options));
        }

        for node in nodes.iter_mut() {
            if let TreeNode::Directory { name, children } = node {
                let child_directory = if directory.is_empty() {
                    name.clone()
                } else {
                    format!("{}/{}", directory, name)
                };

                Self::apply_order(repo, base_tree, &child_directory, children, order_options);
            }
        }
    }

    /// 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 (flat, dir_stubs) =
            Self::collect_flat_with_stubs(subtree, max_depth, include_hidden_files)?;

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

    /// The walk behind [`Self::collect_subtree`], stopped one step short of
    /// building a tree: the in-scope files as flat paths relative to `subtree`,
    /// plus the directories descent stopped at (kept as stubs so a
    /// depth-limited folder still shows, childless). Split out because the
    /// exact-path selection has to *prefix* both lists with the path it
    /// expanded before they reach `build_tree` — something a built tree can no
    /// longer be given.
    fn collect_flat_with_stubs(
        subtree: &git2::Tree<'_>,
        max_depth: Option<usize>,
        include_hidden_files: bool,
    ) -> Result<(Vec<String>, Vec<String>), 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("");

            // Order indexes are a separate resource, never listed as content.
            if name == order::ORDER_FILE_NAME {
                return git2::TreeWalkResult::Ok;
            }

            flat.push(format!("{}{}", root, name));

            git2::TreeWalkResult::Ok
        })?;

        Ok((flat, dir_stubs))
    }

    /// 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.
    #[allow(clippy::too_many_arguments)]
    fn search_by_file_name(
        repo: &Repository,
        walk_tree: &git2::Tree<'_>,
        path_prefix: Option<&str>,
        needles: &[String],
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        date_filter: Option<DateFilter>,
        order_options: Option<OrderOptions>,
        page: usize,
        per_page: usize,
    ) -> Result<Listing, 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();

        // Matched directories the depth limit stopped the walk at, kept apart
        // from the stubs above because their contents are still unknown here:
        // a date filter has to look inside them (their subtree oid is what it
        // looks inside with) before it can say whether they belong on the page.
        let mut depth_stubs: Vec<(String, Oid)> = 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 {
                                depth_stubs.push((full_path, entry.id()));
                            }

                            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);
                    }
                }
                // Order indexes are a separate resource, never listed as
                // content — and so never searchable by name either.
                Some(git2::ObjectType::Blob)
                    if name != order::ORDER_FILE_NAME && (in_matched || self_matches) =>
                {
                    flat.push(full_path);
                }
                _ => {}
            }

            git2::TreeWalkResult::Ok
        })?;

        Self::finish_filtered_listing(
            repo,
            walk_tree,
            path_prefix,
            flat,
            dir_stubs,
            depth_stubs,
            include_hidden_files,
            date_filter,
            order_options,
            page,
            per_page,
        )
    }

    /// Returns the tree of exactly the entries `wanted` names, each path
    /// relative to the listing root (so relative to `prefix_path` when one is
    /// set, which is what the caller spelled them against). A path HEAD does
    /// not hold is simply absent from the result rather than an error: a
    /// selection states what the caller is interested in, not what it believes
    /// exists.
    ///
    /// Every other rule is the one [`Self::search_by_file_name`] follows, since
    /// this is the same listing mode reached by a different predicate — an
    /// entry is selected by its exact path instead of its leaf name:
    ///
    /// - a named **file** is returned as a leaf, its ancestor directories
    ///   present purely as the structure leading to it;
    /// - a named **directory** is returned with its whole subtree expanded, so
    ///   naming a folder reads it in one call;
    /// - `include_hidden_files` gates hidden entries the same way, and it gates
    ///   them by *path*: a named entry is dropped when any of its components is
    ///   dot-prefixed, which is what the search's wholesale pruning of a hidden
    ///   directory's subtree amounts to;
    /// - `maximum_depth` bounds the result the same way — a named path deeper
    ///   than the limit is not returned at all (the search would never have
    ///   walked to it), and a named directory sitting *at* the limit renders as
    ///   a childless stub;
    /// - an order index is never selectable, exactly as it is never listed;
    /// - a date filter intersects, pagination stays parent-based over the
    ///   root-level entries of the selected tree, and no blob is ever opened.
    ///
    /// Duplicate paths are harmless rather than rejected (the tree is built by
    /// name, so naming a path twice builds the same node once), and the cost of
    /// this mode is one tree lookup per path — the only listing mode cheaper
    /// than the plain one, since nothing is walked that was not asked for.
    #[allow(clippy::too_many_arguments)]
    fn select_by_file_paths(
        repo: &Repository,
        walk_tree: &git2::Tree<'_>,
        path_prefix: Option<&str>,
        wanted: &[String],
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        date_filter: Option<DateFilter>,
        order_options: Option<OrderOptions>,
        page: usize,
        per_page: usize,
    ) -> Result<Listing, AppError> {
        let mut flat: Vec<String> = Vec::new();
        let mut dir_stubs: Vec<String> = Vec::new();
        let mut depth_stubs: Vec<(String, Oid)> = Vec::new();

        for wanted_path in wanted {
            let Ok(entry) = walk_tree.get_path(Path::new(wanted_path)) else {
                continue;
            };

            let components: Vec<&str> = wanted_path.split('/').collect();

            // Hidden entries (Unix dot convention) are excluded by path, not
            // just by leaf name: a file inside a hidden directory is one the
            // walking modes never reach, so naming it explicitly must not be a
            // way around the flag.
            if !include_hidden_files
                && components
                    .iter()
                    .any(|component| component.starts_with('.'))
            {
                continue;
            }

            // Depth of the named entry relative to the listing root: a
            // root-level entry is depth 1, `docs/intro.md` depth 2, …
            let depth = components.len();

            // A path the depth limit puts out of reach is not returned, exactly
            // as a name match below the limit is never found.
            if maximum_depth.is_some_and(|max| depth > max) {
                continue;
            }

            match entry.kind() {
                // Order indexes are a separate resource, never listed as
                // content — and so never selectable by path either.
                Some(git2::ObjectType::Blob) => {
                    if components.last() != Some(&order::ORDER_FILE_NAME) {
                        flat.push(wanted_path.clone());
                    }
                }

                Some(git2::ObjectType::Tree) => {
                    // Sitting *at* the limit: on the page as a childless stub,
                    // its contents never opened (a date filter is the one thing
                    // that looks inside, and it takes the oid to do it).
                    if maximum_depth == Some(depth) {
                        depth_stubs.push((wanted_path.clone(), entry.id()));

                        continue;
                    }

                    // Stubbed as well as expanded, so a named directory still
                    // shows when everything inside it is hidden or filtered out
                    // — it is itself what the caller asked for.
                    dir_stubs.push(wanted_path.clone());

                    let subtree = repo.find_tree(entry.id())?;

                    // The depth limit below is relative to this subtree, which
                    // sits `depth` levels down from the listing root.
                    let subtree_max_depth = maximum_depth.map(|max| max - depth);

                    let (leaves, stubs) = Self::collect_flat_with_stubs(
                        &subtree,
                        subtree_max_depth,
                        include_hidden_files,
                    )?;

                    flat.extend(
                        leaves
                            .into_iter()
                            .map(|leaf| format!("{}/{}", wanted_path, leaf)),
                    );

                    dir_stubs.extend(
                        stubs
                            .into_iter()
                            .map(|stub| format!("{}/{}", wanted_path, stub)),
                    );
                }

                _ => {}
            }
        }

        Self::finish_filtered_listing(
            repo,
            walk_tree,
            path_prefix,
            flat,
            dir_stubs,
            depth_stubs,
            include_hidden_files,
            date_filter,
            order_options,
            page,
            per_page,
        )
    }

    /// The half of a filtered listing that follows the walk, shared by the two
    /// modes that filter — name search and exact-path selection — because it is
    /// identical for both: the date window is intersected with what was
    /// selected, the surviving paths are built into a tree, that tree is ordered
    /// in full, and the page window is sliced from it.
    ///
    /// `flat` holds the selected files as paths relative to the listing root,
    /// `dir_stubs` the directories that must show even when childless, and
    /// `depth_stubs` those the depth limit cut short — kept apart from
    /// `dir_stubs` because only a date filter needs to look inside them, and it
    /// needs their subtree oid to do it.
    #[allow(clippy::too_many_arguments)]
    fn finish_filtered_listing(
        repo: &Repository,
        walk_tree: &git2::Tree<'_>,
        path_prefix: Option<&str>,
        flat: Vec<String>,
        mut dir_stubs: Vec<String>,
        depth_stubs: Vec<(String, Oid)>,
        include_hidden_files: bool,
        date_filter: Option<DateFilter>,
        order_options: Option<OrderOptions>,
        page: usize,
        per_page: usize,
    ) -> Result<Listing, AppError> {
        // A date filter, when present, composes with whichever selection ran:
        // only selected entries that also fall inside the date window survive.
        // Because directories carry no date, the tree is rebuilt from the
        // surviving *files* alone — a selected directory left with no in-window
        // file is pruned.
        //
        // A directory the depth limit cut the walk short at is the one case
        // that needs more than `flat`: it is on the page as a childless stub,
        // so whether it holds an in-window file is decided by walking its
        // subtree now. Those files answer that question and nothing else —
        // they are never rendered, since the depth limit is exactly the
        // promise that nothing below it is.
        let mut partial = false;

        let (flat, dir_stubs) = match date_filter {
            Some(date_filter) => {
                let mut candidates = flat;
                let rendered = candidates.len();
                let mut stub_ranges: Vec<(String, Range<usize>)> =
                    Vec::with_capacity(depth_stubs.len());

                for (stub_path, stub_oid) in depth_stubs {
                    let start = candidates.len();

                    if let Ok(subtree) = repo.find_tree(stub_oid) {
                        for leaf in Self::collect_flat_files(&subtree, None, include_hidden_files)?
                        {
                            candidates.push(format!("{}/{}", stub_path, leaf));
                        }
                    }

                    stub_ranges.push((stub_path, start..candidates.len()));
                }

                let (surviving, exhausted) =
                    Self::surviving_by_date(repo, path_prefix, &candidates, date_filter)?;

                partial = exhausted;

                let stubs: Vec<String> = stub_ranges
                    .into_iter()
                    .filter(|(_stub_path, range)| {
                        candidates[range.clone()]
                            .iter()
                            .any(|leaf| surviving.contains(leaf))
                    })
                    .map(|(stub_path, _range)| stub_path)
                    .collect();

                candidates.truncate(rendered);

                (
                    candidates
                        .into_iter()
                        .filter(|leaf| surviving.contains(leaf))
                        .collect(),
                    stubs,
                )
            }
            None => {
                dir_stubs.extend(depth_stubs.into_iter().map(|(stub_path, _oid)| stub_path));

                (flat, dir_stubs)
            }
        };

        // 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 directories that were not (or could not be)
        // expanded. The tree is then paginated over its root-level entries,
        // exactly like the plain listing.
        let mut tree = GitUtils::build_tree(flat, dir_stubs, None);

        // The whole tree is in hand before pagination here, so
        // ordering is applied to it in full and the page window is sliced from
        // the ordered result.
        if let Some(order_options) = order_options {
            Self::apply_order(repo, walk_tree, "", &mut tree, &order_options);
        }

        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(Listing {
            nodes,
            has_more,
            partial,
        })
    }

    /// Lists the in-scope tree narrowed to files whose git date falls inside
    /// `date_filter`'s window. The whole in-scope tree is walked (the off-page
    /// optimisation cannot hold — a date can move any file in or out), each
    /// file is dated against commit history, and the surviving set is
    /// paginated over its root-level entries. Directories survive only as the
    /// structure leading to a surviving file, so an emptied directory is
    /// pruned. `include_hidden_files` bounds the walk exactly as elsewhere.
    ///
    /// `maximum_depth` bounds the *result* rather than the walk: a directory
    /// sitting at the limit renders as a childless stub, exactly as the plain
    /// listing renders it, but only when the subtree below it holds an
    /// in-window file — which is why the walk has to go past the limit even
    /// though nothing below it is ever rendered. Bounding the walk instead
    /// would drop every directory from a depth-limited listing (nothing below
    /// the limit is walked, so nothing below it can be dated), leaving a
    /// caller that browses one level at a time with no folder to descend
    /// into.
    #[allow(clippy::too_many_arguments)]
    fn list_with_date_filter(
        repo: &Repository,
        walk_tree: &git2::Tree<'_>,
        path_prefix: Option<&str>,
        maximum_depth: Option<usize>,
        include_hidden_files: bool,
        date_filter: DateFilter,
        order_options: Option<OrderOptions>,
        page: usize,
        per_page: usize,
    ) -> Result<Listing, AppError> {
        let flat = Self::collect_flat_files(walk_tree, None, include_hidden_files)?;
        let (matched, partial) = Self::retain_by_date(repo, path_prefix, flat, date_filter)?;

        // `build_tree` applies the depth limit, so a surviving file below it
        // is not rendered but still puts the directory it sits under on the
        // page, as the childless stub the plain listing would show. A
        // directory whose whole subtree fell outside the window contributes no
        // path at all and is therefore pruned, exactly like an emptied one.
        let mut tree = GitUtils::build_tree(matched, Vec::new(), maximum_depth);

        // The whole surviving tree is in hand before pagination here, so
        // ordering is applied to it in full and the page window is sliced from
        // the ordered result.
        if let Some(order_options) = order_options {
            Self::apply_order(repo, walk_tree, "", &mut tree, &order_options);
        }

        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(Listing {
            nodes,
            has_more,
            partial,
        })
    }

    /// Collects every in-scope file as a flat path relative to `tree`,
    /// honouring the hidden-entry and depth-limit rules (a hidden directory's
    /// subtree is skipped, and descent stops at the depth limit so files below
    /// it are never collected). Unlike `collect_subtree` it records no
    /// directory stubs and returns bare paths rather than a built tree —
    /// callers that need a tree feed the result back through `build_tree`.
    fn collect_flat_files(
        tree: &git2::Tree<'_>,
        max_depth: Option<usize>,
        include_hidden_files: bool,
    ) -> Result<Vec<String>, AppError> {
        let mut flat: Vec<String> = Vec::new();

        tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            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
                };
            }

            if entry.kind() == Some(git2::ObjectType::Tree) {
                if let Some(max) = max_depth {
                    let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;

                    if entry_depth >= max {
                        return git2::TreeWalkResult::Skip;
                    }
                }

                return git2::TreeWalkResult::Ok;
            }

            if entry.kind() == Some(git2::ObjectType::Blob) {
                let name = entry.name().unwrap_or("");

                // Order indexes are a separate resource, never listed as
                // content — so they are never date-filtered either.
                if name != order::ORDER_FILE_NAME {
                    flat.push(format!("{}{}", root, name));
                }
            }

            git2::TreeWalkResult::Ok
        })?;

        Ok(flat)
    }

    /// Which of those `flat` paths (relative to the listing root) have a git
    /// date inside `date_filter`'s window. The date map returned by
    /// `file_dates` is keyed by repo-root paths, so the listing-root
    /// `path_prefix` is re-joined before each lookup. A path with no date in
    /// history (which cannot happen for a file present in HEAD) is dropped.
    ///
    /// A set rather than a filtered list because a caller may be asking about
    /// two different things at once: which files to render, and whether some
    /// *other* file — one below a depth limit — puts its directory on the page.
    ///
    /// The flag beside it is the one [`Self::file_dates`] returns: the time
    /// budget ran out, so paths left undated are absent from the set and the
    /// listing built from it is short.
    fn surviving_by_date(
        repo: &Repository,
        path_prefix: Option<&str>,
        flat: &[String],
        date_filter: DateFilter,
    ) -> Result<(HashSet<String>, bool), AppError> {
        let to_full = |leaf: &str| -> String {
            match path_prefix {
                Some(prefix) if !prefix.is_empty() => format!("{}/{}", prefix, leaf),
                _ => leaf.to_string(),
            }
        };

        let full_paths: HashSet<String> = flat.iter().map(|leaf| to_full(leaf)).collect();

        if full_paths.is_empty() {
            return Ok((HashSet::new(), false));
        }

        let (dates, exhausted) = Self::file_dates(
            repo,
            &full_paths,
            date_filter.kind,
            path_prefix.filter(|prefix| !prefix.is_empty()),
            date_filter.budget,
        )?;

        Ok((
            flat.iter()
                .filter(|leaf| {
                    dates
                        .get(&to_full(leaf))
                        .is_some_and(|date| date_filter.matches(*date))
                })
                .cloned()
                .collect(),
            exhausted,
        ))
    }

    /// [`Self::surviving_by_date`] applied to a list the caller owns, keeping
    /// the surviving paths in the order they came in.
    fn retain_by_date(
        repo: &Repository,
        path_prefix: Option<&str>,
        flat: Vec<String>,
        date_filter: DateFilter,
    ) -> Result<(Vec<String>, bool), AppError> {
        let (surviving, exhausted) =
            Self::surviving_by_date(repo, path_prefix, &flat, date_filter)?;

        Ok((
            flat.into_iter()
                .filter(|leaf| surviving.contains(leaf))
                .collect(),
            exhausted,
        ))
    }

    /// Walks commit history once (newest-first, diffing each commit against
    /// its first parent) and returns, for each requested repo-root path, the
    /// commit time that defines its `kind` date.
    ///
    /// The diff is computed from tree/oid deltas alone — no patch, no stats,
    /// no rename detection — so **no blob is opened** and a rename surfaces as
    /// an add of the new path plus a delete of the old (renames are not
    /// followed). Cost is therefore O(commits), not O(history × files).
    ///
    /// - `Updated`: the first commit seen (walking newest-first) that touched
    ///   a path is its most-recent touch; the walk stops as soon as every
    ///   requested path has a date.
    /// - `Created`: the oldest commit that *added* a path; the walk must reach
    ///   the root of history, so this is the heavier of the two.
    ///
    /// The returned flag says the walk gave its budget up rather than running
    /// out of history: the dates in hand are kept and the rest of history is
    /// left unread, so a caller that filters on them gets fewer files than
    /// the window really holds. Worth knowing for `Created`, where a date is
    /// only final once the walk has reached the root of history — a path
    /// added, deleted and added again can be left holding the later of its
    /// two additions, which is a *wrong* date rather than a missing one.
    ///
    /// `scope` is the listing's `prefix_path`, and every requested path lives
    /// under it. Handing it to the diff as a pathspec is what keeps a scoped
    /// listing cheap: without it each commit is diffed in full and the deltas
    /// of every *other* directory are produced only to be discarded here, so a
    /// repository holding one sub-tree per locale pays for all of them on
    /// every commit of its history. With it, libgit2 prunes the tree walk to
    /// the sub-tree in scope and never reads the objects behind the rest.
    /// `disable_pathspec_match` is what makes that pruning happen at all —
    /// libgit2 hands the pathspec to its tree iterators only when it is set,
    /// and matching then compares literal path prefixes rather than globs,
    /// which is what a directory path should mean here anyway.
    fn file_dates(
        repo: &Repository,
        paths: &HashSet<String>,
        kind: DateKind,
        scope: Option<&str>,
        budget: Option<Duration>,
    ) -> Result<(HashMap<String, DateTime<Utc>>, bool), AppError> {
        let mut dates: HashMap<String, DateTime<Utc>> = HashMap::new();
        let mut exhausted = false;
        let deadline = budget.map(|budget| Instant::now() + budget);

        let mut revwalk = repo.revwalk()?;

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

        // Built once and reused: the options are the same for every commit,
        // and a scoped walk would otherwise re-allocate its pathspec on each
        // of them.
        let mut diff_options = DiffOptions::new();

        diff_options.include_untracked(false);

        if let Some(scope) = scope {
            diff_options.disable_pathspec_match(true);
            diff_options.pathspec(scope);
        }

        for oid_result in revwalk {
            // Updated: once every requested path is dated, every older commit
            // can only hold an older (irrelevant) touch — nothing left to find.
            if matches!(kind, DateKind::Updated) && dates.len() == paths.len() {
                break;
            }

            // The safety timer, checked per commit because a commit is the
            // unit of work here — one tree-to-tree diff, bounded by what that
            // commit changed inside the scope. Whatever has been dated by now
            // is kept: the caller is told the answer is partial rather than
            // handed an error, since a listing that arrives short is more use
            // than none at all.
            if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                tracing::warn!(
                    dated = dates.len(),
                    wanted = paths.len(),
                    budget_ms = budget.map(|budget| budget.as_millis() as u64),
                    "date filter gave up its time budget, answering partially"
                );

                exhausted = true;

                break;
            }

            let Ok(oid) = oid_result else {
                continue;
            };
            let Ok(commit) = repo.find_commit(oid) else {
                continue;
            };
            let Ok(commit_tree) = commit.tree() else {
                continue;
            };

            // The root commit has no parent — diff against an empty tree
            // (`None`), so its entries register as additions.
            let parent_tree = commit.parent(0).and_then(|parent| parent.tree()).ok();

            let diff = match repo.diff_tree_to_tree(
                parent_tree.as_ref(),
                Some(&commit_tree),
                Some(&mut diff_options),
            ) {
                Ok(diff) => diff,
                Err(_) => continue,
            };

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

            for delta in diff.deltas() {
                // A delete carries the path only on the old side; every other
                // status carries it on the new side.
                let Some(path) = delta
                    .new_file()
                    .path()
                    .or_else(|| delta.old_file().path())
                    .map(|path| path.to_string_lossy().into_owned())
                else {
                    continue;
                };

                if !paths.contains(&path) {
                    continue;
                }

                match kind {
                    // Newest-first, so the first touch seen is the latest.
                    DateKind::Updated => {
                        dates.entry(path).or_insert(commit_time);
                    }
                    // Keep overwriting on each older addition so the final
                    // value is the earliest introduction of the path.
                    DateKind::Created => {
                        if delta.status() == Delta::Added {
                            dates.insert(path, commit_time);
                        }
                    }
                }
            }
        }

        Ok((dates, exhausted))
    }

    /// 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;
                        }
                    }
                }
                // Order indexes are a separate resource, not content: they are
                // excluded from the count exactly as from the listing, whatever
                // `include_hidden_files` says.
                Some(git2::ObjectType::Blob)
                    if entry
                        .name()
                        .is_ok_and(|name| name == order::ORDER_FILE_NAME) => {}

                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, and so does a path naming
    /// an order index, which is reachable only through `/order`. See
    /// `GitUtils::windowed_blob_content` for how seek windows are read.
    ///
    /// The file's position in its parent directory's order index travels with
    /// the content (see [`FileRead`]), so a caller reading one file learns where
    /// it sits among its siblings without a second request.
    pub fn read_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
        seek: &SeekFilter,
    ) -> Result<FileRead, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, "reading file");

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

        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(),
            }
        })?;

        let content = GitUtils::windowed_blob_content(&repo, blob_oid, file_path, seek)?;
        let (directory, name) = order::split_parent(file_path);
        let position = GitOrder::entry_position(&repo, &head_tree, directory, name);

        Ok(FileRead { content, position })
    }

    /// 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)| {
                // An order index is invisible here for the same reason it is
                // on the single read route, and `None` already means "not
                // found" — no special slot is needed for it.
                if order::is_order_file(file_path) {
                    return Ok(None);
                }

                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()
    }

    /// Every file HEAD holds, as a flat list of repo-root-relative paths, plus
    /// the sha of the HEAD commit the list was read from.
    ///
    /// This is the snapshot both replay routes are built on. It opens no blob
    /// — only tree objects — so its cost is the tree walk alone, and order
    /// indexes are excluded exactly as they are from every `/files` route
    /// (`collect_flat_files` drops them), because they are a separate resource
    /// and a receiver mirroring content must never be told one is a file.
    ///
    /// `path_prefix` scopes the walk to a sub-directory with the listing
    /// route's semantics (an absent or non-directory prefix yields an empty
    /// list rather than an error), and `include_hidden_files` follows the
    /// listing's dot-prefix rule. The returned paths are always relative to
    /// the repository root, not to the prefix, so they are the same identities
    /// that travel in hook payloads.
    pub fn list_all_file_paths(
        repo_path: &Path,
        tenant_id: &str,
        path_prefix: Option<&str>,
        include_hidden_files: bool,
    ) -> Result<(String, Vec<String>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, include_hidden_files = include_hidden_files, "listing all file paths");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;
        let head_sha = head_commit.id().to_string();
        let head_tree = head_commit.tree()?;

        // Same prefix resolution as `list_files`: resolve the subtree directly
        // so unrelated directories are never visited.
        let prefix = path_prefix.filter(|prefix| !prefix.is_empty());

        let walk_tree: git2::Tree<'_> = match prefix {
            Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
                Ok(entry) => match repo.find_tree(entry.id()) {
                    Ok(tree) => tree,
                    Err(_not_a_directory) => return Ok((head_sha, Vec::new())),
                },
                Err(_absent) => return Ok((head_sha, Vec::new())),
            },
            None => head_tree,
        };

        let flat = Self::collect_flat_files(&walk_tree, None, include_hidden_files)?;

        let paths = match prefix {
            Some(prefix) => flat
                .into_iter()
                .map(|leaf| format!("{}/{}", prefix, leaf))
                .collect(),
            None => flat,
        };

        tracing::debug!(tenant_id = %tenant_id, file_count = paths.len(), head_sha = %head_sha, "collected file paths");

        Ok((head_sha, paths))
    }

    /// Reads whole file contents for one chunk of a replay, in one repository
    /// pass, index-aligned with `paths`.
    ///
    /// `None` marks a path that cannot be delivered, and the distinction from
    /// [`Self::batch_read_files`] is deliberate: a batch read answers a
    /// caller who asked for exactly these files, so unreadable content is a
    /// hard `422`. A replay is reconciliation running unattended over a
    /// snapshot that may already have moved on, and one undeliverable file
    /// must not abort the other thousands — so a path that is absent, is a
    /// folder, is an order index, or holds content JSON cannot carry is logged
    /// and skipped. Only a failure to read the *repository* is an error.
    pub fn replay_read_files(
        repo_path: &Path,
        tenant_id: &str,
        paths: &[String],
    ) -> Result<Vec<Option<String>>, AppError> {
        tracing::trace!(tenant_id = %tenant_id, count = paths.len(), "reading replay chunk");

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

        let contents = paths
            .iter()
            .map(|file_path| {
                if order::is_order_file(file_path) {
                    return None;
                }

                // Absent from HEAD: the file was deleted between the snapshot
                // and now. Its real `file.deleted` is queued behind this
                // replay, so skipping keeps the receiver converging.
                let blob_oid = GitUtils::blob_oid_in_tree(&head_tree, file_path)?;
                let blob = repo.find_blob(blob_oid).ok()?;

                match std::str::from_utf8(blob.content()) {
                    Ok(text) => Some(text.to_string()),

                    Err(_not_utf8) => {
                        tracing::warn!(path = %file_path, "replay skipping file: content is not valid UTF-8");

                        None
                    }
                }
            })
            .collect();

        Ok(contents)
    }

    /// Classifies what `path` resolves to in HEAD's tree — a file, a folder,
    /// or nothing at all — without reading any content.
    ///
    /// This is the single primitive behind both the existence endpoint (which
    /// decides from the kind whether to answer `200` or `404`) and the
    /// recursion-enabled delete/move routes (which decide from it whether to
    /// run the single-file or the whole-folder operation). A missing *tenant*
    /// is still an error rather than `Missing`: the caller is asking about a
    /// repository that does not exist, which is a different answer from "that
    /// path is not in this repository".
    ///
    /// An order index classifies as `Missing` whatever HEAD holds: it is a
    /// separate resource with its own route, so it is neither a file the
    /// existence endpoint should confirm nor a path delete/move may act on.
    pub fn path_kind(repo_path: &Path, tenant_id: &str, path: &str) -> Result<PathKind, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %path, "classifying path");

        if order::is_order_file(path) {
            return Ok(PathKind::Missing);
        }

        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 = %path, head_sha = %head_commit.id(), "resolved HEAD for path classification");

        let head_tree = head_commit.tree()?;

        let kind = match head_tree.get_path(Path::new(path)) {
            Ok(entry) => match entry.kind() {
                Some(git2::ObjectType::Blob) => PathKind::File,
                Some(git2::ObjectType::Tree) => PathKind::Directory,
                _ => PathKind::Missing,
            },
            Err(_absent) => PathKind::Missing,
        };

        tracing::debug!(tenant_id = %tenant_id, path = %path, kind = ?kind, "path classified");

        Ok(kind)
    }

    /// 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,
        checkout_files: bool,
    ) -> Result<(String, Option<FileChange>), AppError> {
        tracing::debug!(path = %file_path, author_name = %author_name, author_email = %author_email, "writing file");

        // The order index has its own route, which owns its format and
        // validates it. Letting a client PUT it as an ordinary file would
        // bypass that validation entirely, so the path is refused outright —
        // and with a message that says where to go, since unlike a read there
        // is no sense in which a write "is not found".
        if order::is_order_file(file_path) {
            return Err(AppError::InvalidOperation {
                reason: format!(
                    "path is reserved for the file order index, write it through /order instead: {}",
                    file_path
                ),
            });
        }

        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");

        WorkingTree::new(repo_path, checkout_files).write(file_path, content.as_bytes())?;

        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.
    ///
    /// The parent directory's order index, when it lists this file, is
    /// rewritten without it **in the same commit** — so a downstream order
    /// table never holds a position for a file that is gone. That upkeep is
    /// what makes the returned change list plural: the file's own deletion
    /// plus, at most, the index's change (which the hook layer turns into an
    /// `order.*` event from its path alone).
    pub fn delete_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, author_name = %author_name, author_email = %author_email, "deleting file");

        // The order index is not addressable through the file routes, so it is
        // "not a file" here exactly as a folder is.
        if order::is_order_file(file_path) {
            return Err(AppError::FileNotFound {
                path: file_path.to_string(),
            });
        }

        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");

        WorkingTree::new(repo_path, checkout_files).remove_file(file_path)?;

        // 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 mut tree_update = TreeUpdateBuilder::new();

        tree_update.remove(file_path);

        let mut file_changes = vec![FileChange::Deleted {
            path: file_path.to_string(),
        }];

        // Same commit, so the order index can never be left naming a file this
        // commit removed.
        let (parent_directory, leaf_name) = order::split_parent(file_path);

        file_changes.extend(GitOrder::stage_entry_removed(
            &repo,
            repo_path,
            &head_tree,
            &mut tree_update,
            parent_directory,
            leaf_name,
            checkout_files,
        )?);

        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!("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, change_count = file_changes.len(), "file deletion committed");

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

    /// Removes a whole folder — every file beneath it, recursively — in a
    /// single commit, and returns one `FileChange::Deleted` per file so
    /// downstream systems see each entity disappear individually.
    ///
    /// This is the recursive counterpart of [`Self::delete_file`], reached
    /// only when the caller opted in with `allow_prefix_path_recurse: true`
    /// *and* the path resolves to a folder. It is deliberately a separate
    /// function rather than a mode flag on `delete_file`: the two have
    /// different scopes (one path versus a whole subtree) and different blast
    /// radii, so each keeps one unambiguous meaning.
    ///
    /// The commit tree is HEAD's tree minus the single directory entry —
    /// libgit2's tree updater drops the whole subtree with it, and prunes any
    /// parent directory the removal leaves empty. Cost is therefore
    /// proportional to the path depth, not to the number of files removed;
    /// only the hook list scales with the file count.
    ///
    /// Order indexes travel with the subtree: each one inside it is a blob
    /// like any other, so it is collected and reported as a deletion, which
    /// the hook layer turns into an `order.deleted` event from its path alone.
    /// The *parent* directory's index — which sits outside the subtree — is
    /// rewritten without this folder in the same commit.
    pub fn delete_directory(
        repo_path: &Path,
        tenant_id: &str,
        dir_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %dir_path, author_name = %author_name, author_email = %author_email, "deleting directory recursively");

        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 and kind are decided from HEAD's tree, never from the
        // working tree — a stray on-disk folder is not a reason to commit.
        match head_tree.get_path(Path::new(dir_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
            _ => {
                tracing::debug!(tenant_id = %tenant_id, path = %dir_path, "directory not found for recursive deletion");

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

        let blobs = GitUtils::subtree_blob_paths(&repo, &head_tree, dir_path)?;

        // Git has no empty trees, so this only happens for a folder holding
        // nothing but entries this API cannot represent. Nothing to report
        // downstream means nothing worth committing — same contract as an
        // unchanged PUT.
        if blobs.is_empty() {
            tracing::debug!(tenant_id = %tenant_id, path = %dir_path, "directory holds no files, skipping commit");

            return Ok((parent_commit.id().to_string(), Vec::new()));
        }

        tracing::debug!(tenant_id = %tenant_id, path = %dir_path, file_count = blobs.len(), "staging recursive directory deletion");

        WorkingTree::new(repo_path, checkout_files).remove_directory(dir_path)?;

        let mut tree_update = TreeUpdateBuilder::new();

        tree_update.remove(dir_path);

        let mut file_changes: Vec<FileChange> = blobs
            .iter()
            .map(|(path, _oid)| FileChange::Deleted { path: path.clone() })
            .collect();

        // The parent's index, if it pins this folder, loses that entry in the
        // same commit.
        let (parent_directory, dir_name) = order::split_parent(dir_path);

        file_changes.extend(GitOrder::stage_entry_removed(
            &repo,
            repo_path,
            &head_tree,
            &mut tree_update,
            parent_directory,
            dir_name,
            checkout_files,
        )?);

        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)?;

        // The trailing slash marks this as a folder-wide deletion, so a
        // reader of the history can tell it apart from a single-file one.
        let auto_message = format!("delete: {}/", dir_path);
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(tenant_id = %tenant_id, path = %dir_path, message = %message, "committing recursive directory deletion");

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

        tracing::debug!(tenant_id = %tenant_id, path = %dir_path, sha = %commit_oid, change_count = file_changes.len(), "recursive directory deletion committed");

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

    /// 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.
    ///
    /// Order indexes are kept honest in the same commit, and the two shapes of
    /// move are treated differently on purpose:
    ///
    /// - **A rename inside one directory keeps the file's position** in that
    ///   directory's index. Demoting a file to the tail because its name
    ///   changed would silently reorder content the caller only renamed.
    /// - **A move across directories** drops the file from the source index
    ///   and appends it to the destination index *only when one already
    ///   exists* — creating an index would pin one file in a directory whose
    ///   siblings are all implicitly ordered, which the caller did not ask for.
    // One over clippy's limit: the git layer takes its commit context
    // (message, author, checkout) flat rather than in a struct, as every
    // other write function here does.
    #[allow(clippy::too_many_arguments)]
    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,
        checkout_files: bool,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            author_email = %author_email,
            "moving file"
        );

        // The order index is not addressable through the file routes: as a
        // source it is "not a file", and as a destination it is a path the
        // caller may not write (the order route owns its format).
        if order::is_order_file(from_path) {
            return Err(AppError::FileNotFound {
                path: from_path.to_string(),
            });
        }

        if order::is_order_file(to_path) {
            return Err(AppError::InvalidOperation {
                reason: format!(
                    "destination is reserved for the file order index, write it through /order instead: {}",
                    to_path
                ),
            });
        }

        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 working_tree = WorkingTree::new(repo_path, checkout_files);

        working_tree.remove_file(from_path)?;
        working_tree.write(to_path, content.as_bytes())?;

        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 mut tree_update = TreeUpdateBuilder::new();

        tree_update.remove(from_path);
        tree_update.upsert(to_path, source_blob_oid, FileMode::Blob);

        let mut file_changes = vec![FileChange::Moved {
            from_path: from_path.to_string(),
            to_path: to_path.to_string(),
            content,
        }];

        let (from_directory, from_name) = order::split_parent(from_path);
        let (to_directory, to_name) = order::split_parent(to_path);

        if from_directory == to_directory {
            // A pure rename: the file keeps whatever position it held.
            file_changes.extend(GitOrder::stage_entry_renamed(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                from_directory,
                from_name,
                to_name,
                checkout_files,
            )?);
        } else {
            file_changes.extend(GitOrder::stage_entry_removed(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                from_directory,
                from_name,
                checkout_files,
            )?);

            file_changes.extend(GitOrder::stage_entry_appended(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                to_directory,
                to_name,
                checkout_files,
            )?);
        }

        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!("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,
            change_count = file_changes.len(),
            "file move committed"
        );

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

    /// Relocates a whole folder — every file beneath it, recursively — in a
    /// single commit, and returns one `FileChange::Moved` per file so
    /// downstream systems keep each entity's identity across the rename
    /// instead of seeing a wave of deletes followed by unrelated creates.
    ///
    /// This is the recursive counterpart of [`Self::move_file`], reached only
    /// when the caller opted in with `allow_prefix_path_recurse: true` *and*
    /// the source path resolves to a folder. Each file keeps its own leaf
    /// name — only the ancestor prefix changes — so extensions are preserved
    /// by construction and the `limits.allowed_extensions` whitelist has
    /// nothing left to guard (the destination is a folder path, which carries
    /// no extension of its own).
    ///
    /// The destination must not exist in any form, and must not sit *inside*
    /// the source (which would ask the folder to be moved into itself).
    /// Blob oids are reused verbatim, so no content is rehashed; content is
    /// read once per file purely to fill that file's hook payload, exactly as
    /// the single-file move does.
    ///
    /// Order indexes need no rewriting: their entries are leaf names, so every
    /// index inside the subtree is still correct at its new location. Each one
    /// travels as a moved blob like any other file, which the hook layer turns
    /// into `order.deleted` at the old directory plus `order.updated` at the
    /// new one. The two *parent* indexes — outside the subtree — are updated
    /// in the same commit, with the same rename-keeps-its-position rule as
    /// [`Self::move_file`].
    // One over clippy's limit: the git layer takes its commit context
    // (message, author, checkout) flat rather than in a struct, as every
    // other write function here does.
    #[allow(clippy::too_many_arguments)]
    pub fn move_directory(
        repo_path: &Path,
        tenant_id: &str,
        from_path: &str,
        to_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            author_email = %author_email,
            "moving directory recursively"
        );

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

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

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

        // Moving a folder under itself has no coherent result: the source
        // subtree would have to contain its own relocated copy.
        if to_path.starts_with(&format!("{}/", from_path)) {
            tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, to_path = %to_path, "directory move rejected: destination is inside the source");

            return Err(AppError::InvalidOperation {
                reason: format!(
                    "destination must not be inside the source directory: {}",
                    to_path
                ),
            });
        }

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

        // Existence and kind are decided from HEAD's tree, never from the
        // working tree.
        match head_tree.get_path(Path::new(from_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
            _ => {
                tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source directory not found for move");

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

        // Refuse to merge into an existing destination, whether it is a file
        // or a folder — the caller must delete it first. This also rules out
        // the mirror case of the check above (the source sitting inside the
        // destination), since any ancestor of the source necessarily exists.
        if head_tree.get_path(Path::new(to_path)).is_ok() {
            tracing::debug!(tenant_id = %tenant_id, to_path = %to_path, "directory move rejected: destination already exists");

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

        let blobs = GitUtils::subtree_blob_paths(&repo, &head_tree, from_path)?;

        // Nothing this API can represent lives under the folder, so there is
        // nothing to report downstream and nothing worth committing.
        if blobs.is_empty() {
            tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source directory holds no files, skipping commit");

            return Ok((parent_commit.id().to_string(), Vec::new()));
        }

        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            file_count = blobs.len(),
            "staging recursive directory move"
        );

        let working_tree = WorkingTree::new(repo_path, checkout_files);

        // The commit tree is HEAD's tree with the source folder dropped and
        // every one of its blobs re-attached under the destination prefix,
        // reusing the existing oids — no content rehash, no index round-trip.
        let mut tree_update = TreeUpdateBuilder::new();

        tree_update.remove(from_path);

        let mut file_changes: Vec<FileChange> = Vec::with_capacity(blobs.len());

        for (source_path, blob_oid) in &blobs {
            // Every collected path starts with `from_path/`, so swapping that
            // prefix for `to_path` keeps each file's leaf name — and thus its
            // extension and downstream identity — intact.
            let relative_path = source_path
                .strip_prefix(from_path)
                .and_then(|rest| rest.strip_prefix('/'))
                .unwrap_or(source_path);

            let destination_path = format!("{}/{}", to_path, relative_path);

            // Content comes from HEAD's blob — the authoritative state —
            // rather than whatever the working tree currently holds. It is
            // needed for this file's hook payload either way.
            let content = GitUtils::blob_content_from_tree(&repo, &head_tree, source_path)?;

            working_tree.write(&destination_path, content.as_bytes())?;

            tree_update.upsert(&destination_path, *blob_oid, FileMode::Blob);

            file_changes.push(FileChange::Moved {
                from_path: source_path.clone(),
                to_path: destination_path,
                content,
            });
        }

        // The destination is never inside the source (rejected above), so the
        // freshly written files cannot be swept away by this cleanup.
        working_tree.remove_directory(from_path)?;

        // The parent indexes are settled last, once every file is staged: the
        // folder loses its entry where it came from and gains one where it
        // landed, or keeps its position outright when both are the same parent.
        let (from_parent, from_name) = order::split_parent(from_path);
        let (to_parent, to_name) = order::split_parent(to_path);

        if from_parent == to_parent {
            file_changes.extend(GitOrder::stage_entry_renamed(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                from_parent,
                from_name,
                &order::directory_entry(to_name),
                checkout_files,
            )?);
        } else {
            file_changes.extend(GitOrder::stage_entry_removed(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                from_parent,
                from_name,
                checkout_files,
            )?);

            file_changes.extend(GitOrder::stage_entry_appended(
                &repo,
                repo_path,
                &head_tree,
                &mut tree_update,
                to_parent,
                &order::directory_entry(to_name),
                checkout_files,
            )?);
        }

        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)?;

        // Trailing slashes mark this as a folder-wide move, so a reader of the
        // history can tell it apart from a single-file one.
        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 recursive directory 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_count = file_changes.len(),
            "recursive directory move committed"
        );

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

// ---------------------------------------------------------------------------
// GitOrder — the per-directory file-order index
// ---------------------------------------------------------------------------

/// Reads and writes the per-directory order index, and keeps existing indexes
/// honest as files move and disappear.
///
/// The index is stored as a `.order.json` blob in the directory it orders (see
/// `order.rs` for the format and the reasoning), and every operation here goes
/// through the ordinary write machinery: HEAD is authoritative, the commit tree
/// is built with `TreeUpdateBuilder`, and the working tree is mirrored as a
/// courtesy. Two properties follow from that and are worth stating outright:
///
/// - **An index change is a file change internally.** Every function returns a
///   `FileChange` on the index's own path; the hook layer derives the
///   `order.*` event kind from that path. Nothing here knows about hooks, and
///   nothing else in the system needs a special case for order events —
///   reverts, rollbacks and recursive folder operations classify for free.
/// - **Upkeep rides along in the same commit** as the file operation that
///   triggered it, so a receiver never sees a window in which the order table
///   references a file that no longer exists.
pub struct GitOrder;

impl GitOrder {
    /// Returns the stored order for `directory`, or a 404 when that directory
    /// has no index.
    pub fn read_order(
        repo_path: &Path,
        tenant_id: &str,
        directory: &str,
    ) -> Result<Vec<String>, AppError> {
        tracing::debug!(tenant_id = %tenant_id, directory = %order::display_directory(directory), "reading order index");

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

        Self::stored_order(&repo, &head_tree, directory).ok_or_else(|| AppError::OrderNotFound {
            directory: order::display_directory(directory).to_string(),
        })
    }

    /// Every directory in scope that holds an order index, as a flat list of
    /// repo-root-relative directory paths (`""` for the repository root).
    ///
    /// This is the order-side counterpart of
    /// [`GitFiles::list_all_file_paths`], and the replay route's snapshot of
    /// what a downstream order table should hold. It opens no blob — an index
    /// is located by its tree entry alone, and its content is read later, per
    /// chunk, at delivery time.
    ///
    /// `path_prefix` scopes the walk exactly as it does on the file snapshot
    /// (an absent or non-directory prefix yields an empty list), and
    /// `include_hidden_files` prunes hidden *directories* by the listing's
    /// dot-prefix rule — the index's own dot-prefixed name is never what that
    /// test is about, since an index is not a file to begin with.
    pub fn list_order_directories(
        repo_path: &Path,
        tenant_id: &str,
        path_prefix: Option<&str>,
        include_hidden_files: bool,
    ) -> Result<Vec<String>, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, include_hidden_files = include_hidden_files, "listing order index directories");

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

        let prefix = path_prefix.filter(|prefix| !prefix.is_empty());

        let walk_tree: git2::Tree<'_> = match prefix {
            Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
                Ok(entry) => match repo.find_tree(entry.id()) {
                    Ok(tree) => tree,
                    Err(_not_a_directory) => return Ok(Vec::new()),
                },
                Err(_absent) => return Ok(Vec::new()),
            },
            None => head_tree,
        };

        let mut directories: Vec<String> = Vec::new();

        walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            if entry.kind() == Some(git2::ObjectType::Tree) {
                if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
                    return git2::TreeWalkResult::Skip;
                }

                return git2::TreeWalkResult::Ok;
            }

            if entry.kind() == Some(git2::ObjectType::Blob)
                && entry
                    .name()
                    .is_ok_and(|name| name == order::ORDER_FILE_NAME)
            {
                // `root` is the walk-relative directory with a trailing slash
                // (empty at the walk root), and a directory is spelled without
                // one everywhere an order event carries it.
                directories.push(root.trim_end_matches('/').to_string());
            }

            git2::TreeWalkResult::Ok
        })?;

        // Paths are repo-root-relative, like every other identity on this API.
        let directories: Vec<String> = match prefix {
            Some(prefix) => directories
                .into_iter()
                .map(|directory| {
                    if directory.is_empty() {
                        prefix.to_string()
                    } else {
                        format!("{}/{}", prefix, directory)
                    }
                })
                .collect(),
            None => directories,
        };

        tracing::debug!(tenant_id = %tenant_id, directory_count = directories.len(), "collected order index directories");

        Ok(directories)
    }

    /// Reads the stored order of one chunk of directories for a replay, in a
    /// single repository pass, index-aligned with `directories`.
    ///
    /// `None` marks a directory whose index can no longer be delivered — it
    /// was dropped between the snapshot and now, or it is malformed — on the
    /// same reasoning as [`GitFiles::replay_read_files`]: a replay runs
    /// unattended over a snapshot that may already have moved on, and one
    /// unreadable index must not abort the others. Only a failure to read the
    /// *repository* is an error.
    pub fn replay_read_orders(
        repo_path: &Path,
        tenant_id: &str,
        directories: &[String],
    ) -> Result<Vec<Option<Vec<String>>>, AppError> {
        tracing::trace!(tenant_id = %tenant_id, count = directories.len(), "reading replay order chunk");

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

        Ok(directories
            .iter()
            .map(|directory| Self::stored_order(&repo, &head_tree, directory))
            .collect())
    }

    /// Replaces `directory`'s order index with `order`.
    ///
    /// Every entry is resolved against HEAD's tree and canonicalised from what
    /// it resolved to (a directory gains a trailing slash, a file does not), so
    /// an entry naming something absent is a `400`. That strictness is safe
    /// because the check runs under the tenant write lock, the same lock every
    /// write takes: the classification cannot go stale before the commit it
    /// drives. The order may still be *sparse* — entries must exist, but not
    /// every existing sibling need be listed.
    ///
    /// Writing the order the index already holds is a no-op, exactly as
    /// re-PUTting unchanged file content is: no commit, no hook, and the
    /// returned sha is HEAD's.
    // One over clippy's limit: the git layer takes its commit context
    // (message, author, checkout) flat rather than in a struct, as every
    // other write function here does.
    #[allow(clippy::too_many_arguments)]
    pub fn write_order(
        repo_path: &Path,
        tenant_id: &str,
        directory: &str,
        order_entries: &[String],
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Option<FileChange>), AppError> {
        let display_directory = order::display_directory(directory);

        tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, entry_count = order_entries.len(), author_name = %author_name, author_email = %author_email, "writing order index");

        // No auto-init here, unlike a file write: an order can only name
        // entries that exist, so there is nothing a brand-new repository could
        // accept — and an order route has no business creating a tenant.
        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

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

        // The repository root is always there; any other directory must be.
        if !directory.is_empty() {
            match head_tree.get_path(Path::new(directory)) {
                Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
                _ => {
                    tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "directory not found for order write");

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

        let mut canonical: Vec<String> = Vec::with_capacity(order_entries.len());

        for entry in order_entries {
            let name = order::entry_name(entry);

            let entry_path = if directory.is_empty() {
                name.to_string()
            } else {
                format!("{}/{}", directory, name)
            };

            match head_tree.get_path(Path::new(&entry_path)) {
                Ok(tree_entry) if tree_entry.kind() == Some(git2::ObjectType::Blob) => {
                    canonical.push(name.to_string())
                }
                Ok(tree_entry) if tree_entry.kind() == Some(git2::ObjectType::Tree) => {
                    canonical.push(order::directory_entry(name))
                }
                _ => {
                    tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, entry = %name, "order write rejected: entry does not exist");

                    return Err(AppError::InvalidOperation {
                        reason: format!(
                            "order entry does not exist in '{}': {}",
                            display_directory, name
                        ),
                    });
                }
            }
        }

        let index_path = order::order_file_path(directory);
        let existing_oid = GitUtils::blob_oid_in_tree(&head_tree, &index_path);

        // Hashing the serialised document yields the oid the blob *would* get;
        // matching HEAD's entry means this write changes nothing.
        let incoming_oid = git2::Oid::hash_object(
            git2::ObjectType::Blob,
            order::serialize(&canonical).as_bytes(),
        )?;

        if existing_oid == Some(incoming_oid) {
            tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order unchanged, skipping commit");

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

        let mut tree_update = TreeUpdateBuilder::new();

        let change = Self::stage_index(
            &repo,
            repo_path,
            &mut tree_update,
            directory,
            &canonical,
            existing_oid.is_some(),
            checkout_files,
        )?;

        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!("reorder: {}", display_directory);
        let message = commit_message.unwrap_or(&auto_message);

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

        tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, sha = %commit_oid, "order write committed");

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

    /// Moves one entry to `position` inside its own parent directory's order
    /// index, shifting the entries at and after that position down by one.
    ///
    /// `allow_prefix_path` decides whether the path may name a **directory**
    /// rather than a file. It defaults off at the route, so only files are
    /// positionable unless the caller opts in — the same "the flag permits, it
    /// never forces" rule as `allow_prefix_path_recurse` on delete and move: a
    /// file path with the flag on runs exactly as it would with it off, and a
    /// directory path with it off is simply "not a file" and answers `404`. A
    /// directory entry is stored in the canonical index spelling (a trailing
    /// slash), which is what a stored order needs to be readable without
    /// resolving every name against a tree.
    ///
    /// Positioning an entry **materialises the whole directory** into the
    /// index: every sibling the index does not name yet is folded in first, at
    /// the rank it is rendered with (see [`Self::materialized_order`]), so the
    /// index that comes out pins exactly the sequence the caller was looking at
    /// when they asked for the move. Without that, a position would count
    /// against the listed entries alone while the caller counted against
    /// everything they could see, and the two only agree when the index is
    /// already complete. `implicit_default_index` is where the unlisted
    /// siblings are folded in, and it carries the listing parameter's meaning
    /// exactly (unset: behind everything listed; `0` or negative: above it) —
    /// so a caller reordering inside a rendered listing passes the same value
    /// it rendered with, and the index it gets back is what it saw.
    /// `implicit_allow_hidden_files` decides whether dot-prefixed siblings are
    /// folded in at all; off, they are left out of the generated index (a hidden
    /// entry the index already names is still kept — see
    /// [`Self::materialized_order`]). Whether the *positioned* entry may itself
    /// be hidden is settled at the route, which is where a caller-facing `400`
    /// belongs.
    ///
    /// The entry itself is the one that must be there afterwards, so it is
    /// dropped from wherever it sat and re-inserted at `position` — which makes
    /// the position count against the rest of the directory, the intuitive
    /// reading of "move this to slot N".
    ///
    /// A `position` beyond the end of the resulting index is clamped to the
    /// tail rather than rejected: it is not something a caller can be expected
    /// to compute, and "as far down as possible" is unambiguous. A directory
    /// with no index yet gets one — unlike implicit upkeep, which never creates
    /// an index, this is an explicit request for a position, exactly as
    /// `PUT /order` is.
    ///
    /// [`OrderPosition::Unlisted`] is the inverse operation on the same route:
    /// the entry is dropped from the index and not re-inserted, leaving it
    /// implicitly ordered again. Nothing else changes — the file or folder itself
    /// is untouched, and the index is *not* materialised (unpinning one entry has
    /// no business pinning every other one), so an already-unlisted entry stays a
    /// no-op. When the entry was the index's last one the index is removed rather
    /// than stored empty (an `order.deleted` event), the same rule every other
    /// producer follows.
    ///
    /// Asking for the state the index already holds is a no-op, exactly as
    /// re-PUTting unchanged file content is: no commit, no hook, HEAD's sha.
    /// That covers both directions — the entry already sitting at `position`,
    /// and an already-unlisted entry asked to be unlisted (including when the
    /// directory has no index at all).
    #[allow(clippy::too_many_arguments)]
    pub fn reorder_entry(
        repo_path: &Path,
        tenant_id: &str,
        entry_path: &str,
        position: OrderPosition,
        implicit_default_index: Option<i64>,
        implicit_allow_hidden_files: bool,
        allow_prefix_path: bool,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Option<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %entry_path, position = ?position, implicit_default_index = ?implicit_default_index, implicit_allow_hidden_files = implicit_allow_hidden_files, allow_prefix_path = allow_prefix_path, author_name = %author_name, author_email = %author_email, "reordering order index entry");

        // The index is not a file, so it cannot be given a position of its own
        // — to the `/files` routes it simply does not exist.
        if order::is_order_file(entry_path) {
            return Err(AppError::FileNotFound {
                path: entry_path.to_string(),
            });
        }

        // No auto-init here, as on every other order operation: a position can
        // only be given to something that exists.
        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

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

        let (directory, name) = order::split_parent(entry_path);
        let display_directory = order::display_directory(directory);

        // Classified against HEAD's tree, under the tenant write lock, so the
        // classification cannot go stale before the commit it drives. A folder
        // only counts when the caller opted in; without the flag it is "not a
        // file" and answers `404`, exactly as on a read or a plain delete.
        let canonical_entry = match head_tree.get_path(Path::new(entry_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => name.to_string(),

            Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) && allow_prefix_path => {
                order::directory_entry(name)
            }

            _ => {
                tracing::debug!(tenant_id = %tenant_id, path = %entry_path, allow_prefix_path = allow_prefix_path, "entry not found for reorder");

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

        let index_path = order::order_file_path(directory);
        let existing_oid = GitUtils::blob_oid_in_tree(&head_tree, &index_path);

        let stored = Self::stored_order(&repo, &head_tree, directory).unwrap_or_default();

        // A position is asked for against the directory as the caller sees it,
        // so the index is materialised first: every sibling it does not name
        // yet joins it at the rank it renders with. `Unlisted` skips that — it
        // says "stop pinning this entry", which is no reason to start pinning
        // all the others.
        let mut entries: Vec<String> = match position {
            OrderPosition::At(_) => Self::materialized_order(
                &repo,
                &head_tree,
                directory,
                &stored,
                implicit_default_index,
                implicit_allow_hidden_files,
            )?,

            OrderPosition::Unlisted => stored,
        };

        // Dropped from wherever it sat first, so `position` counts against the
        // other entries alone — moving an entry to the index it already holds
        // then lands it right back where it was. Matching ignores the
        // directory-marking slash, so a stale spelling cannot leave a duplicate
        // behind.
        entries.retain(|entry| order::entry_name(entry) != name);

        // `Unlisted` stops here: the entry is dropped and never re-inserted.
        // The position it actually landed at (after clamping) is kept for the
        // log line, so it records where the entry went rather than what was
        // asked for.
        let inserted_at = match position {
            OrderPosition::At(position) => {
                let position = position.min(entries.len());

                entries.insert(position, canonical_entry);

                Some(position)
            }

            OrderPosition::Unlisted => None,
        };

        // An index left with no entries is removed rather than stored empty (an
        // empty index and no index are the same state), so the "does this change
        // anything" question is asked of the two states separately: an empty
        // result changes nothing when there was no index to begin with, and a
        // non-empty one changes nothing when it hashes to what HEAD already
        // holds. Hashing the serialised document yields the oid the blob *would*
        // get, so neither branch touches the object database.
        let unchanged = if entries.is_empty() {
            existing_oid.is_none()
        } else {
            let incoming_oid = git2::Oid::hash_object(
                git2::ObjectType::Blob,
                order::serialize(&entries).as_bytes(),
            )?;

            existing_oid == Some(incoming_oid)
        };

        if unchanged {
            tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order unchanged, skipping commit");

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

        let mut tree_update = TreeUpdateBuilder::new();

        let change = Self::stage_index(
            &repo,
            repo_path,
            &mut tree_update,
            directory,
            &entries,
            existing_oid.is_some(),
            checkout_files,
        )?;

        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!("reorder: {}", entry_path);
        let message = commit_message.unwrap_or(&auto_message);

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

        tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, position = ?inserted_at, sha = %commit_oid, "order reorder committed");

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

    /// Drops `directory`'s order index, so the directory falls back to the
    /// ordinary listing order. A directory with no index is a 404 — there is
    /// nothing to delete, and reporting success would hide a caller mistake.
    pub fn delete_order(
        repo_path: &Path,
        tenant_id: &str,
        directory: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, FileChange), AppError> {
        let display_directory = order::display_directory(directory);

        tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, author_name = %author_name, author_email = %author_email, "deleting order index");

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

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

        let index_path = order::order_file_path(directory);

        if GitUtils::blob_oid_in_tree(&head_tree, &index_path).is_none() {
            tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order index not found for deletion");

            return Err(AppError::OrderNotFound {
                directory: display_directory.to_string(),
            });
        }

        let mut tree_update = TreeUpdateBuilder::new();

        // An empty order stages a removal — an index holding nothing and no
        // index at all are the same state.
        let change = Self::stage_index(
            &repo,
            repo_path,
            &mut tree_update,
            directory,
            &[],
            true,
            checkout_files,
        )?;

        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!("reorder: {}", display_directory);
        let message = commit_message.unwrap_or(&auto_message);

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

        tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, sha = %commit_oid, "order deletion committed");

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

    /// The order stored for `directory` (relative to `tree`), or `None` when
    /// there is no index or it cannot be read as one.
    ///
    /// A malformed index degrades to "no index" rather than to an error: only
    /// this server's order route writes the file, so a broken one can only
    /// come from a hand-edited commit, and that must not be able to fail every
    /// listing of the directory.
    fn stored_order(
        repo: &Repository,
        tree: &git2::Tree<'_>,
        directory: &str,
    ) -> Option<Vec<String>> {
        let index_path = order::order_file_path(directory);
        let index_oid = GitUtils::blob_oid_in_tree(tree, &index_path)?;
        let blob = repo.find_blob(index_oid).ok()?;

        let parsed = order::parse(std::str::from_utf8(blob.content()).ok()?);

        if parsed.is_none() {
            tracing::warn!(path = %index_path, "order index is malformed, ignoring it");
        }

        parsed
    }

    /// `directory`'s complete order, as it is *rendered* right now: every entry
    /// the directory holds in HEAD, ranked by `stored` exactly as a listing
    /// ranks it, with the entries `stored` does not name folded in at
    /// `implicit_default_index` (unset meaning "behind everything listed", the
    /// default sparse-index behaviour).
    ///
    /// This is what turns a numerical position into the one the caller means. A
    /// caller positions an entry against the directory they are looking at, and
    /// what they are looking at is the rendered order — not the index, which may
    /// name two of the twenty siblings on screen. Materialising through the same
    /// ranking the listing uses makes "put this third" mean the third row, and it
    /// keeps every other entry exactly where it was rendered.
    ///
    /// Sharing [`GitFiles::order_rank`] is the point rather than a convenience:
    /// were the two rankings to drift, a reorder would silently permute rows the
    /// caller never touched. Stale entries — names the index holds but the
    /// directory no longer has — are dropped in passing, since the result is
    /// built from what HEAD actually holds; read paths stay tolerant of them, but
    /// there is no reason to write one back.
    ///
    /// `allow_hidden_files` decides whether dot-prefixed siblings are folded in.
    /// Off (the default at the route) they are left out, so materialising an
    /// index does not quietly pin the metadata a repository happens to carry —
    /// the same judgement `include_hidden_files=false` makes on a listing, and
    /// the reason it is the *default* here too: this index is generated by the
    /// server from a directory, not dictated entry by entry. A hidden entry the
    /// stored index **already names** is kept regardless: it was pinned
    /// deliberately (through this flag, or `allow_hidden_files` on `PUT /order`),
    /// and positioning an unrelated file is no occasion to unpin it.
    ///
    /// A directory absent from HEAD yields nothing, which cannot happen through
    /// the reorder route (the entry itself was just resolved inside it) and would
    /// leave the caller's entry as the index's only member if it ever did.
    fn materialized_order(
        repo: &Repository,
        head_tree: &git2::Tree<'_>,
        directory: &str,
        stored: &[String],
        implicit_default_index: Option<i64>,
        allow_hidden_files: bool,
    ) -> Result<Vec<String>, AppError> {
        let mut entries = Self::directory_entries(repo, head_tree, directory)?;

        let ranks = GitFiles::order_ranks(stored);
        let order_options = OrderOptions {
            implicit_default_index,
        };

        if !allow_hidden_files {
            entries.retain(|entry| {
                !order::is_hidden(entry) || ranks.contains_key(order::entry_name(entry))
            });
        }

        // Stable, so the entries sharing a rank — all the unlisted ones — keep
        // the ordinary listing order they came in with.
        entries.sort_by_key(|entry| {
            GitFiles::order_rank(&ranks, order::entry_name(entry), &order_options)
        });

        Ok(entries)
    }

    /// Every entry `directory` holds in HEAD, in the ordinary listing order
    /// (directories first, then alphabetical) and in the canonical index
    /// spelling (directories with a trailing slash, files without).
    ///
    /// Read from tree objects alone, one level deep — an index orders siblings,
    /// so nothing below the directory is any of its business. The index file
    /// itself is skipped: it is not an entry of the directory it orders.
    /// Anything that is neither a blob nor a tree (a submodule) is left out,
    /// exactly as it is everywhere else in this API. Hidden entries are returned
    /// here and filtered by the caller, which is the only place that knows
    /// whether one was already pinned.
    fn directory_entries(
        repo: &Repository,
        head_tree: &git2::Tree<'_>,
        directory: &str,
    ) -> Result<Vec<String>, AppError> {
        let subtree;

        let tree = if directory.is_empty() {
            head_tree
        } else {
            match head_tree.get_path(Path::new(directory)) {
                Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {
                    subtree = entry.to_object(repo)?.peel_to_tree()?;

                    &subtree
                }

                _ => return Ok(Vec::new()),
            }
        };

        let mut directories: Vec<String> = Vec::new();
        let mut files: Vec<String> = Vec::new();

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

            if entry_name == order::ORDER_FILE_NAME {
                continue;
            }

            match entry.kind() {
                Some(git2::ObjectType::Tree) => {
                    directories.push(order::directory_entry(entry_name))
                }

                Some(git2::ObjectType::Blob) => files.push(entry_name.to_string()),

                _ => {}
            }
        }

        directories.sort();
        files.sort();

        directories.extend(files);

        Ok(directories)
    }

    /// Zero-based position of `name` in `directory`'s stored order, or
    /// [`order::UNLISTED_POSITION`] when the index does not name it.
    ///
    /// "No index", "an unparseable index" and "an index that does not list this
    /// name" all collapse to the same answer, because they are the same answer:
    /// nothing pins this entry. Matching ignores the directory-marking trailing
    /// slash, so a directory reports the position it holds under either
    /// spelling.
    fn entry_position(
        repo: &Repository,
        tree: &git2::Tree<'_>,
        directory: &str,
        name: &str,
    ) -> i64 {
        Self::stored_order(repo, tree, directory)
            .and_then(|stored| {
                stored
                    .iter()
                    .position(|entry| order::entry_name(entry) == name)
            })
            .map_or(order::UNLISTED_POSITION, |position| position as i64)
    }

    /// Stages `directory`'s index to hold `order_entries` — or removes the
    /// index when they are empty — mirroring the change onto the working tree,
    /// and returns the change recorded for the index blob itself.
    ///
    /// `index_existed` only picks between a created and an updated change; both
    /// become the same `order.updated` event, but the distinction keeps the
    /// change list honest for anything else reading it.
    fn stage_index(
        repo: &Repository,
        repo_path: &Path,
        tree_update: &mut TreeUpdateBuilder,
        directory: &str,
        order_entries: &[String],
        index_existed: bool,
        checkout_files: bool,
    ) -> Result<FileChange, AppError> {
        let index_path = order::order_file_path(directory);
        let working_tree = WorkingTree::new(repo_path, checkout_files);

        if order_entries.is_empty() {
            tracing::trace!(path = %index_path, "staging order index removal");

            working_tree.remove_file(&index_path)?;

            tree_update.remove(&index_path);

            return Ok(FileChange::Deleted { path: index_path });
        }

        tracing::trace!(path = %index_path, entry_count = order_entries.len(), "staging order index write");

        let content = order::serialize(order_entries);

        working_tree.write(&index_path, content.as_bytes())?;

        let blob_oid = repo.blob(content.as_bytes())?;

        tree_update.upsert(&index_path, blob_oid, FileMode::Blob);

        Ok(if index_existed {
            FileChange::Updated {
                path: index_path,
                content,
            }
        } else {
            FileChange::Created {
                path: index_path,
                content,
            }
        })
    }

    /// Drops `name` from `directory`'s index. `None` when there is no index
    /// there, or when it does not list `name` — upkeep never creates an index
    /// and never rewrites one it has nothing to say about.
    fn stage_entry_removed(
        repo: &Repository,
        repo_path: &Path,
        head_tree: &git2::Tree<'_>,
        tree_update: &mut TreeUpdateBuilder,
        directory: &str,
        name: &str,
        checkout_files: bool,
    ) -> Result<Option<FileChange>, AppError> {
        let Some(stored) = Self::stored_order(repo, head_tree, directory) else {
            return Ok(None);
        };

        let entry_count = stored.len();

        let retained: Vec<String> = stored
            .into_iter()
            .filter(|entry| order::entry_name(entry) != name)
            .collect();

        if retained.len() == entry_count {
            return Ok(None);
        }

        Self::stage_index(
            repo,
            repo_path,
            tree_update,
            directory,
            &retained,
            true,
            checkout_files,
        )
        .map(Some)
    }

    /// Appends `canonical_entry` to `directory`'s index, at the tail.
    ///
    /// `None` when there is no index there — an index is only ever *edited* by
    /// upkeep, never created: pinning one file in a directory whose siblings
    /// are all implicitly ordered would be a surprise the caller did not ask
    /// for. Also `None` when the entry is already listed (which a stale entry
    /// left by a revert can make true), so upkeep never duplicates a name.
    fn stage_entry_appended(
        repo: &Repository,
        repo_path: &Path,
        head_tree: &git2::Tree<'_>,
        tree_update: &mut TreeUpdateBuilder,
        directory: &str,
        canonical_entry: &str,
        checkout_files: bool,
    ) -> Result<Option<FileChange>, AppError> {
        let Some(mut stored) = Self::stored_order(repo, head_tree, directory) else {
            return Ok(None);
        };

        let name = order::entry_name(canonical_entry);

        if stored.iter().any(|entry| order::entry_name(entry) == name) {
            return Ok(None);
        }

        stored.push(canonical_entry.to_string());

        Self::stage_index(
            repo,
            repo_path,
            tree_update,
            directory,
            &stored,
            true,
            checkout_files,
        )
        .map(Some)
    }

    /// Replaces `from_name` with `canonical_entry` **in place**, keeping the
    /// entry's position. `None` when there is no index there, or when it does
    /// not list `from_name` — an unlisted entry stays unlisted, since a rename
    /// changes a name and should not change an ordering.
    // One over clippy's limit: the git layer takes its commit context
    // (message, author, checkout) flat rather than in a struct, as every
    // other write function here does.
    #[allow(clippy::too_many_arguments)]
    fn stage_entry_renamed(
        repo: &Repository,
        repo_path: &Path,
        head_tree: &git2::Tree<'_>,
        tree_update: &mut TreeUpdateBuilder,
        directory: &str,
        from_name: &str,
        canonical_entry: &str,
        checkout_files: bool,
    ) -> Result<Option<FileChange>, AppError> {
        let Some(mut stored) = Self::stored_order(repo, head_tree, directory) else {
            return Ok(None);
        };

        let Some(position) = stored
            .iter()
            .position(|entry| order::entry_name(entry) == from_name)
        else {
            return Ok(None);
        };

        stored[position] = canonical_entry.to_string();

        Self::stage_index(
            repo,
            repo_path,
            tree_update,
            directory,
            &stored,
            true,
            checkout_files,
        )
        .map(Some)
    }
}

// ---------------------------------------------------------------------------
// 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,
        checkout_files: bool,
    ) -> 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();

        let working_tree = WorkingTree::new(repo_path, checkout_files);

        // 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"
                        );

                        working_tree.remove_file(new_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(),
                        )?;

                        working_tree.write(old_path, content.as_bytes())?;

                        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(),
                        )?;

                        working_tree.write(old_path, content.as_bytes())?;

                        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(),
                        )?;

                        working_tree.remove_file(new_path)?;
                        working_tree.write(old_path, content.as_bytes())?;

                        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))
    }

    /// Rolls every file the commit `sha` touched back to the exact state it
    /// had *at* that commit — point-in-time rollback, the "time machine"
    /// counterpart to the whole-commit revert above. Returns the new commit
    /// SHA and one change per file that actually moved (empty when the
    /// repository already holds that state).
    ///
    /// Which files are in scope is derived from `sha` itself — the same delta
    /// set a revert walks — so the caller passes no paths: the commit already
    /// says what it touched. What differs from `revert_commit` is which *side*
    /// of the target commit is restored. A revert restores `parent(sha)` (undo
    /// what that commit did); a rollback restores `sha` itself (make those
    /// files look the way they looked then), collapsing every later change to
    /// those paths into one commit. Rolling back to the root commit is legal —
    /// with no parent, its delta set is simply its whole tree.
    ///
    /// The target state is read from `sha`'s tree and staged onto **current
    /// HEAD**, reusing existing blob oids so no content is rehashed. Per file:
    ///
    /// - present at `sha`, absent in HEAD → re-created (a file deleted since
    ///   comes back from the dead)
    /// - present at `sha`, different in HEAD → updated
    /// - absent at `sha` (the commit deleted it), present in HEAD → deleted
    ///   again
    /// - identical on both sides → skipped entirely: no staging, no hook
    ///
    /// A rename inside the commit rolls back as a rename (one `file.moved`
    /// hook, preserving downstream entity identity) whenever HEAD still holds
    /// the pre-rename path and not the post-rename one; otherwise each side is
    /// settled on its own. When nothing at all needs to move, no commit is
    /// created and HEAD's sha is returned — same contract as an unchanged PUT.
    ///
    /// History is never rewritten: the rollback is a new commit on top, and
    /// the state it replaces stays reachable through its own commit.
    pub fn rollback_commit(
        repo_path: &Path,
        tenant_id: &str,
        sha: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
        checkout_files: bool,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, sha = %sha, author_name = %author_name, author_email = %author_email, "rolling files back to commit");

        // Stages `path` holding `oid` — the state at the target commit —
        // unless HEAD already holds that exact blob, in which case there is
        // nothing to roll back for this path.
        fn restore_path(
            repo: &Repository,
            working_tree: &WorkingTree<'_>,
            head_tree: &git2::Tree<'_>,
            target_tree: &git2::Tree<'_>,
            tree_update: &mut TreeUpdateBuilder,
            path: &Path,
            oid: Oid,
        ) -> Result<Option<FileChange>, AppError> {
            let path_string = path.to_string_lossy().into_owned();
            let head_oid = GitUtils::blob_oid_in_tree(head_tree, &path_string);

            if head_oid == Some(oid) {
                tracing::trace!(path = %path_string, "rollback: file already in target state");

                return Ok(None);
            }

            tracing::trace!(
                path = %path_string,
                existed_in_head = head_oid.is_some(),
                "rollback: restoring file content from target commit"
            );

            let content = GitUtils::blob_content_from_tree(repo, target_tree, &path_string)?;

            working_tree.write(path, content.as_bytes())?;

            tree_update.upsert(path, oid, FileMode::Blob);

            Ok(Some(if head_oid.is_some() {
                FileChange::Updated {
                    path: path_string,
                    content,
                }
            } else {
                FileChange::Created {
                    path: path_string,
                    content,
                }
            }))
        }

        // Stages the removal of `path` — absent at the target commit — unless
        // HEAD does not hold it as a file either.
        fn remove_path(
            working_tree: &WorkingTree<'_>,
            head_tree: &git2::Tree<'_>,
            tree_update: &mut TreeUpdateBuilder,
            path: &Path,
        ) -> Result<Option<FileChange>, AppError> {
            let path_string = path.to_string_lossy().into_owned();

            if GitUtils::blob_oid_in_tree(head_tree, &path_string).is_none() {
                tracing::trace!(path = %path_string, "rollback: file already absent");

                return Ok(None);
            }

            tracing::trace!(path = %path_string, "rollback: removing file absent from target commit");

            working_tree.remove_file(path)?;

            tree_update.remove(path);

            Ok(Some(FileChange::Deleted { path: path_string }))
        }

        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(),
            })?;

        let target_tree = target_commit.tree()?;

        // Diff parent → target tells us which paths this commit touched, and
        // what each of them looked like once it landed. The root commit has no
        // parent, so it diffs against nothing: its whole tree is in scope.
        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "computing diff for rollback");

        let parent_tree = match target_commit.parent_count() {
            0 => None,
            _ => Some(target_commit.parent(0)?.tree()?),
        };

        let mut diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&target_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 rollback deltas");

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

        // The rollback tree is HEAD's tree with each touched path forced back
        // to its target-commit state — no index round-trip, no rehashing.
        let mut tree_update = TreeUpdateBuilder::new();

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

        let working_tree = WorkingTree::new(repo_path, checkout_files);

        // For each delta: mirror the target state 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 {
                // The commit created or changed this file → restore that version.
                Delta::Added | Delta::Modified => {
                    if let Some(new_path) = &raw_delta.new_path {
                        let change = restore_path(
                            &repo,
                            &working_tree,
                            &head_tree,
                            &target_tree,
                            &mut tree_update,
                            new_path,
                            raw_delta.new_oid,
                        )?;

                        file_changes.extend(change);
                    }
                }

                // The commit deleted this file → at that point in time it was
                // gone, so rolling back deletes it again.
                Delta::Deleted => {
                    if let Some(old_path) = &raw_delta.old_path {
                        let change =
                            remove_path(&working_tree, &head_tree, &mut tree_update, old_path)?;

                        file_changes.extend(change);
                    }
                }

                // The commit renamed old → new. Rolling back re-applies that
                // rename; when HEAD still has the file under its old name and
                // nothing at the new one, it is reported as a single move so
                // downstream receivers keep the entity's identity instead of
                // seeing a delete followed by an unrelated create.
                Delta::Renamed => {
                    if let (Some(old_path), Some(new_path)) =
                        (&raw_delta.old_path, &raw_delta.new_path)
                    {
                        let old_in_head =
                            GitUtils::blob_oid_in_tree(&head_tree, &old_path.to_string_lossy())
                                .is_some();
                        let new_in_head =
                            GitUtils::blob_oid_in_tree(&head_tree, &new_path.to_string_lossy())
                                .is_some();

                        if old_in_head && !new_in_head {
                            tracing::trace!(
                                tenant_id = %tenant_id,
                                sha = %sha,
                                from_path = %old_path.display(),
                                to_path = %new_path.display(),
                                "rollback: re-applying rename"
                            );

                            let content = GitUtils::blob_content_from_tree(
                                &repo,
                                &target_tree,
                                &new_path.to_string_lossy(),
                            )?;

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

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

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

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

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

                            file_changes.push(FileChange::Moved {
                                from_path: old_path.to_string_lossy().into_owned(),
                                to_path: new_path.to_string_lossy().into_owned(),
                                content,
                            });
                        } else {
                            // HEAD's shape does not match a plain rename-back
                            // (the destination is occupied, or the source is
                            // already gone), so each side is settled on its
                            // own terms.
                            let restored = restore_path(
                                &repo,
                                &working_tree,
                                &head_tree,
                                &target_tree,
                                &mut tree_update,
                                new_path,
                                raw_delta.new_oid,
                            )?;

                            file_changes.extend(restored);

                            let removed =
                                remove_path(&working_tree, &head_tree, &mut tree_update, old_path)?;

                            file_changes.extend(removed);
                        }
                    }
                }

                _ => {}
            }
        }

        // Every staged path yields exactly one change, so an empty list means
        // the repository already holds the target state: no commit, no hook.
        if file_changes.is_empty() {
            tracing::debug!(tenant_id = %tenant_id, sha = %sha, "files already in target state, skipping commit");

            return Ok((head_commit.id().to_string(), file_changes));
        }

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "building rollback 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!("rollback: {}", target_commit.message().unwrap_or("unknown"));
        let message = commit_message.unwrap_or(&auto_message);

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

        tracing::debug!(
            tenant_id = %tenant_id,
            rolled_back_to_sha = %sha,
            new_sha = %new_commit_oid,
            file_change_count = file_changes.len(),
            "rollback 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.
    /// Removed through [`GitStaging::remove`], so a concurrent read sees the
    /// tenant vanish at once rather than a half-deleted repository.
    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(),
            });
        }

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

            err
        })?;

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

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// GitReplication — packfile export/import for read-only replicas
// ---------------------------------------------------------------------------

/// One repository as seen by the replication surface: its identity plus the
/// commit its HEAD currently points at.
#[derive(Debug, Serialize)]
pub struct RepositoryHead {
    pub collection_id: String,
    pub tenant_id: String,
    pub head_sha: String,
}

/// What one scan of `repos_root` found, and whether it found everything.
///
/// `complete` is the field a replica's safety rests on: it may only infer
/// deletions — repositories it holds and the master does not — from a scan
/// that describes the master's *entire* set. A directory that could not be
/// read or a repository that could not be opened therefore flips it to
/// `false` rather than being silently left out, because an omission a
/// replica cannot tell from a deletion would make it delete live tenants.
#[derive(Debug, Default)]
pub struct RepositoryScan {
    pub repositories: Vec<RepositoryHead>,
    pub complete: bool,
}

/// What probing one tenant directory for its HEAD found.
enum HeadProbe {
    At(String),
    /// No `.git`, or a repository with no commit yet — nothing to list.
    NotARepository,
    /// A `.git` is there but could not be opened or read: the repository
    /// exists and its state is unknown, which is not the same as absent.
    Unreadable,
}

/// Outcome of applying a replication packfile to a local repository.
///
/// githttp-fs history is append-only — revert and rollback both *add*
/// commits, and nothing ever rewrites one — so in normal operation a
/// replica's HEAD is always an ancestor of its master's and the answer is
/// `FastForwarded` or `UpToDate`. The two refusals are told apart because
/// they mean different things to an operator, even though the replica reacts
/// to both the same way (it keeps its copy, stops syncing that repository,
/// and says so):
///
/// - `Ahead`: the announced head is an ancestor of the local one. The
///   replica holds *more* history than the node it follows — a master
///   restored from a backup, or a chained upstream that restarted behind.
///   Nothing is wrong with the local copy; the upstream is what is behind.
/// - `Diverged`: neither head descends from the other. A tenant deleted and
///   re-created under the same identity (a brand-new root commit), or a
///   manual promotion that forked history.
///
/// Neither is ever resolved by this code discarding the local repository:
/// the replica locks the repository out of replication and leaves the
/// decision to a human, who can delete the local copy if a re-clone is what
/// they want.
#[derive(Debug)]
pub enum PackApply {
    FastForwarded { from: Option<String>, to: String },
    UpToDate,
    Ahead { local: String, remote: String },
    Diverged { local: String, remote: String },
}

/// How a commit the upstream announced relates to this repository's HEAD,
/// answered from local objects alone — before any pack is requested.
///
/// A replica that is *ahead* of its upstream already holds the announced
/// commit, so it can tell without a download; asking for a pack would make
/// the upstream (which does not know the replica's newer `have`) send a full
/// clone that is then refused, on every poll, for as long as the situation
/// lasts.
#[derive(Debug, PartialEq, Eq)]
pub enum HeadRelation {
    /// The announced commit is not in the local object store: a pack is
    /// needed to say anything more.
    Unknown,
    /// The announced commit is HEAD.
    Same,
    /// The announced commit is a strict ancestor of HEAD.
    Ahead { local: String },
    /// The announced commit is held locally but is neither HEAD nor one of
    /// its ancestors (it can only have arrived through an earlier pack whose
    /// ref move never happened, or a hand-edited repository).
    Diverged { local: String },
}

/// Git-level replication primitives: enumerate repositories, export a
/// packfile of the objects a replica is missing, import one back.
///
/// Everything here works on the object database directly. libgit2's network
/// transports are deliberately not used (this build compiles git2 without
/// the `https`/`ssh` features, so they are not even present) — packfiles
/// travel over the same axum/reqwest stack as the rest of the API, which
/// keeps replication inside the existing auth, TLS, and tracing story
/// instead of standing up a second protocol.
pub struct GitReplication;

impl GitReplication {
    /// Reads a repository's HEAD commit sha, or `None` when the repository
    /// does not exist, cannot be opened, or has no commit yet.
    ///
    /// Deliberately total rather than fallible: every caller treats "no
    /// usable HEAD" the same way ("this repository needs a full clone"), and
    /// a replica scanning thousands of directories must not abort its whole
    /// reconcile because one of them is mid-creation.
    pub fn head_sha(repo_path: &Path) -> Option<String> {
        match Self::probe_head(repo_path) {
            HeadProbe::At(head_sha) => Some(head_sha),
            HeadProbe::NotARepository | HeadProbe::Unreadable => None,
        }
    }

    /// Like [`Self::head_sha`], but tells "not a repository" apart from "a
    /// repository I could not read" — the scan needs that distinction to
    /// report whether it is complete.
    fn probe_head(repo_path: &Path) -> HeadProbe {
        if !repo_path.join(".git").exists() {
            return HeadProbe::NotARepository;
        }

        let repo = match Repository::open(repo_path) {
            Ok(repo) => repo,
            Err(err) => {
                tracing::warn!(path = %repo_path.display(), err = %err, "repository cannot be opened");

                return HeadProbe::Unreadable;
            }
        };

        let probe = match repo.head() {
            Ok(head) => match head.target() {
                Some(head_oid) => HeadProbe::At(head_oid.to_string()),
                None => HeadProbe::Unreadable,
            },
            // An initialised repository with no commit yet: a replica whose
            // first import was interrupted before the ref moved. There is
            // nothing to list, and nothing is wrong.
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => HeadProbe::NotARepository,
            Err(err) => {
                tracing::warn!(path = %repo_path.display(), err = %err, "repository HEAD cannot be read");

                HeadProbe::Unreadable
            }
        };

        probe
    }

    /// Enumerates every repository under `repos_root` with its HEAD sha.
    ///
    /// This is the whole-state snapshot both sides of a reconcile compare:
    /// the master serves it from `GET /_replication/state`, and a replica
    /// runs the same walk over its own disk. Only names the API could have
    /// created are considered — anything the identifier validators reject
    /// (the dot-prefixed `.replication.json` and `.replication-incoming/`
    /// among them) is not a tenant and is skipped without comment. A
    /// directory that is not a repository is skipped too. But a directory
    /// that cannot be *read*, or a repository that cannot be *opened*, marks
    /// the scan incomplete rather than being dropped: a replica must never
    /// mistake "the master could not describe this" for "the master no
    /// longer has this".
    ///
    /// Cost is one directory scan plus one ref read per repository, which is
    /// why callers go through `replication::RepositoryIndex` rather than
    /// calling this on every request.
    pub fn list_repositories(repos_root: &Path) -> RepositoryScan {
        let mut scan = RepositoryScan {
            repositories: Vec::new(),
            complete: true,
        };

        let collections = match std::fs::read_dir(repos_root) {
            Ok(collections) => collections,
            Err(err) => {
                tracing::warn!(
                    path = %repos_root.display(),
                    err = %err,
                    "repositories root cannot be read, listing is incomplete"
                );

                scan.complete = false;

                return scan;
            }
        };

        for collection_entry in collections {
            let Ok(collection_entry) = collection_entry else {
                scan.complete = false;

                continue;
            };

            let Some(collection_id) =
                Self::scannable_name(&collection_entry, validate::collection_id)
            else {
                continue;
            };

            let collection_path = collection_entry.path();

            if !collection_path.is_dir() {
                continue;
            }

            let tenants = match std::fs::read_dir(&collection_path) {
                Ok(tenants) => tenants,
                Err(err) => {
                    tracing::warn!(
                        path = %collection_path.display(),
                        err = %err,
                        "collection directory cannot be read, listing is incomplete"
                    );

                    scan.complete = false;

                    continue;
                }
            };

            for tenant_entry in tenants {
                let Ok(tenant_entry) = tenant_entry else {
                    scan.complete = false;

                    continue;
                };

                let Some(tenant_id) = Self::scannable_name(&tenant_entry, validate::tenant_id)
                else {
                    continue;
                };

                let tenant_path = tenant_entry.path();

                if !tenant_path.is_dir() {
                    continue;
                }

                match Self::probe_head(&tenant_path) {
                    HeadProbe::At(head_sha) => scan.repositories.push(RepositoryHead {
                        collection_id: collection_id.clone(),
                        tenant_id,
                        head_sha,
                    }),
                    HeadProbe::NotARepository => {}
                    HeadProbe::Unreadable => scan.complete = false,
                }
            }
        }

        scan
    }

    /// A directory entry's name, if it is one this API could have created.
    fn scannable_name(
        entry: &std::fs::DirEntry,
        validator: fn(&str) -> Result<&str, AppError>,
    ) -> Option<String> {
        let name = entry.file_name();
        let name = name.to_str()?;

        validator(name).ok().map(str::to_string)
    }

    /// Builds a packfile holding every object reachable from `head_sha` but
    /// not from `have`, handing each chunk to `on_chunk` as it is produced.
    /// Returning `false` from `on_chunk` aborts the build (the receiver hung
    /// up), which surfaces here as a git error.
    ///
    /// **No tenant write lock is taken, and none is needed.** The walk reads
    /// objects reachable from a commit that already exists, and two
    /// properties make those objects immortal: history is append-only, so a
    /// commit reachable from the HEAD we were given stays reachable from
    /// every later HEAD; and maintenance only ever drops objects that are
    /// *un*reachable. So no concurrent write or repack can remove anything
    /// this walk needs. A repack running concurrently can still invalidate
    /// libgit2's view of the pack directory mid-build, which surfaces as a
    /// transient error — the replica simply retries on its next pass rather
    /// than this side holding a lock across what may be a multi-second
    /// full-clone build.
    ///
    /// An unknown `have` (a replica reporting a commit this repository has
    /// never held) is ignored rather than rejected, degrading to a full
    /// pack. That is the honest answer: we cannot compute a delta against a
    /// history we do not have, and refusing would strand the replica.
    pub fn build_pack<F>(
        repo_path: &Path,
        tenant_id: &str,
        head_sha: &str,
        have: Option<&str>,
        mut on_chunk: F,
    ) -> Result<usize, AppError>
    where
        F: FnMut(&[u8]) -> bool,
    {
        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let head_oid = Oid::from_str(head_sha).map_err(|_err| AppError::CommitNotFound {
            sha: head_sha.to_string(),
        })?;

        let mut revwalk = repo.revwalk()?;

        revwalk.push(head_oid)?;

        if let Some(have) = have {
            match Oid::from_str(have) {
                Ok(have_oid) if repo.find_commit(have_oid).is_ok() => {
                    tracing::trace!(tenant_id = %tenant_id, have = %have, "hiding replica head from pack walk");

                    revwalk.hide(have_oid)?;
                }
                _ => {
                    tracing::debug!(
                        tenant_id = %tenant_id,
                        have = %have,
                        "replica reported an unknown commit, sending a full pack"
                    );
                }
            }
        }

        let mut packbuilder = repo.packbuilder()?;

        packbuilder.insert_walk(&mut revwalk)?;

        let object_count = packbuilder.object_count();

        // `foreach` streams the pack out chunk by chunk as it is written,
        // rather than materialising the whole thing in memory the way
        // `write_buf` would. A full clone of a large tenant is exactly the
        // case where that difference matters.
        packbuilder.foreach(|chunk| on_chunk(chunk))?;

        tracing::debug!(
            tenant_id = %tenant_id,
            head = %head_sha,
            objects = object_count,
            "replication pack built"
        );

        Ok(object_count)
    }

    /// Imports `pack_path` into the repository at `repo_path` and moves HEAD
    /// to `new_head`, initialising the repository first when it does not
    /// exist yet.
    ///
    /// The order of operations is the feature's whole crash-safety story:
    /// objects are written and indexed first, and only once they are all
    /// present does the ref move. An interrupted apply therefore leaves the
    /// repository at its previous commit, never at a torn state — so a
    /// replica needs no persisted sync cursor at all. Its own on-disk refs
    /// *are* the cursor, which cannot lie the way a checkpoint file can.
    /// Objects from a half-finished apply are unreachable garbage that the
    /// replica's own maintenance pass reclaims.
    ///
    /// A fresh repository is initialised **without** the `"chore: initialize"`
    /// root commit that [`GitUtils::open_or_init_repo`] creates: that commit
    /// is generated locally and would give the replica a different root — and
    /// therefore a permanently divergent history — from its master. A replica
    /// only ever holds commits it was handed.
    ///
    /// A fresh repository is imported through [`GitStaging::create`], so a
    /// reader finds either no tenant or one whose HEAD already points at the
    /// imported commit — never a directory being initialised, nor a
    /// repository whose HEAD stays unborn for as long as the pack takes to
    /// import. A directory that exists without being a repository is adopted
    /// in place, as it always was.
    ///
    /// The working tree is **not** touched here: the caller mirrors it with
    /// [`GitReplication::mirror_working_tree`] once it has recorded the new
    /// head. A checkout is a walk of the whole tenant, and every read already
    /// answers from the moved ref, so running it first would leave the
    /// node's repository listing — and every replica chained to it — behind
    /// its own reads for the length of that walk.
    pub fn apply_pack(
        repo_path: &Path,
        pack_path: &Path,
        new_head: &str,
    ) -> Result<PackApply, AppError> {
        if repo_path.join(".git").exists() {
            let repo = Repository::open(repo_path)?;

            return Self::import_pack(&repo, pack_path, new_head);
        }

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

        if repo_path.exists() {
            let repo = Repository::init(repo_path)?;

            return Self::import_pack(&repo, pack_path, new_head);
        }

        GitStaging::create(repo_path, |staging| {
            let repo = Repository::init(staging)?;

            Self::import_pack(&repo, pack_path, new_head)
        })
    }

    /// The body of [`GitReplication::apply_pack`]: objects first, ref last.
    fn import_pack(
        repo: &Repository,
        pack_path: &Path,
        new_head: &str,
    ) -> Result<PackApply, AppError> {
        let new_oid = Oid::from_str(new_head).map_err(|_err| AppError::CommitNotFound {
            sha: new_head.to_string(),
        })?;

        // Stream the pack straight from disk into the object database. The
        // download landed in a temporary file precisely so this step never
        // has to hold the whole transfer in memory.
        {
            let odb = repo.odb()?;
            let mut packwriter = odb.packwriter()?;
            let mut pack_file = std::fs::File::open(pack_path)?;

            std::io::copy(&mut pack_file, &mut packwriter)?;

            packwriter.commit()?;
        }

        // Finding the announced commit proves the pack was complete: libgit2
        // would have rejected a truncated or corrupt pack above, but a pack
        // that simply did not contain what the master promised would not be
        // caught until a read failed much later.
        repo.find_commit(new_oid)
            .map_err(|_err| AppError::CommitNotFound {
                sha: new_head.to_string(),
            })?;

        let local_head = repo.head().ok().and_then(|head| head.target());

        if let Some(local_oid) = local_head {
            if local_oid == new_oid {
                return Ok(PackApply::UpToDate);
            }

            if !repo.graph_descendant_of(new_oid, local_oid)? {
                // Not a fast-forward. Which kind decides what the operator
                // is told, so both directions are checked; the objects just
                // imported are left in place either way (they are
                // unreachable garbage that maintenance reclaims), and the ref
                // is never moved.
                let ahead = repo.graph_descendant_of(local_oid, new_oid)?;

                return Ok(if ahead {
                    PackApply::Ahead {
                        local: local_oid.to_string(),
                        remote: new_head.to_string(),
                    }
                } else {
                    PackApply::Diverged {
                        local: local_oid.to_string(),
                        remote: new_head.to_string(),
                    }
                });
            }
        }

        let head_reference = Self::head_reference_name(repo)?;

        repo.reference(
            &head_reference,
            new_oid,
            true,
            &format!("replication: fast-forward to {}", new_head),
        )?;

        Ok(PackApply::FastForwarded {
            from: local_head.map(|oid| oid.to_string()),
            to: new_head.to_string(),
        })
    }

    /// Checks a replicated repository's working tree out to HEAD.
    ///
    /// A replica needs only the object store to answer reads — HEAD's tree is
    /// authoritative everywhere in this codebase — but a master keeps its
    /// working tree mirrored so that a human can `ls` a tenant and see its
    /// files, and a replica that did not would be the odd one out: the same
    /// content, present on one node and invisible on the other, with `git
    /// status` reporting every file as deleted.
    ///
    /// It is a full checkout rather than a diff of the two commits, which
    /// would be the cheaper mirror (the write path mirrors file by file for
    /// exactly that reason). A checkout *converges*: whatever the working
    /// tree held before — nothing at all, because this node predates this
    /// behaviour, or a half-written state left by a killed process — one pass
    /// makes it HEAD, where a delta would faithfully apply one commit's worth
    /// of changes on top of a tree that was never correct. Its cost is a
    /// `stat` walk of the tenant per landed pack, paid on a node that just
    /// wrote a packfile, and nothing is written when nothing differs.
    ///
    /// Untracked files are removed, because a replica's working tree is
    /// wholly server-owned: anything there that HEAD does not name is a file
    /// the upstream deleted, and leaving it would make the directory listing
    /// a human reads disagree with every API response.
    ///
    /// Failure is logged and swallowed. The working tree is a courtesy on
    /// every node, so a checkout that cannot run (a permission problem, a
    /// file held open) must not turn a correctly applied pack into a sync
    /// failure that is retried forever.
    ///
    /// Returns how many files the checkout actually wrote or removed, which
    /// is `0` for a working tree that already matched HEAD. That number is
    /// what lets the startup heal pass report whether it repaired anything
    /// rather than only that it ran.
    pub fn mirror_working_tree(repo_path: &Path) -> usize {
        let Ok(repo) = Repository::open(repo_path) else {
            return 0;
        };

        Self::mirror_repository(repo_path, &repo)
    }

    /// The body of [`GitReplication::mirror_working_tree`], for callers that
    /// already hold the repository open.
    fn mirror_repository(repo_path: &Path, repo: &Repository) -> usize {
        // Nothing to mirror before the first pack lands a ref.
        if repo.head().ok().and_then(|head| head.target()).is_none() {
            return 0;
        }

        if let Err(err) = GitLocks::cleanup_stale_index_lock(repo_path) {
            tracing::warn!(
                path = %repo_path.display(),
                err = %err,
                "cannot clear stale index lock before mirroring the working tree"
            );
        }

        // The index is the stat cache the checkout diffs the working tree
        // against, and on a node that accepts writes it drifts from HEAD by
        // design: commits are built with `TreeUpdateBuilder` and never touch
        // it (only maintenance refreshes it). Left stale, every file committed
        // since the last maintenance pass looks modified and is rewritten —
        // byte-identically — on every pass, which would both cost real I/O and
        // make this report healing work it did not do. Refreshing it first
        // makes the pass what it claims to be: HEAD, compared against disk.
        if let Err(err) = Self::refresh_index(repo) {
            tracing::warn!(
                path = %repo_path.display(),
                err = %err,
                "cannot refresh the index before mirroring the working tree"
            );
        }

        // Counted through the notification callback rather than by diffing
        // first: libgit2 announces each path immediately before touching it,
        // so the count is exactly what changed on disk and costs no second
        // pass. A `Cell` because the callback is `FnMut` and borrowed for the
        // duration of the checkout.
        let touched = std::cell::Cell::new(0_usize);

        let mut checkout = CheckoutBuilder::new();

        // `force` writes over whatever is on disk, and `remove_untracked`
        // takes away what HEAD no longer names — together they are what make
        // the pass converge from any prior state. The index is updated as
        // well (libgit2's default), which is what keeps `git status` clean
        // between maintenance passes.
        checkout
            .force()
            .remove_untracked(true)
            .notify_on(git2::CheckoutNotificationType::UPDATED)
            .notify(|_kind, _path, _baseline, _target, _workdir| {
                touched.set(touched.get() + 1);

                true
            });

        if let Err(err) = repo.checkout_head(Some(&mut checkout)) {
            tracing::warn!(
                path = %repo_path.display(),
                err = %err,
                "cannot mirror the working tree onto HEAD"
            );
        }

        touched.get()
    }

    /// Resets the on-disk index to HEAD, the same refresh maintenance does.
    fn refresh_index(repo: &Repository) -> Result<(), AppError> {
        let head_tree = repo.head()?.peel_to_commit()?.tree()?;
        let mut index = repo.index()?;

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

        Ok(())
    }

    /// Relates `remote_sha` to this repository's HEAD using local objects
    /// only. See [`HeadRelation`] for why this runs *before* a pack is asked
    /// for. A repository that does not exist or has no HEAD yet answers
    /// `Unknown`: it needs whatever the upstream has.
    pub fn relation_to(repo_path: &Path, remote_sha: &str) -> HeadRelation {
        let Ok(repo) = Repository::open(repo_path) else {
            return HeadRelation::Unknown;
        };

        let Some(local_oid) = repo.head().ok().and_then(|head| head.target()) else {
            return HeadRelation::Unknown;
        };

        let Ok(remote_oid) = Oid::from_str(remote_sha) else {
            return HeadRelation::Unknown;
        };

        if repo.find_commit(remote_oid).is_err() {
            return HeadRelation::Unknown;
        }

        if remote_oid == local_oid {
            return HeadRelation::Same;
        }

        match repo.graph_descendant_of(local_oid, remote_oid) {
            Ok(true) => HeadRelation::Ahead {
                local: local_oid.to_string(),
            },
            Ok(false) => HeadRelation::Diverged {
                local: local_oid.to_string(),
            },
            Err(_) => HeadRelation::Unknown,
        }
    }

    /// The branch reference HEAD points at.
    ///
    /// Read from the local repository rather than taken from the master,
    /// because the branch name is not part of this API's surface: every read
    /// path resolves content through `repo.head()`, so a replica whose
    /// libgit2 defaulted to `main` while its master defaulted to `master`
    /// still serves byte-identical results.
    fn head_reference_name(repo: &Repository) -> Result<String, AppError> {
        let head = repo.find_reference("HEAD")?;

        Ok(head
            .symbolic_target()?
            .unwrap_or("refs/heads/master")
            .to_string())
    }
}