phora 0.1.2

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

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use gix::object::tree::EntryKind;
use thiserror::Error;

use crate::config::{Refspec, TemplateOptIn};
use crate::kernel::{Commit, Digest, KernelError, OfferSelection, SourceName, safe_component};
use crate::store::ManifestFile;

/// Errors owned by the source context (`SourceBackend` and its adapters).
#[derive(Debug, Error)]
pub enum SourceError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    #[error("source error: {0}")]
    Source(String),

    #[error("{path} is absent at {commit} in {source_name}")]
    FileAbsent {
        source_name: String,
        commit: String,
        path: PathBuf,
    },

    #[error("root path not found in tree: {root}")]
    RootNotFound { root: std::path::PathBuf },

    #[error("mapped key not found in source tree: {key}")]
    MappedKeyNotFound { key: PathBuf },

    #[error("mapped key does not resolve to a regular file: {key}")]
    MappedKeyNotALeaf { key: PathBuf },

    #[error("symlink not allowed: {path} (set allow_symlinks=true to permit)")]
    SymlinkNotAllowed { path: std::path::PathBuf },

    #[error("template render failed for {path}: {message}")]
    Render { path: PathBuf, message: String },

    #[error("deployed-name collision in artifact: {name} (from {first} and {second})")]
    DeployedNameCollision {
        name: String,
        first: PathBuf,
        second: PathBuf,
    },

    #[error("source error: {0}")]
    Kernel(#[from] KernelError),
}

type Result<T> = std::result::Result<T, SourceError>;

/// Re-exported beside the backends it composes; defined in `backend` to keep routing separate.
pub use crate::backend::RouterBackend;

/// gix clones origin as refs/remotes/origin/*; a mirror must update refs/heads/* and
/// refs/tags/* directly so tags (and tag-only-reachable commits) resolve after one fetch.
const MIRROR_REFSPECS: &[&str] = &["+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"];

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
    Https,
    Ssh,
}

#[derive(Debug, Clone)]
pub struct ExportPolicy {
    pub allow_symlinks: bool,
    pub preserve_executable: bool,
    pub vcs_opt_in: bool,
}

impl Default for ExportPolicy {
    fn default() -> Self {
        Self {
            allow_symlinks: false,
            preserve_executable: true,
            vcs_opt_in: false,
        }
    }
}

#[derive(Debug)]
pub struct ExportResult {
    pub files: Vec<ManifestFile>,
    pub digest: String,
    /// Digest of the full effective vars map; `Some` iff at least one template rendered.
    pub vars_digest: Option<String>,
}

/// A direct child of a tree, for the shallow ls-style listing of `phora trust --show <dir>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeEntry {
    pub name: String,
    pub is_dir: bool,
}

/// One leaf to export: a source-relative path looked up in the root tree, staged at
/// the staging-relative `dest` (the deployed name, hashed and recorded verbatim).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExportLeaf {
    pub source: PathBuf,
    pub dest: PathBuf,
}

/// Borrowed parameters of [`SourceBackend::export_artifact`].
pub struct ExportRequest<'a> {
    pub source: &'a SourceName,
    pub url: &'a str,
    pub commit: &'a str,
    pub root: Option<&'a Path>,
    pub policy: &'a ExportPolicy,
    pub staging_dir: &'a Path,
    pub commit_time: u64,
    pub template_opt_in: &'a TemplateOptIn,
    pub vars: &'a BTreeMap<String, String>,
    /// The explicit leaf plan: each source path is looked up in the root tree and
    /// staged at its `dest`.
    pub leaves: &'a [ExportLeaf],
}

/// `source` is the human name (diagnostics); `url` identifies the bare mirror,
/// keyed by normalized-URL hash.
pub trait SourceBackend {
    fn fetch(&self, source: &SourceName, url: &str) -> Result<()>;

    /// Whether a valid local mirror for `url` exists, letting a locked source skip
    /// the fetch. A missing or corrupt mirror returns `false` so the caller still
    /// fetches on a lock hit after the mirror cache was cleared. The default assumes
    /// no mirror; only mirror-backed backends override it.
    fn mirror_ready(&self, _url: &str) -> bool {
        false
    }

    /// Reads `path` from the already-fetched mirror at `commit`, offline. Mirror
    /// reads are git-only; the default errs unsupported and only `GitBackend` overrides it.
    ///
    /// # Errors
    /// - the mirror was never fetched, `commit` is unknown, or `path` is absent at `commit`.
    fn read_file_at(
        &self,
        _source: &SourceName,
        _url: &str,
        _commit: &str,
        _path: &Path,
    ) -> Result<Vec<u8>> {
        Err(SourceError::Source(
            "read_file_at is unsupported on this backend: mirror reads are git-only".to_owned(),
        ))
    }

    /// Every blob path in the subtree at `root`, forward-slashed, sorted, and
    /// root-relative, with no selection applied; the default errs unsupported and
    /// only `GitBackend` overrides it.
    ///
    /// # Errors
    /// - the mirror was never fetched, `commit` is unknown, or `root` is absent at `commit`.
    fn list_source_leaves(
        &self,
        _source: &SourceName,
        _url: &str,
        _commit: &str,
        _root: Option<&Path>,
    ) -> Result<Vec<String>> {
        Err(SourceError::Source(
            "list_source_leaves is unsupported on this backend: mirror reads are git-only"
                .to_owned(),
        ))
    }

    /// The direct children of the subtree at `path` (empty path means the repo root),
    /// shallow and sorted by leaf name; the default errs unsupported and only
    /// `GitBackend` overrides it.
    ///
    /// # Errors
    /// - the mirror was never fetched, `commit` is unknown, or `path` is absent at `commit`.
    fn list_tree_at(
        &self,
        _source: &SourceName,
        _url: &str,
        _commit: &str,
        _path: &Path,
    ) -> Result<Vec<TreeEntry>> {
        Err(SourceError::Source(
            "list_tree_at is unsupported on this backend: mirror reads are git-only".to_owned(),
        ))
    }

    fn resolve(&self, source: &SourceName, url: &str, refspec: &Refspec) -> Result<String>;

    fn commit_time(&self, source: &SourceName, url: &str, commit: &str) -> Result<u64>;

    /// # Errors
    /// - [`SourceError::Render`]: a templated file is invalid or fails to render.
    /// - [`SourceError::DeployedNameCollision`]: two source paths map to the same deployed name.
    /// - [`SourceError::MappedKeyNotFound`]: a leaf's source path resolves to nothing in the tree.
    /// - [`SourceError::MappedKeyNotALeaf`]: a leaf's source path resolves to a non-regular-file.
    fn export_artifact(&self, req: &ExportRequest<'_>) -> Result<ExportResult>;

    /// Blake3 fingerprint of the offer-selected subtree at the resolved commit — the
    /// selected source bytes, not the deploy/artifact set.
    ///
    /// Filters by the offer's gitignore-style include/exclude (`OfferSelection`),
    /// hashing each selected leaf framed by its root-relative path.
    ///
    /// The value written to `LockedSource::digest`; lock reuse is decided by
    /// `lock::source_matches`, not by comparing this digest.
    fn compute_digest(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
        include: &[String],
        exclude: &[String],
    ) -> Result<String>;
}

/// Canonical git URL: equivalent forms collapse to one mirror key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedUrl(String);

impl NormalizedUrl {
    /// Strips a trailing `.git`, rewrites scp-style ssh (`git@host:owner/repo`) to
    /// `host/owner/repo`, drops scheme/userinfo, and lowercases the host.
    #[must_use]
    pub fn parse(url: &str) -> Self {
        let s = url.trim().trim_end_matches('/');
        let s = if let Some(rest) = s.strip_prefix("git@") {
            rest.replacen(':', "/", 1)
        } else {
            let no_scheme = s.split_once("://").map_or(s, |(_, rest)| rest);
            match no_scheme.split_once('@') {
                Some((_, host_and_path)) => host_and_path.to_string(),
                None => no_scheme.to_string(),
            }
        };
        let s = s.strip_suffix(".git").unwrap_or(&s);
        let normalized = match s.split_once('/') {
            Some((host, path)) => format!("{}/{path}", host.to_lowercase()),
            None => s.to_lowercase(),
        };
        Self(normalized)
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Mirror directory key: BLAKE3 of a [`NormalizedUrl`], first 16 hex chars.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MirrorKey(String);

impl MirrorKey {
    #[must_use]
    pub fn from_url(url: &NormalizedUrl) -> Self {
        let hash = blake3::hash(url.as_str().as_bytes());
        Self(hash.to_hex()[..16].to_string())
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// `<MirrorKey>.git` under `git_dir`; the single source of mirror-directory layout.
pub(crate) fn mirror_path(git_dir: &Path, url: &str) -> PathBuf {
    let key = MirrorKey::from_url(&NormalizedUrl::parse(url));
    git_dir.join(format!("{}.git", key.as_str()))
}

pub(crate) fn mirror_lock_path(git_dir: &Path, url: &str) -> PathBuf {
    let mut s = mirror_path(git_dir, url).into_os_string();
    s.push(".lock");
    PathBuf::from(s)
}

pub(crate) fn lock_mirror(git_dir: &Path, source: &SourceName, url: &str) -> Result<std::fs::File> {
    std::fs::create_dir_all(git_dir)
        .map_err(|e| SourceError::Source(format!("create git dir for lock {source}: {e}")))?;
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(mirror_lock_path(git_dir, url))
        .map_err(|e| SourceError::Source(format!("open mirror lock {source}: {e}")))?;
    lock.lock()
        .map_err(|e| SourceError::Source(format!("lock mirror {source}: {e}")))?;
    Ok(lock)
}

/// Idle window above any real clone; a staging dir older than this lost its
/// owning process before `Drop` could clean it up.
const STAGING_ORPHAN_GRACE: std::time::Duration = std::time::Duration::from_hours(1);

/// Removes staging dirs abandoned by a killed clone of `url`'s mirror.
///
/// Caller must hold the per-mirror lock: it excludes a concurrent full fetch of
/// this key, and [`STAGING_ORPHAN_GRACE`] excludes the lock-free shallow clone.
/// Errors are ignored; a sweep must never fail the fetch it precedes.
fn sweep_orphan_staging(git_dir: &Path, url: &str) {
    let key = MirrorKey::from_url(&NormalizedUrl::parse(url));
    let prefix = format!(".{}.staging-", key.as_str());
    let Ok(entries) = std::fs::read_dir(git_dir) else {
        return;
    };
    for entry in entries.flatten() {
        let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
            continue;
        };
        if !name.starts_with(&prefix) || staging_is_recent(&entry.path()) {
            continue;
        }
        let _ = std::fs::remove_dir_all(entry.path());
    }
}

/// A clone writes its pack into `objects/pack/` subdirs, so the staging root's own
/// mtime freezes early; liveness must consider the newest mtime in the whole tree.
fn staging_is_recent(path: &Path) -> bool {
    let mut saw_mtime = false;
    for entry in walkdir::WalkDir::new(path) {
        let Ok(entry) = entry else { return true };
        let Ok(meta) = entry.metadata() else {
            return true;
        };
        let Ok(modified) = meta.modified() else {
            return true;
        };
        saw_mtime = true;
        if modified
            .elapsed()
            .map_or(true, |age| age < STAGING_ORPHAN_GRACE)
        {
            return true;
        }
    }
    !saw_mtime
}

/// Opens the canonical mirror, distinguishing "re-clone" from "leave untouched".
///
/// `Ok(None)` means absent or genuinely not a repository — safe to re-clone. Any
/// other open failure (I/O, permissions, unreadable config) may be transient, so it
/// propagates rather than destroying a possibly-healthy cache.
fn open_mirror(source: &SourceName, mirror: &Path) -> Result<Option<gix::Repository>> {
    if !mirror.exists() {
        return Ok(None);
    }
    match gix::open(mirror) {
        Ok(repo) => Ok(Some(repo)),
        Err(gix::open::Error::NotARepository { .. }) => Ok(None),
        Err(e) => Err(SourceError::Source(format!("open mirror {source}: {e}"))),
    }
}

fn fetch_into_mirror(source: &SourceName, repo: &gix::Repository) -> Result<()> {
    let mut remote = repo
        .find_remote("origin")
        .map_err(|e| SourceError::Source(format!("find origin in {source}: {e}")))?;
    remote
        .replace_refspecs(
            MIRROR_REFSPECS.iter().copied(),
            gix::remote::Direction::Fetch,
        )
        .map_err(|e| SourceError::Source(format!("set mirror refspec in {source}: {e}")))?;
    remote
        .connect(gix::remote::Direction::Fetch)
        .map_err(|e| SourceError::Source(format!("connect origin in {source}: {e}")))?
        .prepare_fetch(
            gix::progress::Discard,
            gix::remote::ref_map::Options::default(),
        )
        .map_err(|e| SourceError::Source(format!("prepare fetch in {source}: {e}")))?
        .receive(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)
        .map_err(|e| SourceError::Source(format!("receive pack in {source}: {e}")))?;
    Ok(())
}

/// Clones a fresh mirror into staging, then replaces `mirror`. The canonical mirror
/// is removed only after the clone succeeds, so a failed clone (unreachable remote)
/// leaves an existing mirror intact rather than trading it for nothing.
fn reclone_mirror(git_dir: &Path, source: &SourceName, url: &str, mirror: &Path) -> Result<()> {
    let staging = MirrorStaging::create(git_dir, url);
    gix::prepare_clone_bare(url, &staging.path)
        .map_err(|e| SourceError::Source(format!("prepare clone {source}: {e}")))?
        .configure_remote(|mut remote| {
            remote.replace_refspecs(
                MIRROR_REFSPECS.iter().copied(),
                gix::remote::Direction::Fetch,
            )?;
            Ok(remote)
        })
        .fetch_only(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)
        .map_err(|e| SourceError::Source(format!("clone bare {source}: {e}")))?;
    if mirror.exists() {
        std::fs::remove_dir_all(mirror)
            .map_err(|e| SourceError::Source(format!("remove corrupt mirror {source}: {e}")))?;
    }
    staging.commit_to(mirror, source.as_str())
}

/// A scratch mirror renamed into the canonical path on success, removed on drop otherwise.
struct MirrorStaging {
    path: PathBuf,
    armed: bool,
}

impl MirrorStaging {
    fn create(git_dir: &Path, url: &str) -> Self {
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let nonce = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let key = MirrorKey::from_url(&NormalizedUrl::parse(url));
        let name = format!(".{}.staging-{}-{nonce}", key.as_str(), std::process::id());
        Self {
            path: git_dir.join(name),
            armed: true,
        }
    }

    fn commit_to(mut self, mirror: &Path, label: &str) -> Result<()> {
        std::fs::rename(&self.path, mirror)
            .map_err(|e| SourceError::Source(format!("publish mirror {label}: {e}")))?;
        self.armed = false;
        Ok(())
    }
}

impl Drop for MirrorStaging {
    fn drop(&mut self) {
        if self.armed {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }
}

pub struct GitBackend {
    git_dir: PathBuf,
}

impl GitBackend {
    #[must_use]
    pub fn new(git_dir: PathBuf) -> Self {
        Self { git_dir }
    }

    fn mirror_path(&self, url: &str) -> PathBuf {
        mirror_path(&self.git_dir, url)
    }

    /// Reads a remote's root `phora.toml` at `refspec`, reusing an existing mirror
    /// when present and otherwise fetching one. Offline if the mirror is cached.
    ///
    /// # Errors
    /// - the remote cannot be fetched, the ref cannot be resolved, or no `phora.toml` exists.
    pub fn fetch_root_manifest(
        &self,
        source: &SourceName,
        url: &str,
        refspec: &Refspec,
    ) -> Result<Vec<u8>> {
        if self.mirror_path(url).exists() {
            let commit = self.resolve(source, url, refspec)?;
            return self.read_file_at(source, url, &commit, Path::new("phora.toml"));
        }
        self.shallow_read_root_manifest(source, url, refspec)
    }

    /// Every path whose blob differs between `from_commit` and `to_commit` (added, removed, or
    /// modified), read from `url`'s mirror. Backs the `phora trust` inspect-before-trust diff: both
    /// commits must already be in the mirror (a full `phora sync` clone holds them).
    ///
    /// # Errors
    /// - the mirror is missing, either commit cannot be resolved, or a tree cannot be walked.
    pub fn file_diff_between(
        &self,
        source: &SourceName,
        url: &str,
        from_commit: &str,
        to_commit: &str,
    ) -> Result<Vec<String>> {
        let mirror = self.mirror_path(url);
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))?;
        let from = tree_blobs(&repo, source, from_commit)?;
        let to = tree_blobs(&repo, source, to_commit)?;
        let mut changed: BTreeSet<String> = BTreeSet::new();
        for (path, id) in &to {
            if from.get(path) != Some(id) {
                changed.insert(path.clone());
            }
        }
        for path in from.keys() {
            if !to.contains_key(path) {
                changed.insert(path.clone());
            }
        }
        Ok(changed.into_iter().collect())
    }

    /// Reads a remote's root `phora.toml` via a `--depth=1` shallow clone into an
    /// ephemeral staging dir, leaving the persistent mirror cache untouched.
    ///
    /// # Errors
    /// - the shallow clone fails, the ref cannot be resolved, or no `phora.toml` exists.
    fn shallow_read_root_manifest(
        &self,
        source: &SourceName,
        url: &str,
        refspec: &Refspec,
    ) -> Result<Vec<u8>> {
        let depth = std::num::NonZeroU32::new(1).expect("1 is non-zero");
        std::fs::create_dir_all(&self.git_dir)
            .map_err(|e| SourceError::Source(format!("source {source}: create git dir: {e}")))?;
        let staging = MirrorStaging::create(&self.git_dir, url);

        let mut prepare = gix::prepare_clone_bare(url, &staging.path)
            .map_err(|e| SourceError::Source(format!("prepare shallow clone {source}: {e}")))?
            .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote(depth));
        if let Some(refname) = shallow_ref_name(refspec) {
            prepare = prepare.with_ref_name(Some(refname.as_str())).map_err(|e| {
                SourceError::Source(format!("shallow ref {refname} for {source}: {e}"))
            })?;
        }
        let (repo, _) = prepare
            .fetch_only(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)
            .map_err(|e| SourceError::Source(format!("shallow clone {source}: {e}")))?;

        let commit = resolve_in(&repo, source, refspec)?;
        read_blob_at(&repo, source, &commit, Path::new("phora.toml"))
    }
}

fn shallow_ref_name(refspec: &Refspec) -> Option<String> {
    match refspec {
        Refspec::Branch(name) => Some(format!("refs/heads/{name}")),
        Refspec::Tag(name) => Some(format!("refs/tags/{name}")),
        Refspec::Rev(_) | Refspec::Default | Refspec::None => None,
    }
}

fn resolve_in(repo: &gix::Repository, source: &SourceName, refspec: &Refspec) -> Result<String> {
    let commit = match refspec {
        Refspec::Branch(name) => repo
            .find_reference(&format!("refs/heads/{name}"))
            .map_err(|e| SourceError::Source(format!("branch {name} in {source}: {e}")))?
            .peel_to_commit()
            .map_err(|e| SourceError::Source(format!("peel branch {name} in {source}: {e}")))?,
        Refspec::Tag(name) => repo
            .find_reference(&format!("refs/tags/{name}"))
            .map_err(|e| SourceError::Source(format!("tag {name} in {source}: {e}")))?
            .peel_to_commit()
            .map_err(|e| SourceError::Source(format!("peel tag {name} in {source}: {e}")))?,
        Refspec::Rev(rev) => {
            let commit: Commit = rev
                .parse()
                .map_err(|e| SourceError::Source(format!("parse rev {rev} in {source}: {e}")))?;
            let oid = gix::ObjectId::from_hex(commit.as_str().as_bytes())
                .map_err(|e| SourceError::Source(format!("parse rev {rev} in {source}: {e}")))?;
            repo.find_commit(oid)
                .map_err(|e| SourceError::Source(format!("rev {rev} in {source}: {e}")))?
        }
        Refspec::Default => repo
            .head_commit()
            .map_err(|e| SourceError::Source(format!("default branch (HEAD) in {source}: {e}")))?,
        Refspec::None => {
            return Err(SourceError::Source(format!(
                "source {source}: git backend cannot resolve a url source's empty refspec"
            )));
        }
    };
    Ok(commit.id().to_hex().to_string())
}

fn tree_blobs(
    repo: &gix::Repository,
    source: &SourceName,
    commit: &str,
) -> Result<BTreeMap<String, gix::ObjectId>> {
    let oid = gix::ObjectId::from_hex(commit.as_bytes())
        .map_err(|e| SourceError::Source(format!("parse commit {commit} in {source}: {e}")))?;
    let tree = repo
        .find_commit(oid)
        .map_err(|e| SourceError::Source(format!("commit {commit} in {source}: {e}")))?
        .tree()
        .map_err(|e| SourceError::Source(format!("tree of {commit} in {source}: {e}")))?;
    let mut blobs = BTreeMap::new();
    let mut recorder = gix::traverse::tree::Recorder::default();
    tree.traverse()
        .breadthfirst(&mut recorder)
        .map_err(|e| SourceError::Source(format!("walk tree of {commit} in {source}: {e}")))?;
    for entry in recorder.records {
        if entry.mode.is_blob() {
            blobs.insert(entry.filepath.to_string(), entry.oid);
        }
    }
    Ok(blobs)
}

fn read_blob_at(
    repo: &gix::Repository,
    source: &SourceName,
    commit: &str,
    path: &Path,
) -> Result<Vec<u8>> {
    let oid = gix::ObjectId::from_hex(commit.as_bytes())
        .map_err(|e| SourceError::Source(format!("parse commit {commit} in {source}: {e}")))?;
    let tree = repo
        .find_commit(oid)
        .map_err(|e| SourceError::Source(format!("commit {commit} in {source}: {e}")))?
        .tree()
        .map_err(|e| SourceError::Source(format!("tree of {commit} in {source}: {e}")))?;
    let display = path.display();
    let entry = tree
        .lookup_entry_by_path(path)
        .map_err(|e| SourceError::Source(format!("read {display} at {commit}: {e}")))?
        .ok_or_else(|| SourceError::FileAbsent {
            source_name: source.to_string(),
            commit: commit.to_owned(),
            path: path.to_owned(),
        })?;
    if !entry.mode().is_blob() {
        return Err(SourceError::Source(format!(
            "{display} at {commit} in {source} is not a regular file"
        )));
    }
    let object = entry
        .object()
        .map_err(|e| SourceError::Source(format!("read {display} at {commit}: {e}")))?;
    Ok(object.data.clone())
}

impl SourceBackend for GitBackend {
    fn read_file_at(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        path: &Path,
    ) -> Result<Vec<u8>> {
        let mirror = self.mirror_path(url);
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))?;
        read_blob_at(&repo, source, commit, path)
    }

    fn list_source_leaves(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
    ) -> Result<Vec<String>> {
        let repo = self.open_mirror(source.as_str(), url)?;
        let subtree = Self::subtree_at_root(&repo, source.as_str(), commit, root)?;
        let mut recorder = gix::traverse::tree::Recorder::default();
        subtree
            .traverse()
            .breadthfirst(&mut recorder)
            .map_err(|e| SourceError::Source(format!("walk subtree in {source}: {e}")))?;
        let mut leaves: Vec<String> = recorder
            .records
            .into_iter()
            .filter(|entry| entry.mode.is_blob())
            .map(|entry| entry.filepath.to_string())
            .collect();
        leaves.sort_unstable();
        Ok(leaves)
    }

    fn list_tree_at(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        path: &Path,
    ) -> Result<Vec<TreeEntry>> {
        let repo = self.open_mirror(source.as_str(), url)?;
        let root = if path.as_os_str().is_empty() {
            None
        } else {
            Some(path)
        };
        let subtree = Self::subtree_at_root(&repo, source.as_str(), commit, root)?;
        let mut entries = Vec::new();
        for entry in subtree.iter() {
            let entry = entry
                .map_err(|e| SourceError::Source(format!("read tree entry in {source}: {e}")))?;
            entries.push(TreeEntry {
                name: entry.filename().to_string(),
                is_dir: entry.mode().is_tree(),
            });
        }
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(entries)
    }

    fn fetch(&self, source: &SourceName, url: &str) -> Result<()> {
        let _lock = lock_mirror(&self.git_dir, source, url)?;
        sweep_orphan_staging(&self.git_dir, url);
        let mirror = self.mirror_path(url);

        if let Some(repo) = open_mirror(source, &mirror)?
            && fetch_into_mirror(source, &repo).is_ok()
        {
            return Ok(());
        }
        reclone_mirror(&self.git_dir, source, url, &mirror)
    }

    fn mirror_ready(&self, url: &str) -> bool {
        gix::open(self.mirror_path(url)).is_ok()
    }

    fn resolve(&self, source: &SourceName, url: &str, refspec: &Refspec) -> Result<String> {
        let mirror = self.mirror_path(url);
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))?;
        resolve_in(&repo, source, refspec)
    }

    fn commit_time(&self, source: &SourceName, url: &str, commit: &str) -> Result<u64> {
        let mirror = self.mirror_path(url);
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))?;
        let oid = gix::ObjectId::from_hex(commit.as_bytes())
            .map_err(|e| SourceError::Source(format!("parse commit {commit} in {source}: {e}")))?;
        let commit_obj = repo
            .find_commit(oid)
            .map_err(|e| SourceError::Source(format!("commit {commit} in {source}: {e}")))?;
        let seconds = commit_obj
            .author()
            .map_err(|e| SourceError::Source(format!("author of {commit} in {source}: {e}")))?
            .time()
            .map_err(|e| SourceError::Source(format!("author time of {commit} in {source}: {e}")))?
            .seconds;
        u64::try_from(seconds)
            .map_err(|e| SourceError::Source(format!("author time of {commit} in {source}: {e}")))
    }

    fn export_artifact(&self, req: &ExportRequest<'_>) -> Result<ExportResult> {
        let repo = self.open_mirror(req.source.as_str(), req.url)?;
        let root_tree = Self::subtree_at_root(&repo, req.source.as_str(), req.commit, req.root)?;

        std::fs::create_dir_all(req.staging_dir)?;

        let renderer = Renderer::new(req.template_opt_in, req.vars);
        let mut walk = ExportWalk {
            repo: &repo,
            source: req.source.as_str(),
            out_base: req.staging_dir,
            policy: req.policy,
            commit_time: req.commit_time,
            files: Vec::new(),
            hasher: blake3::Hasher::new(),
            renderer: &renderer,
            deployed_names: BTreeMap::new(),
            rendered_any: false,
        };
        walk.run(&root_tree, req.leaves)?;

        let digest = format!("blake3:{}", walk.hasher.finalize().to_hex());
        let vars_digest = walk.rendered_any.then(|| renderer.vars_digest());
        Ok(ExportResult {
            files: walk.files,
            digest,
            vars_digest,
        })
    }

    fn compute_digest(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
        include: &[String],
        exclude: &[String],
    ) -> Result<String> {
        let repo = self.open_mirror(source.as_str(), url)?;
        let subtree = Self::subtree_at_root(&repo, source.as_str(), commit, root)?;

        let mut leaves = Vec::new();
        Self::collect_digest_leaves(&repo, source.as_str(), &subtree, Path::new(""), &mut leaves)?;

        let selection = OfferSelection::compile(include, exclude, None)
            .map_err(|e| SourceError::Source(format!("compile offer for {source}: {e}")))?;
        let candidates: Vec<&str> = leaves.iter().map(|(path, _, _)| path.as_str()).collect();
        let selected: BTreeSet<String> = selection.select(&candidates).into_iter().collect();

        let mut hasher = blake3::Hasher::new();
        for (path, tag, oid) in &leaves {
            if !selected.contains(path) {
                continue;
            }
            let data = Self::find_blob_data(&repo, source.as_str(), *oid)?;
            hash_framed_entry(&mut hasher, path.as_bytes(), tag, &data);
        }
        Ok(format!("blake3:{}", hasher.finalize().to_hex()))
    }
}

impl GitBackend {
    /// Every blob leaf under `tree`, breadth-first into `(forward-slashed root-relative
    /// path, frame tag, oid)`. The tag distinguishes exec/link/file so the digest frames
    /// match the historical tree-walk byte stream.
    fn collect_digest_leaves(
        repo: &gix::Repository,
        source: &str,
        tree: &gix::Tree<'_>,
        rel_path: &Path,
        leaves: &mut Vec<(String, &'static [u8], gix::ObjectId)>,
    ) -> Result<()> {
        for entry in tree.iter() {
            let entry = entry
                .map_err(|e| SourceError::Source(format!("read tree entry in {source}: {e}")))?;
            let component = safe_component(&entry.filename().to_string())?.to_string();
            let entry_rel = rel_path.join(component);

            match entry.kind() {
                EntryKind::Blob | EntryKind::BlobExecutable | EntryKind::Link => {
                    let tag: &[u8] = match entry.kind() {
                        EntryKind::BlobExecutable => b"\x00exec\x00",
                        EntryKind::Link => b"\x00link\x00",
                        _ => b"\x00file\x00",
                    };
                    leaves.push((
                        entry_rel.to_string_lossy().replace('\\', "/"),
                        tag,
                        entry.object_id(),
                    ));
                }
                EntryKind::Tree => {
                    let subtree = repo
                        .find_tree(entry.object_id())
                        .map_err(|e| SourceError::Source(format!("subtree in {source}: {e}")))?;
                    Self::collect_digest_leaves(repo, source, &subtree, &entry_rel, leaves)?;
                }
                EntryKind::Commit => {}
            }
        }
        Ok(())
    }

    fn open_mirror(&self, source: &str, url: &str) -> Result<gix::Repository> {
        let mirror = self.mirror_path(url);
        gix::open(&mirror).map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))
    }

    fn commit_tree<'repo>(
        repo: &'repo gix::Repository,
        source: &str,
        commit: &str,
    ) -> Result<gix::Tree<'repo>> {
        let oid = gix::ObjectId::from_hex(commit.as_bytes())
            .map_err(|e| SourceError::Source(format!("parse commit {commit} in {source}: {e}")))?;
        repo.find_commit(oid)
            .map_err(|e| SourceError::Source(format!("commit {commit} in {source}: {e}")))?
            .tree()
            .map_err(|e| SourceError::Source(format!("tree of {commit} in {source}: {e}")))
    }

    fn subtree_at_root<'repo>(
        repo: &'repo gix::Repository,
        source: &str,
        commit: &str,
        root: Option<&Path>,
    ) -> Result<gix::Tree<'repo>> {
        let tree = Self::commit_tree(repo, source, commit)?;
        match root {
            Some(r) => {
                let entry = tree
                    .lookup_entry_by_path(r)
                    .map_err(|e| {
                        SourceError::Source(format!("lookup root {} in {source}: {e}", r.display()))
                    })?
                    .ok_or_else(|| SourceError::RootNotFound {
                        root: r.to_path_buf(),
                    })?;
                repo.find_tree(entry.object_id()).map_err(|e| {
                    SourceError::Source(format!("root tree {} in {source}: {e}", r.display()))
                })
            }
            None => Ok(tree),
        }
    }

    fn find_blob_data(repo: &gix::Repository, source: &str, oid: gix::ObjectId) -> Result<Vec<u8>> {
        let blob = repo
            .find_blob(oid)
            .map_err(|e| SourceError::Source(format!("blob {oid} in {source}: {e}")))?;
        Ok(blob.data.clone())
    }
}

/// A download scratch file under `git_dir`, removed on drop.
struct TempDownload {
    path: PathBuf,
}

impl TempDownload {
    fn create(git_dir: &Path) -> Self {
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let nonce = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let name = format!(".phora-download-{}-{nonce}.tmp", std::process::id());
        Self {
            path: git_dir.join(name),
        }
    }
}

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

/// Url-source adapter: downloads + extracts + imports a synthetic mirror, then
/// reads it through an inner [`GitBackend`] over the same `git_dir`.
pub struct HttpBackend {
    git_dir: PathBuf,
    git: GitBackend,
    digests: BTreeMap<SourceName, Digest>,
}

impl HttpBackend {
    #[must_use]
    pub fn new(git_dir: PathBuf, digests: BTreeMap<SourceName, Digest>) -> Self {
        let git = GitBackend::new(git_dir.clone());
        Self {
            git_dir,
            git,
            digests,
        }
    }
}

impl SourceBackend for HttpBackend {
    fn fetch(&self, source: &SourceName, url: &str) -> Result<()> {
        std::fs::create_dir_all(&self.git_dir)
            .map_err(|e| SourceError::Source(format!("source {source}: create git dir: {e}")))?;
        let temp = TempDownload::create(&self.git_dir);

        crate::http::download(url, &temp.path)?;

        if let Some(expected) = self.digests.get(source) {
            let bytes = std::fs::read(&temp.path)
                .map_err(|e| SourceError::Source(format!("source {source}: read download: {e}")))?;
            crate::http::verify_digest(&bytes, expected)
                .map_err(|e| SourceError::Source(format!("source {source}: {e}")))?;
        }

        let entries = crate::archive::extract(&temp.path, url)?;
        let _lock = lock_mirror(&self.git_dir, source, url)?;
        import_tree(&self.git_dir, url, &entries)?;
        Ok(())
    }

    fn mirror_ready(&self, url: &str) -> bool {
        self.git.mirror_ready(url)
    }

    /// Resolve ignores the refspec: url sources live at refs/heads/phora.
    fn resolve(&self, source: &SourceName, url: &str, _refspec: &Refspec) -> Result<String> {
        let mirror = mirror_path(&self.git_dir, url);
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {source}: {e}")))?;
        let commit = repo
            .find_reference(IMPORT_REF)
            .map_err(|e| SourceError::Source(format!("{IMPORT_REF} in {source}: {e}")))?
            .peel_to_commit()
            .map_err(|e| SourceError::Source(format!("peel {IMPORT_REF} in {source}: {e}")))?;
        Ok(commit.id().to_hex().to_string())
    }

    fn commit_time(&self, source: &SourceName, url: &str, commit: &str) -> Result<u64> {
        self.git.commit_time(source, url, commit)
    }

    fn list_source_leaves(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
    ) -> Result<Vec<String>> {
        self.git.list_source_leaves(source, url, commit, root)
    }

    fn export_artifact(&self, req: &ExportRequest<'_>) -> Result<ExportResult> {
        self.git.export_artifact(req)
    }

    fn compute_digest(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
        include: &[String],
        exclude: &[String],
    ) -> Result<String> {
        self.git
            .compute_digest(source, url, commit, root, include, exclude)
    }
}

struct Renderer<'a> {
    opt_in: &'a TemplateOptIn,
    env: minijinja::Environment<'static>,
    vars: &'a BTreeMap<String, String>,
}

impl<'a> Renderer<'a> {
    fn new(opt_in: &'a TemplateOptIn, vars: &'a BTreeMap<String, String>) -> Self {
        let mut env = minijinja::Environment::new();
        env.set_undefined_behavior(minijinja::UndefinedBehavior::Strict);
        env.set_keep_trailing_newline(true);
        // Bounds runaway templates from untrusted sources (e.g. unbounded loops).
        env.set_fuel(Some(1_000_000));
        Self { opt_in, env, vars }
    }

    fn rel_key(entry_rel: &Path) -> String {
        entry_rel.to_string_lossy().replace('\\', "/")
    }

    fn render(&self, entry_rel: &Path, source_bytes: &[u8]) -> Result<Rendered> {
        let key = Self::rel_key(entry_rel);
        if !self.opt_in.renders(&key) {
            return Ok(Rendered {
                bytes: source_bytes.to_vec(),
                templated: false,
            });
        }
        let template = std::str::from_utf8(source_bytes).map_err(|e| SourceError::Render {
            path: entry_rel.to_path_buf(),
            message: format!("template is not valid UTF-8: {e}"),
        })?;
        self.env
            .render_str(template, self.vars)
            .map(|bytes| Rendered {
                bytes: bytes.into_bytes(),
                templated: true,
            })
            .map_err(|e| SourceError::Render {
                path: entry_rel.to_path_buf(),
                message: e.to_string(),
            })
    }

    fn vars_digest(&self) -> String {
        vars_digest(self.vars)
    }
}

/// Blake3 digest of the full effective vars map.
///
/// Export and `check_artifact_state` MUST agree byte-for-byte; both route through this.
#[must_use]
pub fn vars_digest(vars: &BTreeMap<String, String>) -> String {
    let mut hasher = blake3::Hasher::new();
    for (key, value) in vars {
        hash_framed_entry(
            &mut hasher,
            key.as_bytes(),
            b"\x00var\x00",
            value.as_bytes(),
        );
    }
    format!("blake3:{}", hasher.finalize().to_hex())
}

struct Rendered {
    bytes: Vec<u8>,
    templated: bool,
}

struct ExportWalk<'a, 'r> {
    repo: &'a gix::Repository,
    source: &'a str,
    out_base: &'a Path,
    policy: &'a ExportPolicy,
    commit_time: u64,
    files: Vec<ManifestFile>,
    hasher: blake3::Hasher,
    renderer: &'a Renderer<'r>,
    deployed_names: BTreeMap<PathBuf, PathBuf>,
    rendered_any: bool,
}

fn dest_has_vcs_component(dest: &Path) -> bool {
    dest.components().any(|c| c.as_os_str() == ".git")
}

impl ExportWalk<'_, '_> {
    /// Stages each leaf of the explicit plan: look up its source path in `root_tree`,
    /// reject a non-blob or a symlink the policy forbids, then stage at the leaf's
    /// dest. Render keys on the source path; the framed digest and manifest path key
    /// on the dest.
    fn run(&mut self, root_tree: &gix::Tree<'_>, leaves: &[ExportLeaf]) -> Result<()> {
        for leaf in leaves {
            if !self.policy.vcs_opt_in && dest_has_vcs_component(&leaf.dest) {
                continue;
            }
            let entry = root_tree
                .lookup_entry_by_path(&leaf.source)
                .map_err(|e| {
                    SourceError::Source(format!(
                        "lookup key {} in {}: {e}",
                        leaf.source.display(),
                        self.source
                    ))
                })?
                .ok_or_else(|| SourceError::MappedKeyNotFound {
                    key: leaf.source.clone(),
                })?;
            let kind = entry.mode().kind();
            if !matches!(
                kind,
                EntryKind::Blob | EntryKind::BlobExecutable | EntryKind::Link
            ) {
                return Err(SourceError::MappedKeyNotALeaf {
                    key: leaf.source.clone(),
                });
            }
            let bytes = GitBackend::find_blob_data(self.repo, self.source, entry.object_id())?;
            match kind {
                EntryKind::Blob => self.stage_leaf(&leaf.dest, &leaf.source, &bytes, false)?,
                EntryKind::BlobExecutable => {
                    self.stage_leaf(&leaf.dest, &leaf.source, &bytes, true)?;
                }
                EntryKind::Link => self.stage_link(&leaf.dest, &bytes)?,
                _ => unreachable!("non-leaf kinds rejected above"),
            }
        }
        Ok(())
    }

    fn register_deployed_name(&mut self, deployed_rel: PathBuf, source_rel: &Path) -> Result<()> {
        let name = deployed_rel.to_string_lossy().into_owned();
        if let Some(prior) = self
            .deployed_names
            .insert(deployed_rel, source_rel.to_path_buf())
        {
            return Err(SourceError::DeployedNameCollision {
                name,
                first: prior,
                second: source_rel.to_path_buf(),
            });
        }
        Ok(())
    }

    fn stage_leaf(
        &mut self,
        deployed_rel: &Path,
        source_rel: &Path,
        source_bytes: &[u8],
        executable: bool,
    ) -> Result<()> {
        self.register_deployed_name(deployed_rel.to_path_buf(), source_rel)?;

        let rendered = self.renderer.render(source_rel, source_bytes)?;
        self.rendered_any |= rendered.templated;
        let data = rendered.bytes;

        let out_path = self.out_base.join(deployed_rel);
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&out_path, &data)?;
        set_deterministic_mtime(&out_path, self.commit_time)?;

        if executable && self.policy.preserve_executable {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mut perms = std::fs::metadata(&out_path)?.permissions();
                perms.set_mode(perms.mode() | 0o111);
                std::fs::set_permissions(&out_path, perms)?;
            }
        }

        let tag: &[u8] = if executable {
            b"\x00exec\x00"
        } else {
            b"\x00file\x00"
        };
        hash_framed_entry(
            &mut self.hasher,
            deployed_rel.to_string_lossy().as_bytes(),
            tag,
            &data,
        );

        self.files.push(ManifestFile {
            path: deployed_rel.to_path_buf(),
            size: data.len() as u64,
            mtime: self.commit_time,
            blake3: blake3::hash(&data).to_hex().to_string(),
        });
        Ok(())
    }

    fn stage_link(&mut self, deployed_rel: &Path, target: &[u8]) -> Result<()> {
        if !self.policy.allow_symlinks {
            return Err(SourceError::SymlinkNotAllowed {
                path: deployed_rel.to_path_buf(),
            });
        }
        self.register_deployed_name(deployed_rel.to_path_buf(), deployed_rel)?;

        let out_path = self.out_base.join(deployed_rel);
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        materialize_symlink(&out_path, target)?;

        hash_framed_entry(
            &mut self.hasher,
            deployed_rel.to_string_lossy().as_bytes(),
            b"\x00link\x00",
            target,
        );
        Ok(())
    }
}

// Fixed identity/time/message: with no parents and git-sorted trees the commit id is a
// function of the imported content only — identical entries yield an identical commit id.
const IMPORT_NAME: &str = "phora";
const IMPORT_EMAIL: &str = "phora@localhost";
const IMPORT_MESSAGE: &str = "phora synthetic import";
// epoch+1, not epoch 0: HFS+/FAT32 clamp a 0 mtime on EXPORTED files, making clean checks
// report Modified; the commit id is pure content, so this never affects determinism.
const IMPORT_TIME_SECONDS: i64 = 1;
const IMPORT_REF: &str = "refs/heads/phora";

fn to_gix_entry_kind(kind: crate::archive::EntryKind) -> EntryKind {
    match kind {
        crate::archive::EntryKind::Blob => EntryKind::Blob,
        crate::archive::EntryKind::BlobExecutable => EntryKind::BlobExecutable,
        crate::archive::EntryKind::Link => EntryKind::Link,
    }
}

/// Writes `entries` as a synthetic commit on `refs/heads/phora` in the bare mirror for
/// `url` (created if absent), returning the commit id as hex. The id is content-addressed:
/// fixed identity/time/message + no parents + git-sorted trees ⇒ identical content, identical id.
pub(crate) fn import_tree(
    git_dir: &Path,
    url: &str,
    entries: &[crate::archive::ExtractedEntry],
) -> Result<String> {
    let mirror = mirror_path(git_dir, url);

    if mirror.exists() {
        let repo = gix::open(&mirror)
            .map_err(|e| SourceError::Source(format!("open mirror {url}: {e}")))?;
        return write_import(&repo, url, entries);
    }

    std::fs::create_dir_all(git_dir)
        .map_err(|e| SourceError::Source(format!("create git dir for {url}: {e}")))?;
    let staging = MirrorStaging::create(git_dir, url);
    let commit = {
        let repo = gix::init_bare(&staging.path)
            .map_err(|e| SourceError::Source(format!("init mirror {url}: {e}")))?;
        write_import(&repo, url, entries)?
    };
    staging.commit_to(&mirror, url)?;
    Ok(commit)
}

fn write_import(
    repo: &gix::Repository,
    url: &str,
    entries: &[crate::archive::ExtractedEntry],
) -> Result<String> {
    let mut root = ImportDir::default();
    for entry in entries {
        let oid = repo
            .write_blob(&entry.data)
            .map_err(|e| SourceError::Source(format!("write blob for {url}: {e}")))?
            .detach();
        root.insert(&entry.path, to_gix_entry_kind(entry.kind), oid)?;
    }

    let root_oid = write_import_tree(repo, &root, url)?;

    let signature = gix::actor::Signature {
        name: IMPORT_NAME.into(),
        email: IMPORT_EMAIL.into(),
        time: gix::date::Time {
            seconds: IMPORT_TIME_SECONDS,
            offset: 0,
        },
    };
    let commit = gix::objs::Commit {
        tree: root_oid,
        parents: std::iter::empty::<gix::ObjectId>().collect(),
        author: signature.clone(),
        committer: signature,
        encoding: None,
        message: IMPORT_MESSAGE.into(),
        extra_headers: vec![],
    };
    let commit_id = repo
        .write_object(&commit)
        .map_err(|e| SourceError::Source(format!("write import commit for {url}: {e}")))?
        .detach();

    // PreviousValue::Any: create the ref if absent, force-update it on re-import.
    repo.reference(
        IMPORT_REF,
        commit_id,
        gix::refs::transaction::PreviousValue::Any,
        IMPORT_MESSAGE,
    )
    .map_err(|e| SourceError::Source(format!("update {IMPORT_REF} for {url}: {e}")))?;

    Ok(commit_id.to_hex().to_string())
}

/// Mutable in-memory directory while assembling the import; leaves carry a written
/// blob oid plus the git mode to encode, subdirectories nest further `ImportDir`s.
#[derive(Default)]
struct ImportDir {
    children: std::collections::BTreeMap<String, ImportNode>,
}

enum ImportNode {
    Leaf { kind: EntryKind, oid: gix::ObjectId },
    Dir(ImportDir),
}

impl ImportDir {
    fn insert(&mut self, path: &Path, kind: EntryKind, oid: gix::ObjectId) -> Result<()> {
        let mut components = Vec::new();
        for component in path.components() {
            let name = component.as_os_str().to_str().ok_or_else(|| {
                SourceError::Source(format!("non-utf8 import path: {}", path.display()))
            })?;
            components.push(safe_component(name)?.to_string());
        }
        let Some((leaf, dirs)) = components.split_last() else {
            return Err(SourceError::Source("empty import path".to_owned()));
        };

        let mut dir = self;
        for segment in dirs {
            let node = dir
                .children
                .entry(segment.clone())
                .or_insert_with(|| ImportNode::Dir(ImportDir::default()));
            match node {
                ImportNode::Dir(child) => dir = child,
                ImportNode::Leaf { .. } => {
                    return Err(SourceError::Source(format!(
                        "import path collides file and directory at {segment:?}"
                    )));
                }
            }
        }
        match dir.children.entry(leaf.clone()) {
            std::collections::btree_map::Entry::Vacant(slot) => {
                slot.insert(ImportNode::Leaf { kind, oid });
                Ok(())
            }
            std::collections::btree_map::Entry::Occupied(existing) => match existing.get() {
                ImportNode::Dir(_) => Err(SourceError::Source(format!(
                    "import path collides file and directory at {leaf:?}"
                ))),
                ImportNode::Leaf { .. } => Err(SourceError::Source(format!(
                    "duplicate archive entry path: {leaf:?}"
                ))),
            },
        }
    }
}

fn write_import_tree(repo: &gix::Repository, dir: &ImportDir, url: &str) -> Result<gix::ObjectId> {
    let mut entries = Vec::with_capacity(dir.children.len());
    for (name, node) in &dir.children {
        let (mode, oid) = match node {
            ImportNode::Leaf { kind, oid } => ((*kind).into(), *oid),
            ImportNode::Dir(child) => {
                let child_oid = write_import_tree(repo, child, url)?;
                (EntryKind::Tree.into(), child_oid)
            }
        };
        entries.push(gix::objs::tree::Entry {
            mode,
            filename: name.as_str().into(),
            oid,
        });
    }
    // Git tree order treats directory names as suffixed with '/'; Entry's Ord encodes
    // exactly that, so sorting here makes the tree id input-order independent.
    entries.sort();

    let tree = gix::objs::Tree { entries };
    Ok(repo
        .write_object(&tree)
        .map_err(|e| SourceError::Source(format!("write tree for {url}: {e}")))?
        .detach())
}

/// HEAD of a local working-tree repo; a non-repo or unborn HEAD yields the
/// `"link"` sentinel, since link mode must tolerate a plain directory.
pub fn read_local_head(path: &str) -> crate::error::Result<String> {
    let Ok(repo) = gix::open(path) else {
        return Ok("link".to_owned());
    };
    match repo.head_id() {
        Ok(id) => Ok(id.to_hex().to_string()),
        Err(_) => Ok("link".to_owned()),
    }
}

/// True when `git` is a local filesystem path (absolute or existing), not a scheme/scp-style URL.
#[must_use]
pub fn is_local_path(git: &str) -> bool {
    if git.contains("://") {
        return false;
    }
    let first_slash = git.find('/');
    if let Some(colon) = git.find(':')
        && first_slash.is_none_or(|slash| colon < slash)
    {
        return false;
    }
    let path = Path::new(git);
    path.is_absolute() || path.exists()
}

fn hash_framed_entry(hasher: &mut blake3::Hasher, rel_path: &[u8], tag: &[u8], payload: &[u8]) {
    hasher.update(&(rel_path.len() as u64).to_le_bytes());
    hasher.update(rel_path);
    hasher.update(tag);
    hasher.update(&(payload.len() as u64).to_le_bytes());
    hasher.update(payload);
}

fn set_deterministic_mtime(path: &Path, commit_time: u64) -> Result<()> {
    let seconds = i64::try_from(commit_time)
        .map_err(|e| SourceError::Source(format!("commit_time out of range: {e}")))?;
    filetime::set_file_mtime(path, filetime::FileTime::from_unix_time(seconds, 0))?;
    Ok(())
}

#[cfg(unix)]
fn materialize_symlink(out_path: &Path, target: &[u8]) -> Result<()> {
    use std::os::unix::ffi::OsStrExt;
    let target = std::ffi::OsStr::from_bytes(target);
    std::os::unix::fs::symlink(target, out_path)?;
    Ok(())
}

#[cfg(windows)]
fn materialize_symlink(out_path: &Path, target: &[u8]) -> Result<()> {
    let target = String::from_utf8_lossy(target);
    std::os::windows::fs::symlink_file(target.as_ref(), out_path)?;
    Ok(())
}

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

    use std::process::Command;

    use tempfile::TempDir;

    fn sn(name: &str) -> SourceName {
        SourceName::trusted(name)
    }

    /// Author time on the tagged (first) commit; deliberately != committer time.
    const TAGGED_AUTHOR_TIME: u64 = 1_700_000_000;
    /// Committer time on the tagged commit; `commit_time` must NOT return this.
    const TAGGED_COMMITTER_TIME: u64 = 1_800_000_000;
    /// Well-formed 40-hex SHA that is guaranteed absent from the repo.
    const ABSENT_SHA: &str = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";

    struct GitFixture {
        src: TempDir,
        _git_dir: TempDir,
        backend: GitBackend,
        url: String,
        /// First commit; pointed at by tag `v1.0`. Author != committer time.
        tag_sha: String,
        /// Second commit on `main`; distinct from `tag_sha`.
        head_sha: String,
        /// Tip of the non-default `develop` branch; not pointed at by HEAD/main.
        develop_sha: String,
        /// Commit reachable ONLY via tag `v-orphan`; no branch head leads to it.
        orphan_sha: String,
    }

    impl GitFixture {
        fn rev_parse(&self, rev: &str) -> String {
            let out = run_git(self.src.path(), &["rev-parse", rev]);
            String::from_utf8(out.stdout)
                .expect("rev-parse output is utf8")
                .trim()
                .to_string()
        }
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn run_git_dated(
        cwd: &Path,
        args: &[&str],
        author_date: &str,
        committer_date: &str,
    ) -> std::process::Output {
        crate::store::assert_git_sandboxed(cwd);
        let _serial = crate::store::guard_git_fork();
        let out = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_AUTHOR_DATE", author_date)
            .env("GIT_COMMITTER_DATE", committer_date)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out
    }

    fn run_git(cwd: &Path, args: &[&str]) -> std::process::Output {
        run_git_dated(cwd, args, "@1700000000 +0000", "@1700000000 +0000")
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    #[expect(
        clippy::too_many_lines,
        reason = "single linear fixture builder; splitting obscures the seeded git history"
    )]
    fn build_git_fixture() -> GitFixture {
        let src = TempDir::new().unwrap();
        let src_path = src.path();

        run_git(src_path, &["init", "-b", "main", "."]);
        run_git(src_path, &["config", "user.email", "test@example.com"]);
        run_git(src_path, &["config", "user.name", "Test"]);

        std::fs::write(src_path.join("README.md"), b"hello\n").unwrap();
        run_git(src_path, &["add", "README.md"]);
        run_git_dated(
            src_path,
            &["commit", "-m", "initial"],
            "@1700000000 +0000",
            "@1800000000 +0000",
        );
        run_git(src_path, &["tag", "v1.0"]);

        let tag_out = run_git(src_path, &["rev-parse", "v1.0^{commit}"]);
        let tag_sha = String::from_utf8(tag_out.stdout)
            .unwrap()
            .trim()
            .to_string();

        std::fs::write(src_path.join("SECOND.md"), b"second commit\n").unwrap();
        run_git(src_path, &["add", "SECOND.md"]);
        run_git(src_path, &["commit", "-m", "second"]);

        let head_out = run_git(src_path, &["rev-parse", "HEAD"]);
        let head_sha = String::from_utf8(head_out.stdout)
            .unwrap()
            .trim()
            .to_string();

        assert_ne!(
            tag_sha, head_sha,
            "fixture must produce two distinct commits so tag != HEAD is meaningful"
        );

        run_git(src_path, &["checkout", "-b", "develop"]);
        std::fs::write(src_path.join("DEVELOP.md"), b"develop branch\n").unwrap();
        run_git(src_path, &["add", "DEVELOP.md"]);
        run_git(src_path, &["commit", "-m", "develop"]);
        let develop_out = run_git(src_path, &["rev-parse", "develop"]);
        let develop_sha = String::from_utf8(develop_out.stdout)
            .unwrap()
            .trim()
            .to_string();
        run_git(src_path, &["checkout", "main"]);

        run_git(src_path, &["checkout", "--orphan", "orphanbranch"]);
        run_git(src_path, &["rm", "-rf", "--cached", "."]);
        for entry in std::fs::read_dir(src_path).unwrap() {
            let path = entry.unwrap().path();
            if path.file_name().is_some_and(|n| n == ".git") {
                continue;
            }
            if path.is_dir() {
                std::fs::remove_dir_all(&path).unwrap();
            } else {
                std::fs::remove_file(&path).unwrap();
            }
        }
        std::fs::write(src_path.join("ORPHAN.md"), b"orphan commit\n").unwrap();
        run_git(src_path, &["add", "ORPHAN.md"]);
        run_git(src_path, &["commit", "-m", "orphan"]);
        let orphan_sha = String::from_utf8(run_git(src_path, &["rev-parse", "HEAD"]).stdout)
            .unwrap()
            .trim()
            .to_string();
        run_git(src_path, &["tag", "-a", "v-orphan", "-m", "orphan tag"]);
        run_git(src_path, &["checkout", "main"]);
        run_git(src_path, &["branch", "-D", "orphanbranch"]);

        let is_ancestor_of_main = {
            let _serial = crate::store::guard_git_fork();
            Command::new("git")
                .args(["merge-base", "--is-ancestor", &orphan_sha, "main"])
                .current_dir(src_path)
                .status()
                .unwrap()
                .success()
        };
        assert!(
            !is_ancestor_of_main,
            "orphan commit must be unreachable from main, else heads-only fetch could pull it incidentally"
        );

        let is_ancestor_of_develop = {
            let _serial = crate::store::guard_git_fork();
            Command::new("git")
                .args(["merge-base", "--is-ancestor", &orphan_sha, "develop"])
                .current_dir(src_path)
                .status()
                .unwrap()
                .success()
        };
        assert!(
            !is_ancestor_of_develop,
            "orphan commit must be unreachable from develop, else heads-only fetch could pull it incidentally"
        );

        for sha in [&tag_sha, &head_sha, &develop_sha] {
            assert_ne!(
                &orphan_sha, sha,
                "orphan commit must be distinct from the reachable commits"
            );
        }

        let head_after_checkout =
            String::from_utf8(run_git(src_path, &["rev-parse", "HEAD"]).stdout)
                .unwrap()
                .trim()
                .to_string();

        assert_ne!(
            develop_sha, head_sha,
            "develop must advance past main so resolving it is a non-default-branch test"
        );
        assert_eq!(
            head_after_checkout, head_sha,
            "HEAD must point at main, leaving develop as a non-default branch"
        );

        let git_dir = TempDir::new().unwrap();
        let backend = GitBackend::new(git_dir.path().to_path_buf());
        let url = src_path.to_string_lossy().into_owned();

        GitFixture {
            src,
            _git_dir: git_dir,
            backend,
            url,
            tag_sha,
            head_sha,
            develop_sha,
            orphan_sha,
        }
    }

    fn is_bare_repo(path: &Path) -> bool {
        path.join("objects").is_dir() && (path.join("refs").is_dir() || path.join("HEAD").is_file())
    }

    /// Author timestamp of the single commit in [`build_export_fixture`]; every
    /// exported file's mtime must equal this.
    const EXPORT_COMMIT_TIME: u64 = 1_700_000_000;

    const EDITOR_INIT_CONTENT: &[u8] = b"-- editor init\nvim.opt.number = true\n";
    const EDITOR_OPTS_CONTENT: &[u8] = b"-- nested opts\nreturn {}\n";
    const EDITOR_RUN_CONTENT: &[u8] = b"#!/bin/sh\necho run\n";
    const EDITOR_NOTES_CONTENT: &[u8] = b"scratch notes, excluded by **/*.bak\n";
    const LINK_NAME: &str = "link";
    const LINK_TARGET: &str = "init.lua";

    struct ExportFixture {
        _src: TempDir,
        _git_dir: TempDir,
        backend: GitBackend,
        url: String,
        /// Sole commit; its author time equals [`EXPORT_COMMIT_TIME`].
        commit: String,
    }

    /// Clean base with no root-level symlink: `editor/` is symlink-free; the
    /// only symlink lives in a dedicated `linky/` artifact.
    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_export_fixture() -> ExportFixture {
        let src = TempDir::new().unwrap();
        let src_path = src.path();

        init_export_repo(src_path);

        let editor = src_path.join("editor");
        std::fs::create_dir_all(editor.join("lua")).unwrap();
        std::fs::create_dir_all(editor.join("bin")).unwrap();
        std::fs::write(editor.join("init.lua"), EDITOR_INIT_CONTENT).unwrap();
        std::fs::write(editor.join("lua/opts.lua"), EDITOR_OPTS_CONTENT).unwrap();
        std::fs::write(editor.join("bin/run.sh"), EDITOR_RUN_CONTENT).unwrap();
        std::fs::write(editor.join("notes.bak"), EDITOR_NOTES_CONTENT).unwrap();

        std::fs::create_dir_all(src_path.join("lint")).unwrap();
        std::fs::write(src_path.join("lint/rules.toml"), b"[rules]\n").unwrap();

        let linky = src_path.join("linky");
        std::fs::create_dir_all(&linky).unwrap();
        std::fs::write(linky.join("init.lua"), EDITOR_INIT_CONTENT).unwrap();

        std::fs::create_dir_all(src_path.join(".hidden")).unwrap();
        std::fs::write(src_path.join(".hidden/secret"), b"nope\n").unwrap();

        run_git(src_path, &["add", "-A"]);
        run_git(
            src_path,
            &["update-index", "--chmod=+x", "editor/bin/run.sh"],
        );

        std::os::unix::fs::symlink(LINK_TARGET, linky.join(LINK_NAME)).unwrap();
        run_git(src_path, &["add", "linky/link"]);

        let commit = commit_export_repo(src_path);

        let link_mode =
            String::from_utf8(run_git(src_path, &["ls-files", "-s", "linky/link"]).stdout).unwrap();
        assert!(
            link_mode.starts_with("120000"),
            "linky/link must be committed as a git symlink (120000), got: {link_mode}"
        );
        let run_mode =
            String::from_utf8(run_git(src_path, &["ls-files", "-s", "editor/bin/run.sh"]).stdout)
                .unwrap();
        assert!(
            run_mode.starts_with("100755"),
            "editor/bin/run.sh must be committed executable (100755), got: {run_mode}"
        );

        export_fixture_from(src, commit)
    }

    const FILE_TAG: &[u8] = b"\x00file\x00";

    fn build_collision_fixture(files: &[(&str, &[u8])]) -> ExportFixture {
        let src = TempDir::new().expect("collision src tempdir");
        let src_path = src.path();
        init_export_repo(src_path);

        let art = src_path.join("art");
        std::fs::create_dir_all(&art).expect("create art dir");
        for (name, content) in files {
            std::fs::write(art.join(name), content).expect("write collision file");
        }
        run_git(src_path, &["add", "-A"]);
        let commit = commit_export_repo(src_path);

        export_fixture_from(src, commit)
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_symlink_template_collision_fixture() -> ExportFixture {
        let src = TempDir::new().unwrap();
        let src_path = src.path();
        init_export_repo(src_path);

        let art = src_path.join("art");
        std::fs::create_dir_all(&art).unwrap();
        std::fs::write(art.join("link.tmpl"), b"rendered\n").unwrap();
        std::os::unix::fs::symlink(LINK_TARGET, art.join("link")).unwrap();
        run_git(src_path, &["add", "-A"]);
        let commit = commit_export_repo(src_path);

        export_fixture_from(src, commit)
    }

    fn build_dir_template_collision_fixture() -> ExportFixture {
        let src = TempDir::new().expect("collision src tempdir");
        let src_path = src.path();
        init_export_repo(src_path);

        let art = src_path.join("art");
        std::fs::create_dir_all(art.join("config")).expect("create config dir");
        std::fs::write(art.join("config").join("inner.txt"), b"inner\n").expect("write inner");
        std::fs::write(art.join("config.tmpl"), b"rendered\n").expect("write config.tmpl");
        run_git(src_path, &["add", "-A"]);
        let commit = commit_export_repo(src_path);

        export_fixture_from(src, commit)
    }

    fn digest_of_art(fixture: &ExportFixture) -> String {
        fixture
            .backend
            .compute_digest(
                &sn("src"),
                &fixture.url,
                &fixture.commit,
                Some(Path::new("art")),
                &[],
                &[],
            )
            .expect("digest computes over the art subtree")
    }

    fn init_export_repo(src_path: &Path) {
        run_git(src_path, &["init", "-b", "main", "."]);
        run_git(src_path, &["config", "user.email", "test@example.com"]);
        run_git(src_path, &["config", "user.name", "Test"]);
        run_git(src_path, &["config", "core.autocrlf", "false"]);
    }

    #[test]
    fn list_source_leaves_under_a_root_yields_root_relative_leaves_without_the_root_prefix() {
        let src = TempDir::new().expect("leaf-root src tempdir");
        let src_path = src.path();
        init_export_repo(src_path);

        let art = src_path.join("art");
        std::fs::create_dir_all(art.join("nested")).expect("create art/nested");
        std::fs::write(art.join("top.lua"), b"-- top\n").expect("write art/top.lua");
        std::fs::write(art.join("nested").join("inner.lua"), b"-- inner\n")
            .expect("write art/nested/inner.lua");
        std::fs::write(src_path.join("OUTSIDE.md"), b"sibling outside the root\n")
            .expect("write OUTSIDE.md");
        run_git(src_path, &["add", "-A"]);
        let commit = commit_export_repo(src_path);

        let fixture = export_fixture_from(src, commit);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch builds the mirror the leaf walk reads");

        let leaves = fixture
            .backend
            .list_source_leaves(
                &sn("src"),
                &fixture.url,
                &fixture.commit,
                Some(Path::new("art")),
            )
            .expect("leaf walk under root = art succeeds");

        assert_eq!(
            leaves,
            vec!["nested/inner.lua".to_string(), "top.lua".to_string()],
            "leaves under root = `art` must be ROOT-RELATIVE with no `art/` prefix, and must \
             exclude the sibling `OUTSIDE.md` that lives outside the root; got: {leaves:?}"
        );
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn commit_export_repo(src_path: &Path) -> String {
        run_git_dated(
            src_path,
            &["commit", "-m", "artifacts"],
            "@1700000000 +0000",
            "@1800000000 +0000",
        );
        String::from_utf8(run_git(src_path, &["rev-parse", "HEAD"]).stdout)
            .unwrap()
            .trim()
            .to_string()
    }

    fn export_fixture_from(src: TempDir, commit: String) -> ExportFixture {
        let git_dir = TempDir::new().expect("git dir tempdir");
        let backend = GitBackend::new(git_dir.path().to_path_buf());
        let url = src.path().to_string_lossy().into_owned();

        ExportFixture {
            _src: src,
            _git_dir: git_dir,
            backend,
            url,
            commit,
        }
    }

    fn mtime_secs(path: &Path) -> u64 {
        let ft = filetime::FileTime::from_last_modification_time(
            &std::fs::metadata(path).expect("metadata of exported file"),
        );
        u64::try_from(ft.unix_seconds()).expect("non-negative mtime")
    }

    #[test]
    fn fixture_tag_and_head_are_distinct_forty_hex_commits() {
        let fixture = build_git_fixture();
        for sha in [&fixture.tag_sha, &fixture.head_sha] {
            assert_eq!(sha.len(), 40);
            assert!(sha.chars().all(|c| c.is_ascii_hexdigit()));
        }
        assert_ne!(fixture.tag_sha, fixture.head_sha);
    }

    #[test]
    fn fetch_creates_real_bare_mirror() {
        let fixture = build_git_fixture();
        let mirror = fixture.backend.mirror_path(&fixture.url);

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch clones bare mirror");

        assert!(mirror.exists(), "mirror dir should exist after fetch");
        assert!(
            is_bare_repo(&mirror),
            "mirror must be a real bare repo: objects/ and refs|HEAD present"
        );
    }

    #[test]
    fn fetch_updates_existing_mirror_with_new_commits() {
        let fixture = build_git_fixture();

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("first fetch clones");

        std::fs::write(fixture.src.path().join("THIRD.md"), b"third commit\n")
            .expect("write third file");
        run_git(fixture.src.path(), &["add", "THIRD.md"]);
        run_git(fixture.src.path(), &["commit", "-m", "third"]);
        let third_sha = fixture.rev_parse("HEAD");
        assert_ne!(third_sha, fixture.head_sha, "third commit must be new");

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("second fetch updates existing mirror");

        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Branch("main".into()))
            .expect("branch resolves after update fetch");

        assert_eq!(
            resolved, third_sha,
            "fetch on an existing mirror must pull new commits, not no-op"
        );
    }

    #[test]
    fn fetch_reclones_a_corrupt_canonical_mirror() {
        let fixture = build_git_fixture();
        let mirror = fixture.backend.mirror_path(&fixture.url);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("first fetch clones");

        std::fs::remove_dir_all(&mirror).expect("drop the real mirror");
        std::fs::create_dir_all(&mirror).expect("recreate an empty mirror dir");
        std::fs::write(mirror.join("garbage"), b"not a repo").expect("write garbage");
        assert!(gix::open(&mirror).is_err(), "corrupt mirror must not open");

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch must self-heal a corrupt mirror, not error");

        assert!(
            is_bare_repo(&mirror),
            "mirror must be a valid bare repo after self-heal"
        );
        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Branch("main".into()))
            .expect("branch resolves after self-heal");
        assert_eq!(resolved, fixture.head_sha);
    }

    #[test]
    fn mirror_ready_tracks_fetch_and_a_cleared_cache() {
        let fixture = build_git_fixture();
        let mirror = fixture.backend.mirror_path(&fixture.url);

        assert!(
            !fixture.backend.mirror_ready(&fixture.url),
            "no mirror yet: not ready"
        );

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch clones");
        assert!(
            fixture.backend.mirror_ready(&fixture.url),
            "a freshly cloned mirror is ready"
        );

        std::fs::remove_dir_all(&mirror).expect("clear the mirror cache");
        assert!(
            !fixture.backend.mirror_ready(&fixture.url),
            "a cleared cache is not ready, forcing a re-fetch on the next lock hit"
        );
    }

    #[test]
    fn fetch_sweeps_a_stale_orphan_staging_dir() {
        let fixture = build_git_fixture();
        let git_dir = fixture.backend.git_dir.clone();
        std::fs::create_dir_all(&git_dir).expect("git dir");
        let key = MirrorKey::from_url(&NormalizedUrl::parse(&fixture.url));
        let orphan = git_dir.join(format!(".{}.staging-424242-0", key.as_str()));
        std::fs::create_dir_all(orphan.join("objects/pack")).expect("create orphan staging");
        std::fs::write(orphan.join("objects/pack/partial-pack"), b"x").expect("write partial");
        let stale = filetime::FileTime::from_unix_time(1_600_000_000, 0);
        for entry in walkdir::WalkDir::new(&orphan) {
            let path = entry.expect("walk orphan").into_path();
            filetime::set_file_mtime(&path, stale).expect("backdate orphan past grace");
        }

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        assert!(
            !orphan.exists(),
            "a stale orphan staging dir must be swept by fetch"
        );
        assert!(is_bare_repo(&fixture.backend.mirror_path(&fixture.url)));
    }

    #[test]
    fn fetch_keeps_a_staging_dir_with_recent_inner_writes() {
        let fixture = build_git_fixture();
        let git_dir = fixture.backend.git_dir.clone();
        std::fs::create_dir_all(&git_dir).expect("git dir");
        let key = MirrorKey::from_url(&NormalizedUrl::parse(&fixture.url));
        let live = git_dir.join(format!(".{}.staging-424242-1", key.as_str()));
        let pack = live.join("objects/pack");
        std::fs::create_dir_all(&pack).expect("create live staging");
        std::fs::write(pack.join("tmp_pack_incoming"), b"receiving").expect("write partial pack");
        let stale = filetime::FileTime::from_unix_time(1_600_000_000, 0);
        filetime::set_file_mtime(&live, stale).expect("backdate staging root past grace");

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        assert!(
            live.exists(),
            "a staging dir whose root mtime is stale but whose pack write is recent is a live \
             clone and must survive"
        );
    }

    #[test]
    fn fetch_reclones_when_in_place_fetch_fails() {
        let fixture = build_git_fixture();
        let mirror = fixture.backend.mirror_path(&fixture.url);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("first fetch clones");
        assert!(gix::open(&mirror).is_ok(), "mirror opens after first clone");

        run_git(
            &mirror,
            &["remote", "set-url", "origin", "/nonexistent/repo.git"],
        );

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch must self-heal when an in-place fetch fails, not error");

        assert!(
            is_bare_repo(&mirror),
            "mirror must be a valid bare repo after self-heal"
        );
        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Branch("main".into()))
            .expect("branch resolves after self-heal");
        assert_eq!(resolved, fixture.head_sha);
    }

    #[test]
    fn resolve_branch_main_returns_second_commit_not_tag() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Branch("main".into()))
            .expect("branch resolves to head commit");

        assert_eq!(resolved, fixture.head_sha);
        assert_ne!(
            resolved, fixture.tag_sha,
            "main points at the second commit, not the tagged first commit"
        );
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_trunk_default_repo() -> (TempDir, TempDir, GitBackend, String, String) {
        let src = TempDir::new().unwrap();
        let p = src.path();
        run_git(p, &["init", "-b", "trunk", "."]);
        run_git(p, &["config", "user.email", "test@example.com"]);
        run_git(p, &["config", "user.name", "Test"]);
        std::fs::write(p.join("README.md"), b"on trunk\n").unwrap();
        run_git(p, &["add", "README.md"]);
        run_git(p, &["commit", "-m", "initial"]);
        let trunk_sha = String::from_utf8(run_git(p, &["rev-parse", "HEAD"]).stdout)
            .unwrap()
            .trim()
            .to_string();

        let git_dir = TempDir::new().unwrap();
        let backend = GitBackend::new(git_dir.path().to_path_buf());
        let url = p.to_string_lossy().into_owned();
        (src, git_dir, backend, url, trunk_sha)
    }

    #[test]
    fn resolve_default_follows_remote_default_branch_when_not_main() {
        let (_src, _git_dir, backend, url, trunk_sha) = build_trunk_default_repo();

        backend
            .fetch(&sn("src"), &url)
            .expect("fetch a repo whose default branch is trunk");

        let resolved = backend
            .resolve(&sn("src"), &url, &Refspec::Default)
            .expect("Default must resolve against a repo that has no `main` branch");

        assert_eq!(
            resolved, trunk_sha,
            "an unspecified ref must follow the repo's actual default branch (trunk), \
             not assume `main` — which does not exist here"
        );
    }

    #[test]
    fn resolve_default_survives_an_incremental_fetch() {
        let (src, _git_dir, backend, url, _first_sha) = build_trunk_default_repo();
        backend.fetch(&sn("src"), &url).expect("first fetch");

        std::fs::write(src.path().join("SECOND.md"), b"more\n").expect("write");
        run_git(src.path(), &["add", "SECOND.md"]);
        run_git(src.path(), &["commit", "-m", "second"]);
        let advanced = String::from_utf8(run_git(src.path(), &["rev-parse", "HEAD"]).stdout)
            .expect("utf8")
            .trim()
            .to_string();

        backend
            .fetch(&sn("src"), &url)
            .expect("incremental fetch on the existing mirror");
        let resolved = backend
            .resolve(&sn("src"), &url, &Refspec::Default)
            .expect("Default still resolves after an incremental fetch");

        assert_eq!(
            resolved, advanced,
            "Default must track the default branch tip across an incremental fetch, \
             not a stale HEAD"
        );
    }

    #[test]
    fn file_diff_between_reads_both_commits_and_reports_the_changed_path() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let changed = fixture
            .backend
            .file_diff_between(
                &sn("src"),
                &fixture.url,
                &fixture.tag_sha,
                &fixture.head_sha,
            )
            .expect("diff between two commits resolves both trees");

        assert!(
            changed.iter().any(|p| p == "SECOND.md"),
            "the diff must list `SECOND.md`, which exists only in the second commit's tree — \
             proving file_diff_between read BOTH commits, not just one; got: {changed:?}"
        );
        assert!(
            !changed.iter().any(|p| p == "README.md"),
            "`README.md` is byte-identical across both commits and must NOT appear in the diff; \
             got: {changed:?}"
        );
    }

    #[test]
    fn resolve_non_default_branch_after_first_clone() {
        let fixture = build_git_fixture();

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("first fetch clones bare mirror");

        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Branch("develop".into()))
            .expect("non-default branch resolves after a single first-clone fetch");

        assert_eq!(
            resolved, fixture.develop_sha,
            "first clone must mirror all heads, not only the default branch"
        );
    }

    #[test]
    fn resolve_tag_returns_tagged_commit_not_head() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Tag("v1.0".into()))
            .expect("tag resolves to tagged commit");

        assert_eq!(resolved, fixture.tag_sha);
        assert_ne!(
            resolved, fixture.head_sha,
            "tag must resolve to its commit, not HEAD/main"
        );
    }

    #[test]
    fn resolve_tag_unreachable_from_any_head_after_single_fetch() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let resolved = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Tag("v-orphan".into()))
            .expect("a tag unreachable from every branch head resolves after one fetch");

        assert_eq!(
            resolved, fixture.orphan_sha,
            "the mirror must fetch tags, not only commits reachable from heads"
        );
    }

    #[test]
    fn resolve_rev_unreachable_from_any_head_after_single_fetch() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let resolved = fixture
            .backend
            .resolve(
                &sn("src"),
                &fixture.url,
                &Refspec::Rev(fixture.orphan_sha.clone()),
            )
            .expect("a bare sha unreachable from every head resolves after one fetch");

        assert_eq!(
            resolved, fixture.orphan_sha,
            "fetching tags must bring the tagged object into the mirror, not just the ref"
        );
    }

    #[test]
    #[expect(
        clippy::unwrap_used,
        reason = "removing the source repo fails loudly if the fixture path is gone"
    )]
    fn single_fetch_covers_reachable_and_unreachable_tags() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("single fetch");

        std::fs::remove_dir_all(fixture.src.path()).unwrap();
        assert!(
            fixture.backend.fetch(&sn("src"), &fixture.url).is_err(),
            "guard: after removing the source repo a fresh fetch from url MUST fail; \
             otherwise this test cannot prove the single fetch was self-contained"
        );

        let reachable = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Tag("v1.0".into()))
            .expect(
                "reachable tag resolves from the mirror after the remote is gone — \
                 no hidden refetch needed",
            );
        let unreachable = fixture
            .backend
            .resolve(&sn("src"), &fixture.url, &Refspec::Tag("v-orphan".into()))
            .expect(
                "unreachable tag resolves from the mirror after the remote is gone; \
                 if resolve relied on a fallback fetch-on-miss this would fail, \
                 proving one fetch per source was NOT achieved",
            );
        let orphan_rev = fixture
            .backend
            .resolve(
                &sn("src"),
                &fixture.url,
                &Refspec::Rev(fixture.orphan_sha.clone()),
            )
            .expect(
                "the bare orphan sha resolves from the mirror after the remote is gone; \
                 the single fetch must have brought the tagged object in, not just the ref",
            );

        assert_eq!(reachable, fixture.tag_sha);
        assert_eq!(unreachable, fixture.orphan_sha);
        assert_eq!(orphan_rev, fixture.orphan_sha);
    }

    #[test]
    fn resolve_rev_returns_same_sha() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let resolved = fixture
            .backend
            .resolve(
                &sn("src"),
                &fixture.url,
                &Refspec::Rev(fixture.head_sha.clone()),
            )
            .expect("rev resolves to itself");

        assert_eq!(resolved, fixture.head_sha);
    }

    #[test]
    fn resolve_rev_for_absent_sha_errors() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let result =
            fixture
                .backend
                .resolve(&sn("src"), &fixture.url, &Refspec::Rev(ABSENT_SHA.into()));

        assert!(
            result.is_err(),
            "a well-formed but absent rev must error, proving resolve consults the mirror"
        );
    }

    #[test]
    fn resolve_nonexistent_branch_errors() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let result =
            fixture
                .backend
                .resolve(&sn("src"), &fixture.url, &Refspec::Branch("nope".into()));

        assert!(result.is_err(), "missing branch must error");
    }

    #[test]
    fn resolve_without_fetch_errors() {
        let fixture = build_git_fixture();

        let result =
            fixture
                .backend
                .resolve(&sn("src"), &fixture.url, &Refspec::Branch("main".into()));

        assert!(result.is_err(), "resolve without a mirror must error");
    }

    #[test]
    fn commit_time_returns_author_time_not_committer_time() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let time = fixture
            .backend
            .commit_time(&sn("src"), &fixture.url, &fixture.tag_sha)
            .expect("commit time resolves");

        assert_eq!(
            time, TAGGED_AUTHOR_TIME,
            "commit_time must return the author timestamp"
        );
        assert_ne!(
            time, TAGGED_COMMITTER_TIME,
            "commit_time must NOT return the committer timestamp"
        );
    }

    // ---- MIRROR-LOCK-001: per-mirror BLOCKING flock around fetch ----

    use std::sync::mpsc;
    use std::time::Duration;

    /// The exact per-mirror lock-file path the implementation must use:
    /// `<git_dir>/<MirrorKey>.git.lock` (the mirror dir path with `.lock`
    /// appended). Derived independently from `mirror_path` so the test fails if
    /// the impl picks a different naming.
    fn mirror_lock_path(git_dir: &Path, url: &str) -> PathBuf {
        let mut s = mirror_path(git_dir, url).into_os_string();
        s.push(".lock");
        PathBuf::from(s)
    }

    /// Minimal seeded git repo at `path` with a single commit on `main`; used as
    /// a `url` for a SECOND distinct mirror (different `MirrorKey`).
    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_minimal_repo(path: &Path) {
        run_git(path, &["init", "-b", "main", "."]);
        run_git(path, &["config", "user.email", "test@example.com"]);
        run_git(path, &["config", "user.name", "Test"]);
        std::fs::write(path.join("ONLY.md"), b"only commit\n").unwrap();
        run_git(path, &["add", "ONLY.md"]);
        run_git(path, &["commit", "-m", "only"]);
    }

    /// Holds an exclusive advisory lock on `path` (creating it). The test grabs
    /// the lock the binary's `fetch` will contend for; held until dropped.
    fn hold_mirror_lock(path: &Path) -> std::fs::File {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("create git_dir for lock");
        }
        let file = std::fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(path)
            .expect("open per-mirror lock file");
        file.try_lock()
            .expect("test acquires the mirror lock first");
        file
    }

    #[test]
    fn fetch_blocks_on_held_per_mirror_lock_then_succeeds_when_released() {
        let fixture = build_git_fixture();
        let git_dir = fixture.backend.git_dir.clone();
        let url = fixture.url.clone();

        let lock_path = mirror_lock_path(&git_dir, &url);
        let held = hold_mirror_lock(&lock_path);

        let (tx, rx) = mpsc::channel();
        let backend = GitBackend::new(git_dir.clone());
        let url_for_thread = url.clone();
        let worker = std::thread::spawn(move || {
            let result = backend.fetch(&sn("src"), &url_for_thread);
            tx.send(result).expect("send fetch result");
        });

        assert!(
            rx.recv_timeout(Duration::from_millis(750)).is_err(),
            "fetch must BLOCK while the per-mirror lock is held; it completed \
             within the window, so it took no blocking lock on {}",
            lock_path.display()
        );

        drop(held);

        let result = rx
            .recv_timeout(Duration::from_secs(10))
            .expect("fetch must complete promptly once the mirror lock is released");
        worker.join().expect("fetch thread joins");
        result.expect("fetch succeeds after waiting for the lock (blocking, not error)");

        let mirror = mirror_path(&git_dir, &url);
        assert!(
            is_bare_repo(&mirror),
            "the serialized fetch must leave a valid, non-corrupt bare mirror"
        );
        let repo = gix::open(&mirror).expect("mirror opens as a git repo");
        assert!(
            repo.find_reference("refs/heads/main").is_ok(),
            "the serialized fetch must populate refs/heads/main"
        );
    }

    #[test]
    fn fetch_does_not_create_lock_at_mirror_path_without_locking() {
        let fixture = build_git_fixture();
        let git_dir = fixture.backend.git_dir.clone();
        let lock_path = mirror_lock_path(&git_dir, &fixture.url);

        assert!(
            !lock_path.exists(),
            "precondition: no lock file before fetch"
        );

        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch clones bare mirror");

        assert!(
            lock_path.exists(),
            "fetch must create/use the per-mirror lock file at {}",
            lock_path.display()
        );
    }

    #[test]
    fn holding_one_mirror_lock_does_not_block_fetch_of_a_different_mirror() {
        let fixture_a = build_git_fixture();
        let git_dir = fixture_a.backend.git_dir.clone();

        let src_b = TempDir::new().expect("src b tempdir");
        build_minimal_repo(src_b.path());
        let url_b = src_b.path().to_string_lossy().into_owned();

        assert_ne!(
            mirror_path(&git_dir, &fixture_a.url),
            mirror_path(&git_dir, &url_b),
            "the two urls must map to distinct mirrors for this test to mean anything"
        );

        let held_a = hold_mirror_lock(&mirror_lock_path(&git_dir, &fixture_a.url));

        let (tx, rx) = mpsc::channel();
        let backend = GitBackend::new(git_dir.clone());
        let worker = std::thread::spawn(move || {
            let result = backend.fetch(&sn("srcb"), &url_b);
            tx.send(result).expect("send fetch-b result");
        });

        let result = rx.recv_timeout(Duration::from_secs(5)).expect(
            "fetching a DIFFERENT mirror must not block on mirror A's lock; \
             the per-mirror lock must be keyed per MirrorKey",
        );
        worker.join().expect("fetch-b thread joins");
        result.expect("fetch of mirror B succeeds while A's lock is held");

        drop(held_a);
    }

    #[test]
    fn scp_style_ssh_drops_userinfo_and_strips_git_suffix() {
        assert_eq!(
            NormalizedUrl::parse("git@github.com:user/repo.git").as_str(),
            "github.com/user/repo"
        );
    }

    #[test]
    fn is_local_path_rejects_url_and_scp_forms() {
        for url in [
            "https://github.com/me/dotfiles.git",
            "ssh://git@host/x.git",
            "git@github.com:me/dotfiles.git",
            "github.com:me/repo",
        ] {
            assert!(
                !is_local_path(url),
                "url/scp form must not be classified local: {url}"
            );
        }
    }

    #[test]
    fn is_local_path_accepts_absolute_path() {
        assert!(
            is_local_path("/home/soeren/dev/loqui"),
            "an absolute path is a local path even if it does not exist"
        );
    }

    /// Removes its directory on drop, so a panicking assert never leaks it.
    struct CwdRelDir(PathBuf);

    impl Drop for CwdRelDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[expect(clippy::unwrap_used, reason = "tempdir setup fails loudly in tests")]
    #[test]
    fn is_local_path_accepts_existing_relative_path() {
        let nonce = format!(
            "phora-rel-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let cwd = std::env::current_dir().unwrap();
        let abs = cwd.join(&nonce);
        std::fs::create_dir(&abs).unwrap();
        let _cleanup = CwdRelDir(abs);

        assert!(
            is_local_path(&nonce),
            "a relative name that exists under cwd on disk is a local path"
        );
    }

    #[test]
    fn https_strips_scheme_and_git_suffix() {
        assert_eq!(
            NormalizedUrl::parse("https://github.com/user/repo.git").as_str(),
            "github.com/user/repo"
        );
    }

    #[test]
    fn host_is_lowercased_but_path_case_is_preserved() {
        assert_eq!(
            NormalizedUrl::parse("https://GitHub.com/User/Repo").as_str(),
            "github.com/User/Repo"
        );
    }

    #[test]
    fn ssh_scheme_drops_scheme_and_userinfo() {
        assert_eq!(
            NormalizedUrl::parse("ssh://git@github.com/user/repo.git").as_str(),
            "github.com/user/repo"
        );
    }

    #[test]
    fn trailing_slash_is_trimmed() {
        assert_eq!(
            NormalizedUrl::parse("https://github.com/user/repo/").as_str(),
            "github.com/user/repo"
        );
    }

    #[test]
    fn surrounding_whitespace_is_trimmed() {
        assert_eq!(
            NormalizedUrl::parse("  https://github.com/user/repo.git  ").as_str(),
            "github.com/user/repo"
        );
    }

    #[test]
    fn local_path_normalizes_deterministically() {
        let first = NormalizedUrl::parse("/home/x/dev/loqui");
        let second = NormalizedUrl::parse("/home/x/dev/loqui");
        assert_eq!(first, second);
        assert_eq!(first.as_str(), "/home/x/dev/loqui");
    }

    #[test]
    fn equivalent_ssh_and_https_forms_share_one_mirror_key() {
        let ssh = MirrorKey::from_url(&NormalizedUrl::parse("git@github.com:user/repo.git"));
        let https = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo.git"));
        let ssh_scheme =
            MirrorKey::from_url(&NormalizedUrl::parse("ssh://git@github.com/user/repo"));
        assert_eq!(ssh, https);
        assert_eq!(https, ssh_scheme);
    }

    #[test]
    fn symbolic_https_ssh_and_literal_collapse_to_one_mirror_key() {
        use std::collections::BTreeMap;

        use crate::config::{Config, Host, ParsedSource};

        let symbolic = Config::parse(
            r#"
version = 1

[sources.tropos]
host = "github"
path = "srnnkls/tropos"
"#,
        )
        .expect("symbolic config parses");
        let raw = symbolic.sources.get("tropos").expect("tropos source");
        let source = ParsedSource::parse("tropos", raw).expect("tropos parses to typed form");
        let no_user_hosts: BTreeMap<String, Host> = BTreeMap::new();

        let symbolic_https = source
            .resolved_remote(&no_user_hosts, Protocol::Https)
            .expect("symbolic github https resolves");
        let symbolic_ssh = source
            .resolved_remote(&no_user_hosts, Protocol::Ssh)
            .expect("symbolic github ssh resolves");
        let literal_https = "https://github.com/srnnkls/tropos.git";

        let key = |remote: &str| MirrorKey::from_url(&NormalizedUrl::parse(remote));

        assert_eq!(
            key(&symbolic_https),
            key(&symbolic_ssh),
            "flipping protocol must not change the mirror: symbolic https and ssh of one repo \
             must share a MirrorKey"
        );
        assert_eq!(
            key(&symbolic_https),
            key(literal_https),
            "a symbolic host+path source and its literal-URL twin must collapse to one MirrorKey"
        );
    }

    #[test]
    fn mirror_key_is_sixteen_hex_chars() {
        let key = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo.git"));
        assert_eq!(key.as_str().len(), 16);
        assert!(key.as_str().chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn mirror_key_is_deterministic_for_same_input() {
        let first = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo"));
        let second = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo"));
        assert_eq!(first, second);
    }

    #[test]
    fn different_repos_produce_different_keys() {
        let one = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo-a"));
        let two = MirrorKey::from_url(&NormalizedUrl::parse("https://github.com/user/repo-b"));
        assert_ne!(one, two);
    }

    #[test]
    fn mirror_key_matches_blake3_of_normalized_url_truncated_to_sixteen() {
        let url = "git@github.com:user/repo.git";
        let normalized = NormalizedUrl::parse(url);
        let expected = blake3::hash(b"github.com/user/repo").to_hex()[..16].to_string();
        assert_eq!(MirrorKey::from_url(&normalized).as_str(), expected);
    }

    #[test]
    fn mirror_path_is_git_dir_joined_with_key_dot_git() {
        let git_dir = PathBuf::from("/var/phora/git");
        let backend = GitBackend::new(git_dir.clone());
        let url = "git@github.com:user/repo.git";
        let key = MirrorKey::from_url(&NormalizedUrl::parse(url));
        assert_eq!(
            backend.mirror_path(url),
            git_dir.join(format!("{}.git", key.as_str()))
        );
    }

    #[test]
    fn mirror_path_unifies_equivalent_urls_to_one_directory() {
        let backend = GitBackend::new(PathBuf::from("/var/phora/git"));
        assert_eq!(
            backend.mirror_path("git@github.com:user/repo.git"),
            backend.mirror_path("https://github.com/user/repo")
        );
    }

    // ---- read_file_at (offline mirror read; the read_manifest seam) ----

    #[test]
    fn read_file_at_returns_bytes_of_a_file_present_at_the_commit() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch builds the bare mirror");

        let bytes = fixture
            .backend
            .read_file_at(
                &sn("src"),
                &fixture.url,
                &fixture.head_sha,
                Path::new("README.md"),
            )
            .expect("read_file_at reads a tracked file from the fetched mirror at HEAD");

        assert_eq!(
            bytes, b"hello\n",
            "read_file_at must return the exact bytes of README.md at the commit, not a digest or path"
        );
    }

    #[test]
    fn read_file_at_errors_when_the_file_is_absent_at_that_commit() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch builds the bare mirror");

        // SECOND.md was added on the second commit (head_sha); it does NOT exist at tag_sha.
        let err = fixture
            .backend
            .read_file_at(
                &sn("src"),
                &fixture.url,
                &fixture.tag_sha,
                Path::new("SECOND.md"),
            )
            .expect_err("a file absent at the requested commit must be an error, not empty bytes");

        let msg = err.to_string();
        assert!(
            msg.contains("SECOND.md"),
            "the absent-file error must name the path it could not find, got: {msg}"
        );
    }

    #[test]
    fn read_file_at_errors_when_the_mirror_is_missing() {
        let git_dir = TempDir::new().expect("git_dir tempdir");
        let backend = GitBackend::new(git_dir.path().to_path_buf());

        let err = backend
            .read_file_at(
                &sn("src"),
                "https://github.com/never/fetched.git",
                ABSENT_SHA,
                Path::new("phora.toml"),
            )
            .expect_err("reading from a mirror that was never fetched must error, not panic");

        assert!(
            !err.to_string().is_empty(),
            "the missing-mirror error must carry a diagnostic message"
        );
    }

    #[test]
    fn read_file_at_default_impl_is_unsupported_on_non_git_backend() {
        let git_dir = TempDir::new().expect("git_dir tempdir");
        let http = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

        let err = http
            .read_file_at(
                &sn("u"),
                "https://example.com/pkg.tar.gz",
                ABSENT_SHA,
                Path::new("phora.toml"),
            )
            .expect_err(
                "the default SourceBackend::read_file_at must error as unsupported; only GitBackend overrides it",
            );

        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("unsupported")
                || msg.contains("not supported")
                || msg.contains("only git"),
            "the default read_file_at error must signal that mirror reads are git-only (unsupported), got: {msg}"
        );
    }

    #[test]
    fn read_file_at_signals_absent_distinctly_from_other_failures() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch builds the bare mirror");

        let absent = fixture
            .backend
            .read_file_at(
                &sn("src"),
                &fixture.url,
                &fixture.tag_sha,
                Path::new("SECOND.md"),
            )
            .expect_err("an absent file must error");
        assert!(
            matches!(absent, SourceError::FileAbsent { .. }),
            "an absent entry must surface as FileAbsent so callers can stay silent, got: {absent:?}"
        );

        let other = fixture
            .backend
            .read_file_at(&sn("src"), &fixture.url, ABSENT_SHA, Path::new("README.md"))
            .expect_err("an unknown commit must error");
        assert!(
            !matches!(other, SourceError::FileAbsent { .. }),
            "a git/commit failure must NOT be mislabelled as an absent file, got: {other:?}"
        );
    }

    #[test]
    fn read_file_at_errors_clearly_when_entry_is_a_tree_not_a_blob() {
        let src = TempDir::new().expect("src tempdir");
        let src_path = src.path();
        run_git(src_path, &["init", "-b", "main", "."]);
        run_git(src_path, &["config", "user.email", "t@example.com"]);
        run_git(src_path, &["config", "user.name", "T"]);
        std::fs::create_dir(src_path.join("nested")).expect("mk dir");
        std::fs::write(src_path.join("nested").join("leaf"), b"x\n").expect("write leaf");
        run_git(src_path, &["add", "-A"]);
        run_git(src_path, &["commit", "-m", "tree"]);
        let commit = String::from_utf8(run_git(src_path, &["rev-parse", "HEAD"]).stdout)
            .expect("utf8 sha")
            .trim()
            .to_owned();

        let git_dir = TempDir::new().expect("git_dir tempdir");
        let backend = GitBackend::new(git_dir.path().to_path_buf());
        let url = src_path.to_string_lossy().into_owned();
        backend.fetch(&sn("src"), &url).expect("fetch mirror");

        let err = backend
            .read_file_at(&sn("src"), &url, &commit, Path::new("nested"))
            .expect_err("a directory entry must not be returned as file bytes");
        let msg = err.to_string();
        assert!(
            msg.contains("nested"),
            "the non-blob error must name the path, got: {msg}"
        );
        assert!(
            !matches!(err, SourceError::FileAbsent { .. }),
            "a present-but-non-blob entry is not 'absent'; it must be a distinct failure, got: {err:?}"
        );
    }

    // ---- list_tree_at (shallow ls-style listing for `trust --show <dir>`) ----

    fn build_tree_fixture() -> ExportFixture {
        let src = TempDir::new().expect("tree src tempdir");
        let src_path = src.path();
        init_export_repo(src_path);

        let d = src_path.join("d");
        std::fs::create_dir_all(d.join("sub")).expect("create d/sub");
        std::fs::write(d.join("a.txt"), b"a\n").expect("write d/a.txt");
        std::fs::write(d.join("b.txt"), b"b\n").expect("write d/b.txt");
        std::fs::write(d.join("sub").join("c.txt"), b"c\n").expect("write d/sub/c.txt");
        std::fs::write(src_path.join("top.txt"), b"top\n").expect("write top.txt");
        run_git(src_path, &["add", "-A"]);
        let commit = commit_export_repo(src_path);

        let fixture = export_fixture_from(src, commit);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch builds the mirror the tree listing reads");
        fixture
    }

    #[test]
    fn list_tree_at_yields_only_the_direct_children_of_the_directory() {
        let fixture = build_tree_fixture();

        let entries = fixture
            .backend
            .list_tree_at(&sn("src"), &fixture.url, &fixture.commit, Path::new("d"))
            .expect("list_tree_at lists the direct children of `d` at the commit");

        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["a.txt", "b.txt", "sub"],
            "list_tree_at must return the DIRECT children of `d` (root-relative leaf names, \
             sorted), with the subdir `sub` listed as a single entry; got: {names:?}"
        );
        assert!(
            !names.contains(&"c.txt") && !names.iter().any(|n| n.contains('/')),
            "list_tree_at is shallow: `d/sub/c.txt` must NOT be flattened in (no recursion), \
             got: {names:?}"
        );
    }

    #[test]
    fn list_tree_at_marks_subdirectories_as_directories_and_files_as_files() {
        let fixture = build_tree_fixture();

        let entries = fixture
            .backend
            .list_tree_at(&sn("src"), &fixture.url, &fixture.commit, Path::new("d"))
            .expect("list_tree_at lists `d`");

        let sub = entries
            .iter()
            .find(|e| e.name == "sub")
            .expect("the `sub` directory entry must be present");
        assert!(
            sub.is_dir,
            "the `sub` entry is a directory and must be reported as is_dir=true so `--show` can \
             render it ls-style; got: {sub:?}"
        );
        for file in entries.iter().filter(|e| e.name != "sub") {
            assert!(
                !file.is_dir,
                "the regular file `{}` must be reported as is_dir=false, got: {file:?}",
                file.name
            );
        }
    }

    #[test]
    fn list_tree_at_with_empty_path_lists_the_repo_root() {
        let fixture = build_tree_fixture();

        let entries = fixture
            .backend
            .list_tree_at(&sn("src"), &fixture.url, &fixture.commit, Path::new(""))
            .expect("an empty path lists the repo root's top-level entries");

        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["d", "top.txt"],
            "listing the repo root (empty path) must yield the top-level entries `d` and \
             `top.txt`, not the contents of `d`; got: {names:?}"
        );
    }

    #[test]
    fn list_tree_at_errors_when_the_directory_is_absent_at_the_commit() {
        let fixture = build_tree_fixture();

        let err = fixture
            .backend
            .list_tree_at(&sn("src"), &fixture.url, &fixture.commit, Path::new("nope"))
            .expect_err("listing a path that does not exist must error, not return an empty list");

        assert!(
            matches!(err, SourceError::RootNotFound { .. }),
            "an absent directory must surface as RootNotFound (via subtree_at_root), got: {err:?}"
        );
    }

    #[test]
    fn list_tree_at_default_impl_is_unsupported_on_non_git_backend() {
        let git_dir = TempDir::new().expect("git_dir tempdir");
        let http = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

        let err = http
            .list_tree_at(
                &sn("u"),
                "https://example.com/pkg.tar.gz",
                ABSENT_SHA,
                Path::new("d"),
            )
            .expect_err(
                "the default SourceBackend::list_tree_at must error as unsupported; only \
                 GitBackend overrides it (this is the one git-only trust read path)",
            );

        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("unsupported")
                || msg.contains("not supported")
                || msg.contains("only git"),
            "the default list_tree_at error must signal that mirror reads are git-only \
             (unsupported), got: {msg}"
        );
    }

    // ---- fetch_root_manifest (single-file / shallow; no full mirror) ----

    #[test]
    fn fetch_root_manifest_uncached_does_not_build_a_full_mirror() {
        let src = TempDir::new().expect("src tempdir");
        let src_path = src.path();
        run_git(src_path, &["init", "-b", "main", "."]);
        run_git(src_path, &["config", "user.email", "t@example.com"]);
        run_git(src_path, &["config", "user.name", "T"]);
        std::fs::write(
            src_path.join("phora.toml"),
            b"version = 1\n\n[sources.nvim]\ngit = \"https://github.com/dep/nvim.git\"\n",
        )
        .expect("write manifest");
        run_git(src_path, &["add", "-A"]);
        run_git(src_path, &["commit", "-m", "root"]);

        let git_dir = TempDir::new().expect("git_dir tempdir");
        let backend = GitBackend::new(git_dir.path().to_path_buf());
        let url = src_path.to_string_lossy().into_owned();

        let bytes = backend
            .fetch_root_manifest(&sn("dep"), &url, &Refspec::Branch("main".to_owned()))
            .expect("uncached fetch_root_manifest reads the root phora.toml");
        let text = String::from_utf8(bytes).expect("manifest is utf-8");
        assert!(
            text.contains("[sources.nvim]"),
            "fetch_root_manifest must return the root phora.toml bytes, got: {text}"
        );

        assert!(
            !backend.mirror_path(&url).exists(),
            "the uncached path must NOT create a persistent all-refs mirror — that is the regression \
             this task prevents; it must fetch shallowly into ephemeral storage"
        );
    }

    #[test]
    fn fetch_root_manifest_reuses_a_cached_mirror_offline() {
        let fixture = build_git_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("prime the mirror cache");
        std::fs::write(
            fixture.src.path().join("phora.toml"),
            b"version = 1\n\n[sources.x]\ngit = \"https://github.com/dep/x.git\"\n",
        )
        .expect("write manifest");
        run_git(fixture.src.path(), &["add", "-A"]);
        run_git(fixture.src.path(), &["commit", "-m", "add manifest"]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("refresh cached mirror");

        let bytes = fixture
            .backend
            .fetch_root_manifest(
                &sn("src"),
                &fixture.url,
                &Refspec::Branch("main".to_owned()),
            )
            .expect("cached fetch_root_manifest reads via the mirror");
        let text = String::from_utf8(bytes).expect("utf8");
        assert!(
            text.contains("[sources.x]"),
            "cached fetch_root_manifest must read from the primed mirror, got: {text}"
        );
        assert!(
            fixture.backend.mirror_path(&fixture.url).exists(),
            "a primed mirror must be reused, not discarded"
        );
    }

    // ---- safe_component (path-traversal guard) ----

    #[test]
    fn safe_component_accepts_normal_single_components() {
        for name in ["init.lua", "lua", "run.sh", "opts.lua", "a"] {
            assert_eq!(
                safe_component(name).expect("normal single component must be accepted"),
                name,
                "{name} is a normal single path component and must pass through unchanged"
            );
        }
    }

    #[test]
    fn safe_component_rejects_traversal_and_separators() {
        for name in [
            "..",
            ".",
            "",
            "a/b",
            "..\\b",
            "lua\\opts",
            "/abs",
            "/etc/passwd",
            "a/../b",
        ] {
            assert!(
                safe_component(name).is_err(),
                "{name:?} escapes a single path component and must be rejected to prevent staging-dir traversal"
            );
        }
    }

    // ---- export_artifact ----

    fn export_named(
        fixture: &ExportFixture,
        staging: &Path,
        leaves: &[ExportLeaf],
        policy: &ExportPolicy,
    ) -> Result<ExportResult> {
        let source = sn("src");
        let req = ExportRequest {
            source: &source,
            url: &fixture.url,
            commit: &fixture.commit,
            root: None,
            policy,
            staging_dir: staging,
            commit_time: EXPORT_COMMIT_TIME,
            template_opt_in: &TemplateOptIn::SuffixOnly,
            vars: &BTreeMap::new(),
            leaves,
        };
        fixture.backend.export_artifact(&req)
    }

    /// The `editor` artifact's three non-`.bak` leaves, each mapped to its
    /// dir-relative deployed path — the leaf-granular expression of `exclude **/*.bak`.
    fn editor_leaves() -> Vec<ExportLeaf> {
        vec![
            ExportLeaf {
                source: PathBuf::from("editor/init.lua"),
                dest: PathBuf::from("init.lua"),
            },
            ExportLeaf {
                source: PathBuf::from("editor/lua/opts.lua"),
                dest: PathBuf::from("lua/opts.lua"),
            },
            ExportLeaf {
                source: PathBuf::from("editor/bin/run.sh"),
                dest: PathBuf::from("bin/run.sh"),
            },
        ]
    }

    fn export_editor(
        fixture: &ExportFixture,
        staging: &Path,
        policy: &ExportPolicy,
    ) -> Result<ExportResult> {
        export_named(fixture, staging, &editor_leaves(), policy)
    }

    /// The `linky` artifact's blob and symlink leaves, mapped to dir-relative dests.
    fn linky_leaves() -> Vec<ExportLeaf> {
        vec![
            ExportLeaf {
                source: PathBuf::from("linky/init.lua"),
                dest: PathBuf::from("init.lua"),
            },
            ExportLeaf {
                source: PathBuf::from(format!("linky/{LINK_NAME}")),
                dest: PathBuf::from(LINK_NAME),
            },
        ]
    }

    #[test]
    fn export_materializes_files_with_exact_content() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        export_editor(&fixture, staging.path(), &ExportPolicy::default()).expect("export succeeds");

        assert_eq!(
            std::fs::read(staging.path().join("init.lua")).expect("init.lua exists"),
            EDITOR_INIT_CONTENT
        );
        assert_eq!(
            std::fs::read(staging.path().join("lua/opts.lua")).expect("nested opts.lua exists"),
            EDITOR_OPTS_CONTENT
        );
    }

    #[test]
    fn export_excludes_bak_files_by_path_matcher() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_editor(&fixture, staging.path(), &ExportPolicy::default())
            .expect("export succeeds");

        assert!(
            !staging.path().join("notes.bak").exists(),
            "**/*.bak must exclude notes.bak from staging"
        );
        assert!(
            !result
                .files
                .iter()
                .any(|f| f.path == Path::new("notes.bak")),
            "excluded file must not appear in ExportResult.files"
        );
    }

    /// A real source blob renamed onto a dest that buries it under a `.git`
    /// path component — the write-time vector a `take` rename produces. The
    /// `keep.txt` leaf is the control: it must survive.
    fn dot_git_dest_leaves(dest: &str) -> Vec<ExportLeaf> {
        vec![
            ExportLeaf {
                source: PathBuf::from("editor/init.lua"),
                dest: PathBuf::from(dest),
            },
            ExportLeaf {
                source: PathBuf::from("editor/lua/opts.lua"),
                dest: PathBuf::from("keep.txt"),
            },
        ]
    }

    #[test]
    fn export_prunes_a_nested_dot_git_dest_at_write() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_named(
            &fixture,
            staging.path(),
            &dot_git_dest_leaves("nested/.git/config"),
            &ExportPolicy::default(),
        )
        .expect("export succeeds; the .git-dest leaf is pruned, not an error");

        assert!(
            !staging.path().join("nested/.git/config").exists(),
            "a leaf whose DEST buries it under a `.git` component must be pruned at write, never \
             staged under the deploy target where confine cannot guard it"
        );
        assert!(
            !result
                .files
                .iter()
                .any(|f| f.path == Path::new("nested/.git/config")),
            "the pruned `.git`-dest leaf must be absent from the manifest; got: {:?}",
            result.files
        );
        assert!(
            staging.path().join("keep.txt").exists()
                && result.files.iter().any(|f| f.path == Path::new("keep.txt")),
            "the control leaf with a clean dest must still be staged and recorded; got: {:?}",
            result.files
        );
    }

    #[test]
    fn export_prunes_a_top_level_dot_git_dest_at_write() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_named(
            &fixture,
            staging.path(),
            &dot_git_dest_leaves(".git/config"),
            &ExportPolicy::default(),
        )
        .expect("export succeeds; the top-level .git-dest leaf is pruned");

        assert!(
            !staging.path().join(".git/config").exists(),
            "a `.git` component at the TOP of the dest must be pruned at write"
        );
        assert!(
            !result
                .files
                .iter()
                .any(|f| f.path == Path::new(".git/config")),
            "the pruned top-level `.git`-dest leaf must be absent from the manifest; got: {:?}",
            result.files
        );
    }

    #[test]
    fn export_writes_a_dot_git_dest_when_policy_opts_in() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let policy = ExportPolicy {
            vcs_opt_in: true,
            ..ExportPolicy::default()
        };
        let result = export_named(
            &fixture,
            staging.path(),
            &dot_git_dest_leaves("nested/.git/config"),
            &policy,
        )
        .expect("export succeeds with the .git opt-in");

        assert!(
            staging.path().join("nested/.git/config").exists(),
            "with the `.git` opt-in the write-time prune must be suppressed and the leaf staged"
        );
        assert!(
            result
                .files
                .iter()
                .any(|f| f.path == Path::new("nested/.git/config")),
            "an opted-in `.git`-dest leaf must appear in the manifest; got: {:?}",
            result.files
        );
    }

    #[test]
    fn export_writes_a_dot_gitignore_basename_dest_without_opt_in() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_named(
            &fixture,
            staging.path(),
            &dot_git_dest_leaves("nested/.gitignore"),
            &ExportPolicy::default(),
        )
        .expect("export succeeds; a `.gitignore` basename is not a `.git` component");

        assert!(
            staging.path().join("nested/.gitignore").exists(),
            "a `.gitignore` basename is NOT a `.git` path component and must be staged even without \
             the opt-in"
        );
        assert!(
            result
                .files
                .iter()
                .any(|f| f.path == Path::new("nested/.gitignore")),
            "the `.gitignore` leaf must be recorded in the manifest; got: {:?}",
            result.files
        );
    }

    #[test]
    fn export_result_lists_exported_files() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_editor(&fixture, staging.path(), &ExportPolicy::default())
            .expect("export succeeds");

        let mut listed: Vec<String> = result
            .files
            .iter()
            .map(|f| f.path.to_string_lossy().replace('\\', "/"))
            .collect();
        listed.sort();

        assert!(
            listed.contains(&"init.lua".to_string()),
            "files must list init.lua, got {listed:?}"
        );
        assert!(
            listed.contains(&"lua/opts.lua".to_string()),
            "files must list nested lua/opts.lua, got {listed:?}"
        );
        assert!(
            listed.contains(&"bin/run.sh".to_string()),
            "files must list bin/run.sh, got {listed:?}"
        );
    }

    #[test]
    fn export_sets_mtime_to_commit_time() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let result = export_editor(&fixture, staging.path(), &ExportPolicy::default())
            .expect("export succeeds");

        assert!(!result.files.is_empty(), "expected exported files");
        for file in &result.files {
            let on_disk = staging.path().join(&file.path);
            assert_eq!(
                mtime_secs(&on_disk),
                EXPORT_COMMIT_TIME,
                "exported {} mtime must equal commit_time",
                file.path.display()
            );
            assert_eq!(
                file.mtime, EXPORT_COMMIT_TIME,
                "ManifestFile.mtime must equal commit_time"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn export_preserves_executable_bit_by_default() {
        use std::os::unix::fs::PermissionsExt;

        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        export_editor(&fixture, staging.path(), &ExportPolicy::default()).expect("export succeeds");

        let mode = std::fs::metadata(staging.path().join("bin/run.sh"))
            .expect("run.sh exists")
            .permissions()
            .mode();
        assert!(
            mode & 0o111 != 0,
            "preserve_executable default true: run.sh must have an exec bit, mode {mode:o}"
        );
    }

    // ---- in-artifact symlink policy ----

    #[test]
    fn export_rejects_symlink_when_policy_disallows() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let policy = ExportPolicy {
            allow_symlinks: false,
            ..ExportPolicy::default()
        };
        let err = export_named(&fixture, staging.path(), &linky_leaves(), &policy)
            .expect_err("linky/link is a symlink; allow_symlinks=false must error");

        assert!(
            matches!(err, SourceError::SymlinkNotAllowed { .. }),
            "must be a real symlink-policy rejection, not the unimplemented stub: {err}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains(LINK_NAME),
            "rejection must name the offending symlink {LINK_NAME}, got: {msg}"
        );
        assert!(
            msg.contains("symlink"),
            "rejection must identify a symlink-policy rejection, got: {msg}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn export_materializes_symlink_when_allowed() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let policy = ExportPolicy {
            allow_symlinks: true,
            ..ExportPolicy::default()
        };
        export_named(&fixture, staging.path(), &linky_leaves(), &policy)
            .expect("export with symlinks allowed");

        let link = staging.path().join(LINK_NAME);
        let meta = std::fs::symlink_metadata(&link).expect("link entry exists");
        assert!(
            meta.file_type().is_symlink(),
            "allowed symlink must be materialized as a symlink, not dereferenced"
        );
        assert_eq!(
            std::fs::read_link(&link).expect("readlink"),
            Path::new(LINK_TARGET),
            "symlink target must be preserved verbatim"
        );
    }

    #[test]
    fn export_rejects_symlink_colliding_with_rendered_deployed_name() {
        let fixture = build_symlink_template_collision_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let policy = ExportPolicy {
            allow_symlinks: true,
            ..ExportPolicy::default()
        };
        let leaves = vec![
            ExportLeaf {
                source: PathBuf::from("art/link.tmpl"),
                dest: PathBuf::from(TemplateOptIn::SuffixOnly.deployed_name("link.tmpl")),
            },
            ExportLeaf {
                source: PathBuf::from("art/link"),
                dest: PathBuf::from("link"),
            },
        ];
        let err = export_named(&fixture, staging.path(), &leaves, &policy)
            .expect_err("symlink `link` and rendered `link.tmpl` both deploy to `link`");
        assert!(
            matches!(err, SourceError::DeployedNameCollision { .. }),
            "a symlink and a blob mapping to the same deployed name must collide, not last-writer-wins, got: {err:?}"
        );
    }

    #[test]
    fn export_rejects_directory_colliding_with_rendered_deployed_name() {
        let fixture = build_dir_template_collision_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let leaves = vec![
            ExportLeaf {
                source: PathBuf::from("art/config.tmpl"),
                dest: PathBuf::from(TemplateOptIn::SuffixOnly.deployed_name("config.tmpl")),
            },
            ExportLeaf {
                source: PathBuf::from("art/config/inner.txt"),
                dest: PathBuf::from("config"),
            },
        ];
        let err = export_named(&fixture, staging.path(), &leaves, &ExportPolicy::default())
            .expect_err("directory `config` and rendered `config.tmpl` both deploy to `config`");
        assert!(
            matches!(err, SourceError::DeployedNameCollision { .. }),
            "a directory and a blob mapping to the same deployed name must collide, not surface a raw fs error, got: {err:?}"
        );
    }

    #[test]
    fn export_aborts_a_runaway_template_via_fuel_instead_of_hanging() {
        let runaway = b"{% for i in range(100000000) %}x{% endfor %}\n";
        let fixture = build_collision_fixture(&[("loop.txt.tmpl", runaway)]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let leaves = vec![ExportLeaf {
            source: PathBuf::from("art/loop.txt.tmpl"),
            dest: PathBuf::from(TemplateOptIn::SuffixOnly.deployed_name("loop.txt.tmpl")),
        }];
        let err = export_named(&fixture, staging.path(), &leaves, &ExportPolicy::default())
            .expect_err("a template that exhausts the fuel budget must surface an error");
        assert!(
            matches!(err, SourceError::Render { .. }),
            "exceeding the minijinja fuel cap must abort the artifact as a Render error, not panic or hang, got: {err:?}"
        );
    }

    // ---- ExportResult.vars_digest (TPH-010) ----

    /// Every leaf under the `art` subtree, mapped to its suffix-stripped dir-relative dest.
    fn art_leaves(fixture: &ExportFixture) -> Vec<ExportLeaf> {
        fixture
            .backend
            .list_source_leaves(
                &sn("src"),
                &fixture.url,
                &fixture.commit,
                Some(Path::new("art")),
            )
            .expect("list art leaves")
            .into_iter()
            .map(|rel| ExportLeaf {
                source: PathBuf::from("art").join(&rel),
                dest: PathBuf::from(TemplateOptIn::SuffixOnly.deployed_name(&rel)),
            })
            .collect()
    }

    fn export_art_with_vars(
        fixture: &ExportFixture,
        staging: &Path,
        vars: &BTreeMap<String, String>,
    ) -> ExportResult {
        let source = sn("src");
        let leaves = art_leaves(fixture);
        let req = ExportRequest {
            source: &source,
            url: &fixture.url,
            commit: &fixture.commit,
            root: None,
            policy: &ExportPolicy::default(),
            staging_dir: staging,
            commit_time: EXPORT_COMMIT_TIME,
            template_opt_in: &TemplateOptIn::SuffixOnly,
            vars,
            leaves: &leaves,
        };
        fixture.backend.export_artifact(&req).expect("export art")
    }

    #[test]
    fn export_vars_digest_is_none_when_no_template_rendered() {
        let fixture = build_collision_fixture(&[("plain.txt", b"static body\n")]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let mut vars = BTreeMap::new();
        vars.insert("name".to_owned(), "ada".to_owned());

        let result = export_art_with_vars(&fixture, staging.path(), &vars);

        assert_eq!(
            result.vars_digest, None,
            "a feature-free artifact (no `.tmpl`, no template rendered) must report vars_digest = \
             None even when vars are present, so a vars change leaves it untouched (INV-8), got {:?}",
            result.vars_digest
        );
    }

    #[test]
    fn export_vars_digest_is_some_when_a_template_rendered() {
        let fixture = build_collision_fixture(&[("greeting.txt.tmpl", b"hello {{ name }}\n")]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let mut vars = BTreeMap::new();
        vars.insert("name".to_owned(), "ada".to_owned());

        let result = export_art_with_vars(&fixture, staging.path(), &vars);

        assert!(
            result.vars_digest.is_some(),
            "an artifact that rendered at least one template must report vars_digest = Some(..), \
             got {:?}",
            result.vars_digest
        );
    }

    #[test]
    fn export_vars_digest_changes_when_a_var_value_changes() {
        let fixture = build_collision_fixture(&[("greeting.txt.tmpl", b"hello {{ name }}\n")]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let staging_a = TempDir::new().expect("staging a");
        let mut vars_a = BTreeMap::new();
        vars_a.insert("name".to_owned(), "ada".to_owned());
        let digest_a = export_art_with_vars(&fixture, staging_a.path(), &vars_a).vars_digest;

        let staging_b = TempDir::new().expect("staging b");
        let mut vars_b = BTreeMap::new();
        vars_b.insert("name".to_owned(), "grace".to_owned());
        let digest_b = export_art_with_vars(&fixture, staging_b.path(), &vars_b).vars_digest;

        assert!(
            digest_a.is_some() && digest_b.is_some(),
            "both renders must produce a vars_digest"
        );
        assert_ne!(
            digest_a, digest_b,
            "changing a vars value must change the vars_digest so every templated artifact is \
             marked Outdated and re-renders, got {digest_a:?} vs {digest_b:?}"
        );
    }

    #[test]
    fn export_vars_digest_hashes_full_vars_not_only_consumed_keys() {
        let fixture = build_collision_fixture(&[("greeting.txt.tmpl", b"hello {{ name }}\n")]);
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let staging_a = TempDir::new().expect("staging a");
        let mut vars_a = BTreeMap::new();
        vars_a.insert("name".to_owned(), "ada".to_owned());
        let digest_a = export_art_with_vars(&fixture, staging_a.path(), &vars_a).vars_digest;

        let staging_b = TempDir::new().expect("staging b");
        let mut vars_b = BTreeMap::new();
        vars_b.insert("name".to_owned(), "ada".to_owned());
        vars_b.insert("unused".to_owned(), "x".to_owned());
        let digest_b = export_art_with_vars(&fixture, staging_b.path(), &vars_b).vars_digest;

        assert_ne!(
            digest_a, digest_b,
            "the digest scope is the FULL effective vars map, not consumed-keys-only: adding a var \
             the template never references must still change vars_digest, got {digest_a:?} vs {digest_b:?}"
        );
    }

    // ---- mapped export (leaf aliasing, T2b) ----

    const MAP_TOP_CONTENT: &[u8] = b"# top-level agents\n";
    const MAP_NESTED_CONTENT: &[u8] = b"# nested agents\n";
    const MAP_TOOL_CONTENT: &[u8] = b"#!/bin/sh\necho tool\n";

    /// Top-level and nested leaves plus an executable, all committed at root.
    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_map_fixture() -> ExportFixture {
        let src = TempDir::new().unwrap();
        let src_path = src.path();

        init_export_repo(src_path);

        std::fs::write(src_path.join("AGENTS.md"), MAP_TOP_CONTENT).unwrap();
        std::fs::create_dir_all(src_path.join("nested")).unwrap();
        std::fs::write(src_path.join("nested/AGENTS.md"), MAP_NESTED_CONTENT).unwrap();
        std::fs::write(src_path.join("tool.sh"), MAP_TOOL_CONTENT).unwrap();

        run_git(src_path, &["add", "-A"]);
        run_git(src_path, &["update-index", "--chmod=+x", "tool.sh"]);

        let commit = commit_export_repo(src_path);

        let tool_mode =
            String::from_utf8(run_git(src_path, &["ls-files", "-s", "tool.sh"]).stdout).unwrap();
        assert!(
            tool_mode.starts_with("100755"),
            "tool.sh must be committed executable (100755), got: {tool_mode}"
        );

        export_fixture_from(src, commit)
    }

    fn export_mapped(
        fixture: &ExportFixture,
        staging: &Path,
        map: &[(&str, &str)],
    ) -> Result<ExportResult> {
        let source = sn("src");
        let leaves: Vec<ExportLeaf> = map
            .iter()
            .map(|(key, dest)| ExportLeaf {
                source: PathBuf::from(key),
                dest: PathBuf::from(dest),
            })
            .collect();
        let req = ExportRequest {
            source: &source,
            url: &fixture.url,
            commit: &fixture.commit,
            root: None,
            policy: &ExportPolicy::default(),
            staging_dir: staging,
            commit_time: EXPORT_COMMIT_TIME,
            template_opt_in: &TemplateOptIn::SuffixOnly,
            vars: &BTreeMap::new(),
            leaves: &leaves,
        };
        fixture.backend.export_artifact(&req)
    }

    #[test]
    fn mapped_export_renames_top_level_blob() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("AGENTS.md", "CLAUDE.md")];
        let result = export_mapped(&fixture, staging.path(), map).expect("mapped export succeeds");

        assert_eq!(
            std::fs::read(staging.path().join("CLAUDE.md")).expect("CLAUDE.md staged"),
            MAP_TOP_CONTENT,
            "the source bytes of AGENTS.md must land at the renamed dest CLAUDE.md"
        );
        assert!(
            !staging.path().join("AGENTS.md").exists(),
            "the source name must not be staged; only the dest name"
        );
        let listed: Vec<String> = result
            .files
            .iter()
            .map(|f| f.path.to_string_lossy().replace('\\', "/"))
            .collect();
        assert_eq!(
            listed,
            vec!["CLAUDE.md".to_string()],
            "files must contain exactly the dest path, not the source key, got {listed:?}"
        );
    }

    #[test]
    fn mapped_export_flattens_nested_key_to_dest() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("nested/AGENTS.md", "codex.md")];
        let result = export_mapped(&fixture, staging.path(), map).expect("mapped export succeeds");

        assert_eq!(
            std::fs::read(staging.path().join("codex.md")).expect("codex.md staged"),
            MAP_NESTED_CONTENT,
            "a nested source key must stage flat at the single-component dest"
        );
        assert!(
            !staging.path().join("nested").exists(),
            "the nested source path must not be reproduced under staging"
        );
        let listed: Vec<String> = result
            .files
            .iter()
            .map(|f| f.path.to_string_lossy().replace('\\', "/"))
            .collect();
        assert_eq!(
            listed,
            vec!["codex.md".to_string()],
            "files must list the flat dest, not the nested key, got {listed:?}"
        );
    }

    #[test]
    fn mapped_export_stages_all_entries_of_a_multi_key_map() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("AGENTS.md", "CLAUDE.md"), ("nested/AGENTS.md", "codex.md")];
        let result = export_mapped(&fixture, staging.path(), map).expect("mapped export succeeds");

        assert_eq!(
            std::fs::read(staging.path().join("CLAUDE.md")).expect("CLAUDE.md staged"),
            MAP_TOP_CONTENT,
            "the top-level key's bytes must land at its dest"
        );
        assert_eq!(
            std::fs::read(staging.path().join("codex.md")).expect("codex.md staged"),
            MAP_NESTED_CONTENT,
            "the nested key's bytes must land at its dest"
        );

        let mut listed: Vec<String> = result
            .files
            .iter()
            .map(|f| f.path.to_string_lossy().replace('\\', "/"))
            .collect();
        listed.sort();
        assert_eq!(
            listed,
            vec!["CLAUDE.md".to_string(), "codex.md".to_string()],
            "files must contain exactly both dests, no source keys and no extras, got {listed:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn mapped_export_preserves_executable_bit() {
        use std::os::unix::fs::PermissionsExt;

        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("tool.sh", "run")];
        export_mapped(&fixture, staging.path(), map).expect("mapped export succeeds");

        let mode = std::fs::metadata(staging.path().join("run"))
            .expect("run staged")
            .permissions()
            .mode();
        assert!(
            mode & 0o111 != 0,
            "executable source leaf must keep an exec bit through the rename, mode {mode:o}"
        );
    }

    #[test]
    fn mapped_export_errors_when_key_is_a_directory() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("nested", "x.md")];
        let err = export_mapped(&fixture, staging.path(), map)
            .expect_err("a key resolving to a directory must error; only regular files map");
        assert!(
            !staging.path().join("x.md").exists(),
            "no dest must be staged when a key resolves to a directory"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("nested"),
            "the error must name the offending key so an unrelated failure can't pass, got {msg:?}"
        );
    }

    #[test]
    fn mapped_export_errors_when_key_is_missing() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("does/not/exist.md", "x.md")];
        let err = export_mapped(&fixture, staging.path(), map)
            .expect_err("a key resolving to nothing must error");
        assert!(
            !staging.path().join("x.md").exists(),
            "no dest must be staged when a key resolves to nothing"
        );
        assert!(
            matches!(err, SourceError::MappedKeyNotFound { .. }),
            "a missing key must be MappedKeyNotFound, not the not-a-leaf variant, got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("exist.md"),
            "the error must name the missing key so an unrelated failure can't pass, got {msg:?}"
        );
    }

    #[test]
    fn mapped_export_errors_when_two_keys_share_a_dest() {
        let fixture = build_map_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");
        let staging = TempDir::new().expect("staging dir");

        let map = &[("AGENTS.md", "x.md"), ("nested/AGENTS.md", "x.md")];
        let err = export_mapped(&fixture, staging.path(), map)
            .expect_err("two keys mapping to one dest must collide");
        assert!(
            matches!(err, SourceError::DeployedNameCollision { .. }),
            "mapped collisions must route through register_deployed_name, got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("x.md"),
            "the collision must name the shared dest, got {msg:?}"
        );
    }

    // ---- compute_digest ----

    #[test]
    fn compute_digest_is_blake3_prefixed_and_stable() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let first = fixture
            .backend
            .compute_digest(&sn("src"), &fixture.url, &fixture.commit, None, &[], &[])
            .expect("digest computes");
        let second = fixture
            .backend
            .compute_digest(&sn("src"), &fixture.url, &fixture.commit, None, &[], &[])
            .expect("digest computes again");

        assert!(
            first.starts_with("blake3:"),
            "digest must carry the blake3: prefix, got {first}"
        );
        assert_eq!(
            first, second,
            "same (commit, root, matcher) must yield an identical digest"
        );
    }

    #[test]
    fn compute_digest_frames_entries_so_content_cannot_bleed_into_next_path() {
        let mut bled_content = b"X".to_vec();
        bled_content.extend_from_slice(b"b");
        bled_content.extend_from_slice(FILE_TAG);
        bled_content.extend_from_slice(b"Y");

        let one_file = build_collision_fixture(&[("a", &bled_content)]);
        let two_files = build_collision_fixture(&[("a", b"X"), ("b", b"Y")]);
        one_file
            .backend
            .fetch(&sn("src"), &one_file.url)
            .expect("fetch one-file tree");
        two_files
            .backend
            .fetch(&sn("src"), &two_files.url)
            .expect("fetch two-file tree");

        assert_ne!(
            digest_of_art(&one_file),
            digest_of_art(&two_files),
            "distinct layouts whose naive path||tag||content streams are byte-identical \
             must hash differently; entries need length framing"
        );
    }

    // ---- import_tree (HTP-004): deterministic synthetic-commit import ----

    use crate::archive::{EntryKind as BlobKind, ExtractedEntry};

    fn entry(path: &str, kind: BlobKind, data: &[u8]) -> ExtractedEntry {
        ExtractedEntry {
            path: PathBuf::from(path),
            kind,
            data: data.to_vec(),
        }
    }

    /// Opens the bare mirror that `import_tree` wrote for `url` under `git_dir`.
    fn open_imported_mirror(git_dir: &Path, url: &str) -> gix::Repository {
        let key = MirrorKey::from_url(&NormalizedUrl::parse(url));
        let mirror = git_dir.join(format!("{}.git", key.as_str()));
        gix::open(&mirror).expect("imported mirror opens as a git repo")
    }

    const IMPORT_URL: &str = "https://example.com/owner/repo";

    #[test]
    fn deterministic_same_entries_same_commit_id() {
        let dir_a = TempDir::new().expect("git_dir a");
        let dir_b = TempDir::new().expect("git_dir b");
        let entries = || {
            vec![
                entry("a.txt", BlobKind::Blob, b"alpha"),
                entry("dir/b.txt", BlobKind::Blob, b"bravo"),
            ]
        };

        let first =
            import_tree(dir_a.path(), IMPORT_URL, &entries()).expect("import into fresh git_dir a");
        let second = import_tree(dir_b.path(), IMPORT_URL, &entries())
            .expect("import the same entries into fresh git_dir b");

        assert_eq!(
            first, second,
            "identical entries must produce an identical content-addressed commit id, \
             independent of which git_dir they land in"
        );
    }

    #[test]
    fn input_order_independent_commit_id() {
        let dir_a = TempDir::new().expect("git_dir a");
        let dir_b = TempDir::new().expect("git_dir b");

        let forward = vec![
            entry("a.txt", BlobKind::Blob, b"alpha"),
            entry("m.txt", BlobKind::Blob, b"mike"),
            entry("z.txt", BlobKind::Blob, b"zulu"),
            entry("dir/b.txt", BlobKind::Blob, b"bravo"),
        ];
        let reversed = vec![
            entry("dir/b.txt", BlobKind::Blob, b"bravo"),
            entry("z.txt", BlobKind::Blob, b"zulu"),
            entry("m.txt", BlobKind::Blob, b"mike"),
            entry("a.txt", BlobKind::Blob, b"alpha"),
        ];

        let forward_id =
            import_tree(dir_a.path(), IMPORT_URL, &forward).expect("import forward order");
        let reversed_id =
            import_tree(dir_b.path(), IMPORT_URL, &reversed).expect("import reversed order");

        assert_eq!(
            forward_id, reversed_id,
            "input order must not affect the commit id: the impl must sort tree entries \
             into git order before writing"
        );
    }

    #[test]
    fn different_content_different_commit_id() {
        let dir_a = TempDir::new().expect("git_dir a");
        let dir_b = TempDir::new().expect("git_dir b");

        let base = import_tree(
            dir_a.path(),
            IMPORT_URL,
            &[entry("a.txt", BlobKind::Blob, b"alpha")],
        )
        .expect("import base content");
        let changed = import_tree(
            dir_b.path(),
            IMPORT_URL,
            &[entry("a.txt", BlobKind::Blob, b"ALPHA")],
        )
        .expect("import changed content");

        assert_ne!(
            base, changed,
            "changing a file's bytes must change the content-addressed commit id"
        );
    }

    #[test]
    fn failed_fresh_import_leaves_no_mirror_at_canonical_path() {
        let dir = TempDir::new().expect("git_dir");
        let key = MirrorKey::from_url(&NormalizedUrl::parse(IMPORT_URL));
        let mirror = dir.path().join(format!("{}.git", key.as_str()));
        let duplicate = vec![
            entry("dup.txt", BlobKind::Blob, b"one"),
            entry("dup.txt", BlobKind::Blob, b"two"),
        ];

        let result = import_tree(dir.path(), IMPORT_URL, &duplicate);

        assert!(result.is_err(), "a duplicate archive entry path must error");
        assert!(
            !mirror.exists(),
            "a failed fresh import must not leave a partial mirror at the canonical path"
        );
    }

    #[test]
    fn commit_has_fixed_identity_time_and_no_parents() {
        let dir_a = TempDir::new().expect("git_dir a");
        let dir_b = TempDir::new().expect("git_dir b");
        let make = || vec![entry("a.txt", BlobKind::Blob, b"alpha")];

        let id_a = import_tree(dir_a.path(), IMPORT_URL, &make()).expect("import a");
        let id_b = import_tree(dir_b.path(), IMPORT_URL, &make()).expect("import b");

        let repo = open_imported_mirror(dir_a.path(), IMPORT_URL);
        let oid = gix::ObjectId::from_hex(id_a.as_bytes()).expect("returned hex is a valid oid");
        let commit = repo
            .find_commit(oid)
            .expect("returned commit id exists in the mirror");

        let author = commit.author().expect("commit has an author");
        let committer = commit.committer().expect("commit has a committer");

        assert_eq!(
            author.time().expect("author time decodes").seconds,
            1,
            "author time must be the fixed epoch+1 second (NOT epoch 0)"
        );
        assert_eq!(
            committer.time().expect("committer time decodes").seconds,
            1,
            "committer time must be the fixed epoch+1 second (NOT epoch 0)"
        );

        assert_eq!(
            commit.parent_ids().count(),
            0,
            "a synthetic import commit must have no parents"
        );

        let author_a = author.name.to_string();
        let email_a = author.email.to_string();

        let repo_b = open_imported_mirror(dir_b.path(), IMPORT_URL);
        let oid_b = gix::ObjectId::from_hex(id_b.as_bytes()).expect("id_b valid oid");
        let commit_b = repo_b.find_commit(oid_b).expect("commit b exists");
        let author_b = commit_b.author().expect("author b");

        assert_eq!(
            author_a,
            author_b.name.to_string(),
            "author name must be a fixed constant, stable across imports"
        );
        assert_eq!(
            email_a,
            author_b.email.to_string(),
            "author email must be a fixed constant, stable across imports"
        );
        assert_eq!(
            id_a, id_b,
            "fixed identity+time+message imply identical commit ids for identical trees"
        );
    }

    #[test]
    fn ref_phora_points_at_commit() {
        let dir = TempDir::new().expect("git_dir");
        let commit_id = import_tree(
            dir.path(),
            IMPORT_URL,
            &[entry("a.txt", BlobKind::Blob, b"alpha")],
        )
        .expect("import");

        let repo = open_imported_mirror(dir.path(), IMPORT_URL);
        let resolved = repo
            .find_reference("refs/heads/phora")
            .expect("refs/heads/phora exists after import")
            .peel_to_commit()
            .expect("phora ref peels to a commit")
            .id()
            .to_hex()
            .to_string();

        assert_eq!(
            resolved, commit_id,
            "refs/heads/phora must resolve to the returned commit id"
        );
    }

    #[test]
    fn nested_tree_roundtrips_paths_kinds_data() {
        let dir = TempDir::new().expect("git_dir");
        let commit_id = import_tree(
            dir.path(),
            IMPORT_URL,
            &[
                entry("a.txt", BlobKind::Blob, b"A"),
                entry("dir/b.sh", BlobKind::BlobExecutable, b"B"),
                entry("dir/link", BlobKind::Link, b"target/x"),
            ],
        )
        .expect("import nested tree");

        let repo = open_imported_mirror(dir.path(), IMPORT_URL);
        let oid = gix::ObjectId::from_hex(commit_id.as_bytes()).expect("valid oid");
        let tree = repo
            .find_commit(oid)
            .expect("commit exists")
            .tree()
            .expect("commit has a tree");

        let lookup = |path: &str| {
            tree.lookup_entry_by_path(Path::new(path))
                .expect("lookup does not error")
                .unwrap_or_else(|| panic!("entry {path} must exist in the imported tree"))
        };

        let blob_data = |entry: &gix::object::tree::Entry<'_>| {
            repo.find_blob(entry.object_id())
                .expect("entry blob exists")
                .data
                .clone()
        };

        let a = lookup("a.txt");
        assert_eq!(a.mode().kind(), EntryKind::Blob, "a.txt is a plain blob");
        assert_eq!(blob_data(&a), b"A", "a.txt content roundtrips");

        let b = lookup("dir/b.sh");
        assert_eq!(
            b.mode().kind(),
            EntryKind::BlobExecutable,
            "dir/b.sh must be an executable blob (mode 100755)"
        );
        assert_eq!(blob_data(&b), b"B", "dir/b.sh content roundtrips");

        let link = lookup("dir/link");
        assert_eq!(
            link.mode().kind(),
            EntryKind::Link,
            "dir/link must be a symlink (mode 120000)"
        );
        assert_eq!(
            blob_data(&link),
            b"target/x",
            "symlink blob content must be the target bytes"
        );

        let dir_entry = lookup("dir");
        assert_eq!(
            dir_entry.mode().kind(),
            EntryKind::Tree,
            "the nested dir must be a real subtree"
        );
    }

    #[test]
    fn git_fsck_accepts_synthetic_commit() {
        let dir = TempDir::new().expect("git_dir");
        import_tree(
            dir.path(),
            IMPORT_URL,
            &[
                entry("a.txt", BlobKind::Blob, b"A"),
                entry("dir/b.sh", BlobKind::BlobExecutable, b"B"),
                entry("dir/link", BlobKind::Link, b"target/x"),
                entry("z.txt", BlobKind::Blob, b"Z"),
            ],
        )
        .expect("import");

        let key = MirrorKey::from_url(&NormalizedUrl::parse(IMPORT_URL));
        let mirror = dir.path().join(format!("{}.git", key.as_str()));

        let out = {
            let _serial = crate::store::guard_git_fork();
            Command::new("git")
                .args([
                    "--git-dir",
                    mirror.to_str().expect("mirror path is utf8"),
                    "fsck",
                    "--strict",
                ])
                .output()
                .expect("git fsck runs")
        };

        assert!(
            out.status.success(),
            "git fsck --strict must accept the synthetic objects; stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        let reported_problem = stderr.lines().any(|line| {
            let lower = line.trim().to_lowercase();
            lower.starts_with("error:") || lower.starts_with("fatal:")
        });
        assert!(
            !reported_problem,
            "git fsck must emit no error:/fatal: lines (catches unsorted/malformed trees): {stderr}"
        );
    }

    #[test]
    fn empty_entries_produce_stable_empty_tree_commit() {
        let dir_a = TempDir::new().expect("git_dir a");
        let dir_b = TempDir::new().expect("git_dir b");

        let first = import_tree(dir_a.path(), IMPORT_URL, &[])
            .expect("importing zero entries yields a commit over an empty tree");
        let second =
            import_tree(dir_b.path(), IMPORT_URL, &[]).expect("re-importing zero entries succeeds");

        assert_eq!(
            first, second,
            "an empty entry list must yield a stable empty-tree commit id"
        );
    }

    #[test]
    fn reimport_changed_content_advances_ref() {
        let dir = TempDir::new().expect("git_dir");

        let first = import_tree(
            dir.path(),
            IMPORT_URL,
            &[entry("a.txt", BlobKind::Blob, b"alpha")],
        )
        .expect("first import into a fresh mirror");

        let second = import_tree(
            dir.path(),
            IMPORT_URL,
            &[entry("a.txt", BlobKind::Blob, b"BRAVO")],
        )
        .expect("re-import of changed content into the SAME mirror must succeed");

        assert_ne!(
            first, second,
            "changed content must yield a different commit id on re-import"
        );

        let repo = open_imported_mirror(dir.path(), IMPORT_URL);
        let resolved = repo
            .find_reference("refs/heads/phora")
            .expect("phora ref exists after re-import")
            .peel_to_commit()
            .expect("phora ref peels to a commit")
            .id()
            .to_hex()
            .to_string();

        assert_eq!(
            resolved, second,
            "refs/heads/phora must advance to the second (changed) commit"
        );
    }

    #[test]
    fn reimport_identical_content_is_stable() {
        let dir = TempDir::new().expect("git_dir");
        let make = || vec![entry("a.txt", BlobKind::Blob, b"alpha")];

        let first = import_tree(dir.path(), IMPORT_URL, &make()).expect("first import");
        let second = import_tree(dir.path(), IMPORT_URL, &make())
            .expect("re-import of identical content into the SAME mirror is idempotent");

        assert_eq!(
            first, second,
            "identical content re-imported into the same mirror must be stable"
        );

        let repo = open_imported_mirror(dir.path(), IMPORT_URL);
        let resolved = repo
            .find_reference("refs/heads/phora")
            .expect("phora ref exists")
            .peel_to_commit()
            .expect("phora ref peels to a commit")
            .id()
            .to_hex()
            .to_string();

        assert_eq!(resolved, first, "ref still resolves to the stable commit");
    }

    #[test]
    fn import_rejects_duplicate_entry_paths() {
        let dir = TempDir::new().expect("git_dir");

        let result = import_tree(
            dir.path(),
            IMPORT_URL,
            &[
                entry("a.txt", BlobKind::Blob, b"first"),
                entry("a.txt", BlobKind::Blob, b"second"),
            ],
        );

        assert!(
            matches!(result, Err(SourceError::Source(_))),
            "two entries with the same path must error, not silently overwrite"
        );
    }

    #[test]
    fn import_rejects_file_dir_collision_either_order() {
        let dir_after_file = import_tree(
            TempDir::new().expect("git_dir").path(),
            IMPORT_URL,
            &[
                entry("dir", BlobKind::Blob, b"file"),
                entry("dir/x", BlobKind::Blob, b"child"),
            ],
        );
        assert!(
            matches!(dir_after_file, Err(SourceError::Source(_))),
            "a file then a directory at the same name must error"
        );

        let file_after_dir = import_tree(
            TempDir::new().expect("git_dir").path(),
            IMPORT_URL,
            &[
                entry("dir/x", BlobKind::Blob, b"child"),
                entry("dir", BlobKind::Blob, b"file"),
            ],
        );
        assert!(
            matches!(file_after_dir, Err(SourceError::Source(_))),
            "a directory then a file at the same name must error"
        );
    }

    #[test]
    fn compute_digest_reflects_matched_tree_not_matcher_config() {
        let fixture = build_export_fixture();
        fixture
            .backend
            .fetch(&sn("src"), &fixture.url)
            .expect("fetch");

        let digest = |exclude: &[String]| {
            fixture
                .backend
                .compute_digest(
                    &sn("src"),
                    &fixture.url,
                    &fixture.commit,
                    None,
                    &[],
                    exclude,
                )
                .expect("digest computes")
        };

        let no_exclude = digest(&[]);
        let exclude_nothing = digest(&["**/*.nonexistent".to_owned()]);
        let exclude_lua = digest(&["**/*.lua".to_owned()]);

        assert_eq!(
            no_exclude, exclude_nothing,
            "an exclude that matches no entry must not change the digest; \
             digest reflects the matched tree, not the matcher config"
        );
        assert_ne!(
            no_exclude, exclude_lua,
            "excluding entries that exist must change the digest"
        );
    }

    // ---- HTP-005 B/C: HttpBackend (url source) at the trait level ----

    mod http_backend {
        use std::collections::BTreeMap;
        use std::io::{Read, Write};
        use std::net::{TcpListener, TcpStream};
        use std::path::Path;
        use std::time::Duration;

        use gix::object::tree::EntryKind;
        use tempfile::TempDir;

        use crate::config::Refspec;
        use crate::kernel::Digest;
        use crate::source::{
            ExportLeaf, ExportPolicy, ExportRequest, HttpBackend, SourceBackend, SourceError,
            mirror_path,
        };

        use super::sn;

        const HELLO_BODY: &[u8] = b"hi";
        const RUN_BODY: &[u8] = b"#!/bin/sh\n";

        /// One-shot 127.0.0.1 server returning the canned bytes; accept thread is
        /// detached so a non-connecting fetch never hangs the test on join.
        struct TarServer {
            port: u16,
        }

        impl TarServer {
            fn spawn(body: Vec<u8>) -> Self {
                let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
                let port = listener.local_addr().expect("local addr").port();
                std::thread::spawn(move || {
                    if let Ok((stream, _)) = listener.accept() {
                        Self::serve(stream, &body);
                    }
                });
                Self { port }
            }

            fn serve(mut stream: TcpStream, body: &[u8]) {
                let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
                let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
                let mut buf = [0u8; 1024];
                let _ = stream.read(&mut buf);
                let header = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                let _ = stream.write_all(header.as_bytes());
                let _ = stream.write_all(body);
                let _ = stream.flush();
            }

            fn url(&self) -> String {
                format!("http://127.0.0.1:{}/pkg-1.0.tar.gz", self.port)
            }
        }

        /// A `.tar.gz` of `pkg-1.0/hello.txt`="hi" and `pkg-1.0/bin/run.sh`(0o755)="#!/bin/sh\n".
        /// After auto-strip the entries are `hello.txt` and `bin/run.sh`.
        fn build_pkg_tar_gz() -> Vec<u8> {
            fn append(builder: &mut tar::Builder<Vec<u8>>, path: &str, data: &[u8], mode: u32) {
                let mut header = tar::Header::new_gnu();
                header.set_size(data.len() as u64);
                header.set_mode(mode);
                header.set_entry_type(tar::EntryType::Regular);
                header.set_cksum();
                builder
                    .append_data(&mut header, path, data)
                    .expect("append tar entry");
            }

            let mut builder = tar::Builder::new(Vec::new());
            append(&mut builder, "pkg-1.0/hello.txt", HELLO_BODY, 0o644);
            append(&mut builder, "pkg-1.0/bin/run.sh", RUN_BODY, 0o755);
            let tar_bytes = builder.into_inner().expect("finish tar");

            let mut encoder =
                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
            encoder.write_all(&tar_bytes).expect("gzip tar bytes");
            encoder.finish().expect("finish gzip")
        }

        #[test]
        fn fetch_then_resolve_ignores_refspec_and_reads_phora_head() {
            let server = TarServer::spawn(build_pkg_tar_gz());
            let url = server.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

            backend
                .fetch(&sn("pkg"), &url)
                .expect("fetch downloads, extracts, and imports a tree");

            let resolved = backend
                .resolve(&sn("pkg"), &url, &Refspec::Branch("main".into()))
                .expect("resolve must read refs/heads/phora, ignoring the bogus Branch(main)");

            assert_eq!(resolved.len(), 40, "resolve returns a 40-hex commit id");
            assert!(
                resolved.chars().all(|c| c.is_ascii_hexdigit()),
                "resolve returns a hex commit id, got: {resolved}"
            );

            let none_resolved = backend
                .resolve(&sn("pkg"), &url, &Refspec::None)
                .expect("resolve with Refspec::None must also read the synthetic phora head");
            assert_eq!(
                none_resolved, resolved,
                "resolve must yield the same synthetic commit regardless of the passed refspec, \
                 proving it ignores the refspec and reads refs/heads/phora"
            );
        }

        #[test]
        fn commit_time_of_synthetic_commit_is_epoch_plus_one() {
            let server = TarServer::spawn(build_pkg_tar_gz());
            let url = server.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

            backend.fetch(&sn("pkg"), &url).expect("fetch");
            let commit = backend
                .resolve(&sn("pkg"), &url, &Refspec::None)
                .expect("resolve synthetic head");

            let time = backend
                .commit_time(&sn("pkg"), &url, &commit)
                .expect("commit_time of synthetic commit");
            assert_eq!(
                time, 1,
                "the synthetic import commit's author time is epoch+1 (==1)"
            );
        }

        #[test]
        fn discover_and_export_yield_stripped_files_with_exec_bit() {
            let server = TarServer::spawn(build_pkg_tar_gz());
            let url = server.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

            backend.fetch(&sn("pkg"), &url).expect("fetch");
            let commit = backend
                .resolve(&sn("pkg"), &url, &Refspec::None)
                .expect("resolve synthetic head");

            let leaves = backend
                .list_source_leaves(&sn("pkg"), &url, &commit, None)
                .expect("list leaves over the synthetic tree");
            assert_eq!(
                leaves,
                vec!["bin/run.sh".to_string(), "hello.txt".to_string()],
                "after pkg-1.0/ strip the leaves are `bin/run.sh` and the root file `hello.txt`"
            );

            let staging = TempDir::new().expect("staging tempdir");
            let policy = ExportPolicy {
                allow_symlinks: false,
                preserve_executable: true,
                vcs_opt_in: false,
            };
            let source = sn("pkg");
            let export_leaves = vec![ExportLeaf {
                source: PathBuf::from("bin/run.sh"),
                dest: PathBuf::from("run.sh"),
            }];
            let export = backend
                .export_artifact(&ExportRequest {
                    source: &source,
                    url: &url,
                    commit: &commit,
                    root: None,
                    policy: &policy,
                    staging_dir: staging.path(),
                    commit_time: 1,
                    template_opt_in: &crate::config::TemplateOptIn::SuffixOnly,
                    vars: &BTreeMap::new(),
                    leaves: &export_leaves,
                })
                .expect("export the `bin` artifact");

            let run = export
                .files
                .iter()
                .find(|f| f.path == Path::new("run.sh"))
                .expect("export must contain run.sh under the bin artifact");
            let run_on_disk = staging.path().join("run.sh");
            assert_eq!(
                std::fs::read(&run_on_disk).expect("read exported run.sh"),
                RUN_BODY,
                "exported run.sh content must equal the served file bytes"
            );
            assert_eq!(
                run.size,
                RUN_BODY.len() as u64,
                "manifest size must match the run.sh body length"
            );
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&run_on_disk)
                    .expect("stat exported run.sh")
                    .permissions()
                    .mode();
                assert!(
                    mode & 0o111 != 0,
                    "the 0o755 archive entry must export with the executable bit set, got mode {mode:o}"
                );
            }

            // hello.txt is a root file: discover skips it and export never touches it,
            // so its import fidelity is only provable straight from the git tree.
            let mirror = mirror_path(git_dir.path(), &url);
            let repo = gix::open(&mirror).expect("open synthetic mirror");
            let oid = gix::ObjectId::from_hex(commit.as_bytes()).expect("commit hex");
            let hello = repo
                .find_commit(oid)
                .expect("find synthetic commit")
                .tree()
                .expect("commit tree")
                .lookup_entry_by_path(Path::new("hello.txt"))
                .expect("lookup hello.txt")
                .expect("hello.txt present at the stripped tree root");
            let blob = repo.find_blob(hello.object_id()).expect("hello.txt blob");
            assert_eq!(
                blob.data, HELLO_BODY,
                "the stripped root file hello.txt must import with its served bytes (`hi`)"
            );
        }

        #[test]
        fn matching_digest_lets_fetch_succeed() {
            let tar_gz = build_pkg_tar_gz();
            let server = TarServer::spawn(tar_gz.clone());
            let url = server.url();

            let mut digests = BTreeMap::new();
            digests.insert(sn("pkg"), Digest::sha256(sha256_of(&tar_gz)));

            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), digests);

            backend
                .fetch(&sn("pkg"), &url)
                .expect("a matching configured digest must let fetch succeed");

            backend
                .resolve(&sn("pkg"), &url, &Refspec::None)
                .expect("a verified fetch must create refs/heads/phora");
        }

        #[test]
        fn mismatched_digest_errors_before_import_naming_source() {
            let tar_gz = build_pkg_tar_gz();
            let server = TarServer::spawn(tar_gz);
            let url = server.url();

            let mut digests = BTreeMap::new();
            digests.insert(sn("pkg"), Digest::sha256([0u8; 32]));

            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), digests);

            let err = backend
                .fetch(&sn("pkg"), &url)
                .expect_err("a non-matching configured digest must fail fetch");
            match err {
                SourceError::Source(msg) => assert!(
                    msg.contains("pkg"),
                    "the digest-mismatch error must name the source `pkg`, got: {msg}"
                ),
                other => panic!("expected SourceError::Source on digest mismatch, got: {other:?}"),
            }

            let mirror = mirror_path(git_dir.path(), &url);
            let phora_ref_exists = gix::open(&mirror)
                .ok()
                .is_some_and(|repo| repo.find_reference("refs/heads/phora").is_ok());
            assert!(
                !phora_ref_exists,
                "a digest mismatch must abort BEFORE import: a git-level lookup of \
                 refs/heads/phora must find nothing (packed or loose) — or the mirror \
                 must not even be initialized"
            );
            assert!(
                backend.resolve(&sn("pkg"), &url, &Refspec::None).is_err(),
                "with no synthetic head imported, resolve must fail after a rejected fetch"
            );
        }

        fn sha256_of(bytes: &[u8]) -> [u8; 32] {
            use sha2::{Digest, Sha256};
            let mut out = [0u8; 32];
            out.copy_from_slice(&Sha256::digest(bytes));
            out
        }

        #[test]
        fn import_round_trip_preserves_hello_blob() {
            let server = TarServer::spawn(build_pkg_tar_gz());
            let url = server.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let backend = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

            backend.fetch(&sn("pkg"), &url).expect("fetch");
            let commit = backend
                .resolve(&sn("pkg"), &url, &Refspec::None)
                .expect("resolve synthetic head");

            let mirror = mirror_path(git_dir.path(), &url);
            let repo = gix::open(&mirror).expect("open synthetic mirror");
            let oid = gix::ObjectId::from_hex(commit.as_bytes()).expect("commit hex");
            let tree = repo
                .find_commit(oid)
                .expect("find synthetic commit")
                .tree()
                .expect("commit tree");
            let entry = tree
                .lookup_entry_by_path(Path::new("hello.txt"))
                .expect("lookup hello.txt")
                .expect("hello.txt present at the stripped tree root");
            assert!(
                matches!(entry.mode().kind(), EntryKind::Blob),
                "hello.txt must import as a plain blob"
            );
            let blob = repo.find_blob(entry.object_id()).expect("hello.txt blob");
            assert_eq!(
                blob.data, HELLO_BODY,
                "the downloaded-extracted-imported hello.txt blob must equal `hi`"
            );
        }

        // ---- MIRROR-LOCK-002: HttpBackend::fetch takes the SAME per-mirror flock ----

        use std::path::PathBuf;
        use std::sync::mpsc;

        /// Derived independently from `mirror_path` so the test fails if the impl
        /// picks a different naming; MUST equal `GitBackend`'s per-mirror lock path.
        fn mirror_lock_path(git_dir: &Path, url: &str) -> PathBuf {
            let mut s = mirror_path(git_dir, url).into_os_string();
            s.push(".lock");
            PathBuf::from(s)
        }

        fn hold_mirror_lock(path: &Path) -> std::fs::File {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("create git_dir for lock");
            }
            let file = std::fs::OpenOptions::new()
                .create(true)
                .read(true)
                .write(true)
                .truncate(false)
                .open(path)
                .expect("open per-mirror lock file");
            file.try_lock()
                .expect("test acquires the mirror lock first");
            file
        }

        #[test]
        fn http_fetch_blocks_on_held_per_mirror_lock_then_succeeds_when_released() {
            let server = TarServer::spawn(build_pkg_tar_gz());
            let url = server.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let git_dir_path = git_dir.path().to_path_buf();

            let lock_path = mirror_lock_path(&git_dir_path, &url);
            let held = hold_mirror_lock(&lock_path);

            let (tx, rx) = mpsc::channel();
            let backend = HttpBackend::new(git_dir_path.clone(), BTreeMap::new());
            let url_for_thread = url.clone();
            let worker = std::thread::spawn(move || {
                let result = backend.fetch(&sn("pkg"), &url_for_thread);
                tx.send(result).expect("send fetch result");
            });

            assert!(
                rx.recv_timeout(Duration::from_millis(750)).is_err(),
                "HttpBackend::fetch must BLOCK while the per-mirror lock is held; it \
                 completed within the window, so it took no blocking lock on {} \
                 around its shared-mirror import",
                lock_path.display()
            );

            drop(held);

            let result = rx
                .recv_timeout(Duration::from_secs(10))
                .expect("http fetch must complete promptly once the mirror lock is released");
            worker.join().expect("fetch thread joins");
            result.expect("http fetch succeeds after waiting for the lock (blocking, not error)");

            let mirror = mirror_path(&git_dir_path, &url);
            let repo = gix::open(&mirror).expect("the serialized fetch leaves a valid mirror");
            assert!(
                repo.find_reference("refs/heads/phora").is_ok(),
                "the serialized http fetch must populate refs/heads/phora"
            );
        }

        #[test]
        fn http_holding_one_mirror_lock_does_not_block_fetch_of_a_different_mirror() {
            let server_a = TarServer::spawn(build_pkg_tar_gz());
            let server_b = TarServer::spawn(build_pkg_tar_gz());
            let url_a = server_a.url();
            let url_b = server_b.url();
            let git_dir = TempDir::new().expect("git_dir tempdir");
            let git_dir_path = git_dir.path().to_path_buf();

            assert_ne!(
                mirror_path(&git_dir_path, &url_a),
                mirror_path(&git_dir_path, &url_b),
                "the two urls must map to distinct mirrors for this test to mean anything"
            );

            let held_a = hold_mirror_lock(&mirror_lock_path(&git_dir_path, &url_a));

            let (tx, rx) = mpsc::channel();
            let backend = HttpBackend::new(git_dir_path.clone(), BTreeMap::new());
            let worker = std::thread::spawn(move || {
                let result = backend.fetch(&sn("pkgb"), &url_b);
                tx.send(result).expect("send fetch-b result");
            });

            let result = rx.recv_timeout(Duration::from_secs(10)).expect(
                "fetching a DIFFERENT mirror must not block on mirror A's lock; \
                 the per-mirror lock must be keyed per MirrorKey",
            );
            worker.join().expect("fetch-b thread joins");
            result.expect("http fetch of mirror B succeeds while A's lock is held");

            drop(held_a);
        }
    }
}