vcs-git 0.8.0

Automate Git from Rust: a typed, async wrapper that drives the real git CLI with its exact behavior, config, and credentials.
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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(rustdoc::broken_intra_doc_links)]
//! `vcs-git` — automate Git from Rust by driving the `git` CLI.
//!
//! You call typed `async` methods; `vcs-git` runs the real `git`, parses its
//! output, and hands you structured values — so you get *git's own* behaviour,
//! config, and credentials, not a reimplementation of the object format. Async,
//! structured errors, mockable. Every command runs inside an OS **job** (an
//! OS-level container that kills the whole process tree if your program exits, via
//! [`processkit`]) so a `git` subprocess is never orphaned, with an optional
//! per-client [timeout](Git::default_timeout).
//!
//! # What you can do
//!
//! Status & branches · stage, commit, checkout · diff & log · merge / rebase /
//! reset · worktrees · tags · blame · clone · config · cherry-pick / revert · parse
//! & resolve conflict markers · a hardened (hooks-off) profile for untrusted repos.
//! One tiny call to start:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_git::{Git, GitApi};
//! # async fn demo() -> Result<(), processkit::Error> {
//! let git = Git::new();
//! // `current_branch` is `Option` — `None` on a detached HEAD.
//! println!("{:?}", git.current_branch(Path::new(".")).await?); // e.g. Some("main")
//! # Ok(()) }
//! ```
//!
//! # The surface (engineering reference)
//!
//! - **[`GitApi`]** — the object-safe trait every operation lives on. Depend on
//!   `&dyn GitApi` (or generically on `impl GitApi`) so a test can swap the real
//!   client for a double. Methods take the working directory as the first
//!   argument and return typed results ([`StatusEntry`], [`Branch`], [`Commit`],
//!   [`FileDiff`], [`BlameLine`], …) or a structured [`Error`].
//! - **[`Git`]** — the real client. [`Git::new`] uses the job-backed runner;
//!   [`Git::with_runner`] injects a fake one for tests. It is generic over the
//!   [`ProcessRunner`] seam, defaulting to the production runner.
//!   [`with_credentials`](Git::with_credentials) attaches a [`CredentialProvider`]
//!   to authenticate HTTPS remote ops (fetch/push/clone/ls-remote) with a token
//!   kept out of `argv` — opt-in, off by default (ambient helpers / SSH agent).
//! - **[`GitAt`]** — a cwd-bound view ([`Git::at`]) whose methods drop the
//!   leading `dir`, so `git.at(dir).status()` reads as `git.status(dir)` — handy
//!   when one client drives one checkout.
//! - **Builder specs** for the multi-option commands — [`CommitPaths`],
//!   [`MergeCommit`] / [`MergeNoCommit`], [`GitPush`], [`CloneSpec`],
//!   [`WorktreeAdd`], [`AnnotatedTag`], [`MergeCheck`] — each `#[non_exhaustive]`, built
//!   with a constructor + chained setters, named after the flags they emit.
//! - **[`conflict`]** — a typed conflict-marker model: parse marker soup into
//!   structured regions, re-render byte-exact, and resolve to a chosen side.
//! - **[`Git::hardened`]** — a profile for untrusted repositories (hooks off,
//!   `GIT_*` scrubbed, system config skipped); see the [`guide::security`] guide.
//!
//! # Recipes
//!
//! Read state — depend on the trait so the same code takes a real client or a mock:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_git::{Git, GitApi};
//! # async fn demo() -> Result<(), processkit::Error> {
//! let git = Git::new();
//! let dir = Path::new(".");
//! let branch = git.current_branch(dir).await?;        // the checked-out branch
//! let dirty = !git.status(dir).await?.is_empty();     // any uncommitted change?
//! # let _ = (branch, dirty); Ok(()) }
//! ```
//!
//! Mutate through the builder specs — `fetch` retries transient network failures:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_git::{CommitPaths, Git, GitApi, GitPush};
//! # async fn demo(git: &Git) -> Result<(), processkit::Error> {
//! let dir = Path::new(".");
//! git.fetch(dir).await?;
//! git.commit_paths(dir, CommitPaths::new(["src/a.rs"], "wip")).await?;
//! git.push(dir, GitPush::branch("feature").set_upstream()).await?;
//! # Ok(()) }
//! ```
//!
//! # Testing
//!
//! Two seams: enable the **`mock`** feature for a `mockall`-generated
//! `MockGitApi` (stub whole methods), or inject a
//! [`ScriptedRunner`](processkit::testing::ScriptedRunner) with [`Git::with_runner`] to
//! exercise the *real* argv-building and parsing against canned output. The
//! cross-cutting testing patterns live in
//! [vcs-testkit's guide](https://docs.rs/vcs-testkit/latest/vcs_testkit/guide/testing/).
//!
//! # Safety
//!
//! Every caller value placed in a bare positional argv slot is refused before
//! spawning if it is empty or starts with `-` (git would parse it as a flag);
//! flag-value slots (`-b <name>`) are consumed verbatim and don't need it. For
//! eager validation at an input boundary, the [`RefName`] / [`RevSpec`] newtypes
//! validate up front. Paths always go through `--` / pathspec.
//!
//! # In-depth guide
//!
//! Beyond this page, this crate ships a full how-to guide — rendered on docs.rs
//! from `docs/`. See the [`guide`] module (and its
//! [`security`](crate::guide::security) / [`conflicts`](crate::guide::conflicts)
//! sub-guides).

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use processkit::Command;
// Re-export the processkit types that appear in this crate's public API, so
// consumers needn't depend on processkit directly — incl. `ProcessRunner` (the
// `with_runner`/`Git<R>` seam) and the `JobRunner` default. (`Error`/`Result`/
// `ProcessResult`/`ProcessRunner` are in scope here too via this `pub use`.)
pub use processkit::{Error, JobRunner, ProcessResult, ProcessRunner, Result};
// Re-exported so a consumer can name the token for `default_cancel_on` without
// taking a direct `processkit` dependency.
pub use processkit::CancellationToken;

pub mod conflict;
mod parse;
pub use parse::{BlameLine, Branch, BranchStatus, Commit, StatusEntry, Worktree};
// The git-format diff model + parser and the version type are shared with
// `vcs-jj` (identical output) — re-exported so `vcs_git::FileDiff`,
// `vcs_git::parse_diff`, `vcs_git::GitVersion`, … still resolve.
pub use vcs_diff::{
    ChangeKind, DiffLine, DiffSpec, DiffStat, FileDiff, Hunk, Version as GitVersion, parse_diff,
};
// The error classifiers live in the shared plumbing crate — re-exported so
// `vcs_git::is_merge_conflict`, … still resolve.
use vcs_cli_support::git_credential_helper;
pub use vcs_cli_support::{
    Credential, CredentialProvider, CredentialRequest, CredentialService, EnvToken, RetryPolicy,
    Secret, StaticCredential, is_lock_contention, is_merge_conflict, is_nothing_to_commit,
    is_transient_fetch_error, provider_fn,
};

/// Name of the underlying CLI binary this crate drives.
pub const BINARY: &str = "git";

/// Options for [`GitApi::worktree_add`] (`git worktree add`).
///
/// `#[non_exhaustive]`, so build it through [`WorktreeAdd::checkout`] /
/// [`WorktreeAdd::create_branch`] rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct WorktreeAdd {
    /// Filesystem path for the new worktree.
    pub path: PathBuf,
    /// Create and check out this new branch (`-b <name>`); `None` checks out an
    /// existing ref.
    pub new_branch: Option<String>,
    /// The commit/branch to base the worktree on; `None` defaults to `HEAD`.
    pub commitish: Option<String>,
    /// Register the worktree without populating its files (`--no-checkout`) — the
    /// caller fills the working tree itself (e.g. a copy-on-write clone).
    pub no_checkout: bool,
}

impl WorktreeAdd {
    /// A worktree at `path` checking out an existing `commitish` (e.g. a branch):
    /// `git worktree add <path> <commitish>`.
    pub fn checkout(path: impl Into<PathBuf>, commitish: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            new_branch: None,
            commitish: Some(commitish.into()),
            no_checkout: false,
        }
    }

    /// A worktree at `path` creating a new branch `name` based on `commitish`:
    /// `git worktree add -b <name> <path> <commitish>`.
    pub fn create_branch(
        path: impl Into<PathBuf>,
        name: impl Into<String>,
        commitish: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            new_branch: Some(name.into()),
            commitish: Some(commitish.into()),
            no_checkout: false,
        }
    }

    /// Register the worktree without checking out its files (`--no-checkout`),
    /// for a caller that populates the working tree itself.
    pub fn no_checkout(mut self) -> Self {
        self.no_checkout = true;
        self
    }
}

/// Options for [`GitApi::push`] (`git push`).
///
/// `#[non_exhaustive]`, so build it through [`GitPush::branch`] /
/// [`GitPush::refspec`] rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GitPush {
    /// Remote to push to (defaults to `origin`).
    pub remote: String,
    /// The refspec — a bare branch name, or `local:remote_branch`.
    pub refspec: String,
    /// Set the pushed branch as the upstream (`-u`).
    pub set_upstream: bool,
}

impl GitPush {
    /// Push branch `name` to `origin` under the same name (`git push origin <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            remote: "origin".to_string(),
            refspec: name.into(),
            set_upstream: false,
        }
    }

    /// Push `local` to a differently-named `remote_branch`
    /// (`git push origin <local>:<remote_branch>`).
    pub fn refspec(local: impl AsRef<str>, remote_branch: impl AsRef<str>) -> Self {
        Self {
            remote: "origin".to_string(),
            refspec: format!("{}:{}", local.as_ref(), remote_branch.as_ref()),
            set_upstream: false,
        }
    }

    /// Push to a non-default remote.
    pub fn remote(mut self, remote: impl Into<String>) -> Self {
        self.remote = remote.into();
        self
    }

    /// Record the pushed branch as the local branch's upstream (`-u`).
    pub fn set_upstream(mut self) -> Self {
        self.set_upstream = true;
        self
    }
}

/// Options for [`GitApi::clone_repo`] (`git clone`).
///
/// `#[non_exhaustive]`, so build it through [`CloneSpec::new`] and the chained
/// setters rather than a struct literal.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CloneSpec {
    /// Check out this branch instead of the remote's default (`--branch`).
    pub branch: Option<String>,
    /// Shallow-clone to this many commits (`--depth`). git silently ignores
    /// the flag for a plain local-path source (warns, still clones fully);
    /// use a `file://` URL to shallow-clone locally.
    pub depth: Option<u32>,
    /// Create a bare repository (`--bare`).
    pub bare: bool,
}

impl CloneSpec {
    /// A plain full clone of the remote's default branch.
    pub fn new() -> Self {
        Self::default()
    }

    /// Check out `branch` instead of the remote's default (`--branch`).
    pub fn branch(mut self, branch: impl Into<String>) -> Self {
        self.branch = Some(branch.into());
        self
    }

    /// Shallow-clone to `depth` commits (`--depth`); see the field doc for the
    /// local-path caveat.
    pub fn depth(mut self, depth: u32) -> Self {
        self.depth = Some(depth);
        self
    }

    /// Clone as a bare repository (`--bare`).
    pub fn bare(mut self) -> Self {
        self.bare = true;
        self
    }
}

/// Options for [`GitApi::commit_paths`] (`git commit --only`).
///
/// `#[non_exhaustive]`, so build it through [`CommitPaths::new`] and the chained
/// setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CommitPaths {
    /// The exact paths whose working-tree content to commit (`--only -- <paths>`).
    pub paths: Vec<PathBuf>,
    /// The commit message (`-m`).
    pub message: String,
    /// Amend the previous commit instead of creating a new one (`--amend`).
    pub amend: bool,
}

impl CommitPaths {
    /// Commit exactly `paths`' working-tree content with `message`
    /// (`git commit -m <message> --only -- <paths>`).
    pub fn new(
        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            paths: paths.into_iter().map(Into::into).collect(),
            message: message.into(),
            amend: false,
        }
    }

    /// Amend the previous commit instead of creating a new one (`--amend`).
    pub fn amend(mut self) -> Self {
        self.amend = true;
        self
    }
}

/// Partial [`MergeCheck`] — names the branch being tested; chain
/// [`into_base`](MergeCheckPartial::into_base) to name the base it must be merged into.
#[derive(Debug, Clone)]
pub struct MergeCheckPartial {
    branch: String,
}

impl MergeCheckPartial {
    /// The base branch/ref `branch` should be fully merged **into**.
    pub fn into_base(self, base: impl Into<String>) -> MergeCheck {
        MergeCheck {
            branch: self.branch,
            base: base.into(),
        }
    }
}

/// A "is `branch` fully merged into `base`?" check for [`GitApi::is_merged`].
///
/// Built as `MergeCheck::branch("feature").into_base("main")` — the two same-typed
/// refs are named across **two** builder steps, so they can't be silently transposed
/// (a swap would *invert* the answer). `#[non_exhaustive]`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MergeCheck {
    /// The branch/ref being tested for having been merged.
    pub branch: String,
    /// The base branch/ref it should be fully merged into.
    pub base: String,
}

impl MergeCheck {
    /// Name the `branch` to test; chain [`into_base`](MergeCheckPartial::into_base).
    pub fn branch(name: impl Into<String>) -> MergeCheckPartial {
        MergeCheckPartial {
            branch: name.into(),
        }
    }
}

/// Options for [`GitApi::merge_commit`] (`git merge` that commits the result).
///
/// `#[non_exhaustive]`, so build it through [`MergeCommit::branch`] and the
/// chained setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MergeCommit {
    /// The branch to merge in.
    pub branch: String,
    /// Always create a merge commit, even when a fast-forward was possible
    /// (`--no-ff`).
    pub no_ff: bool,
    /// The merge commit message (`-m`); `None` takes the default message
    /// non-interactively (`--no-edit`).
    pub message: Option<String>,
}

impl MergeCommit {
    /// Merge `name` taking the default merge message non-interactively
    /// (`git merge --no-edit <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            branch: name.into(),
            no_ff: false,
            message: None,
        }
    }

    /// Always create a merge commit, even when a fast-forward was possible
    /// (`--no-ff`).
    pub fn no_ff(mut self) -> Self {
        self.no_ff = true;
        self
    }

    /// Use `m` as the merge commit message (`-m`).
    pub fn message(mut self, m: impl Into<String>) -> Self {
        self.message = Some(m.into());
        self
    }
}

/// Options for [`GitApi::merge_no_commit`] (`git merge --no-commit`).
///
/// `#[non_exhaustive]`, so build it through [`MergeNoCommit::branch`] and the
/// chained setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MergeNoCommit {
    /// The branch to merge in.
    pub branch: String,
    /// Stage the squashed result without recording `MERGE_HEAD` (`--squash`);
    /// takes precedence over `no_ff` (git rejects the pair).
    pub squash: bool,
    /// Always record a real (abortable) merge, even when a fast-forward was
    /// possible (`--no-ff`).
    pub no_ff: bool,
}

impl MergeNoCommit {
    /// Merge `name` but stop before committing (`git merge --no-commit <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            branch: name.into(),
            squash: false,
            no_ff: false,
        }
    }

    /// Stage the squashed result without recording `MERGE_HEAD` (`--squash`).
    pub fn squash(mut self) -> Self {
        self.squash = true;
        self
    }

    /// Always record a real (abortable) merge, even when a fast-forward was
    /// possible (`--no-ff`).
    pub fn no_ff(mut self) -> Self {
        self.no_ff = true;
        self
    }
}

/// Options for [`GitApi::tag_create_annotated`] (`git tag -a`).
///
/// `#[non_exhaustive]`, so build it through [`AnnotatedTag::new`] and the chained
/// setter rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnnotatedTag {
    /// The tag name.
    pub name: String,
    /// The tag message (`-m`).
    pub message: String,
    /// The revision to tag (`<rev>`); `None` tags `HEAD`.
    pub rev: Option<String>,
}

impl AnnotatedTag {
    /// An annotated tag `name` with `message` at `HEAD`
    /// (`git tag -a <name> -m <message>`).
    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            message: message.into(),
            rev: None,
        }
    }

    /// Tag `r` instead of `HEAD`.
    pub fn rev(mut self, r: impl Into<String>) -> Self {
        self.rev = Some(r.into());
        self
    }
}

/// A pre-validated git reference name (branch/tag/remote), for callers that
/// accept names from untrusted input (UIs, bots, agents) and want to fail
/// early with a clear error. The dir-taking methods stay `&str` — they apply
/// the same flag-injection guard internally — so this type is **optional**
/// up-front validation, not a required wrapper.
///
/// Rules follow the load-bearing core of `git check-ref-format`: non-empty,
/// no leading `-` or `.`, no `..`, no control characters or space, none of
/// `~ ^ : ? * [ \`, no trailing `/` or `.lock`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RefName(String);

impl RefName {
    /// Validate `name` as a reference name.
    pub fn new(name: impl Into<String>) -> Result<Self> {
        let name = name.into();
        let bad = name.is_empty()
            || name.starts_with('-')
            || name.starts_with('.')
            || name.ends_with('/')
            || name.ends_with(".lock")
            || name.contains("..")
            || name
                .chars()
                .any(|c| c.is_control() || " ~^:?*[\\".contains(c));
        if bad {
            return Err(Error::Spawn {
                program: BINARY.to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("invalid git reference name: {name:?}"),
                ),
            });
        }
        Ok(RefName(name))
    }

    /// The validated name.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RefName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// A pre-validated revision/range expression (`HEAD~2`, `main..feature`).
/// Deliberately *minimal* — git's revision grammar is too rich to validate
/// here — it only guarantees the expression is non-empty and cannot be parsed
/// as a flag (no leading `-`), matching the internal guard the dir-taking
/// methods apply anyway. Optional up-front validation for untrusted input.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RevSpec(String);

impl RevSpec {
    /// Validate `rev` as a revision/range expression (non-empty, no leading `-`).
    pub fn new(rev: impl Into<String>) -> Result<Self> {
        let rev = rev.into();
        reject_flag_like("revision", &rev)?;
        Ok(RevSpec(rev))
    }

    /// The validated expression.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RevSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// What the installed `git` binary supports, probed via
/// [`GitApi::capabilities`]. A value type — the client holds no state, so
/// probe once and keep the result (callers cache it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct GitCapabilities {
    /// The binary's parsed version.
    pub version: GitVersion,
}

/// The oldest git major this crate is written against. Validated on 2.54;
/// expected to work from ≥ 2.30 — but only the *major* is hard-gated, because
/// a false "unsupported" on an untested-but-fine 2.2x would be worse than the
/// argv error git itself would give. (Contrast vcs-jj, whose floor is precise:
/// its parsers were empirically validated against one jj release.)
const MIN_SUPPORTED_MAJOR: u64 = 2;

impl GitCapabilities {
    /// Whether the binary meets the supported floor (major ≥ 2).
    pub fn is_supported(&self) -> bool {
        self.version.major >= MIN_SUPPORTED_MAJOR
    }

    /// Error unless [`is_supported`](Self::is_supported) — a clear "needs git
    /// ≥ 2, found 1.9.5" instead of a cryptic argv failure later.
    pub fn ensure_supported(&self) -> Result<()> {
        if self.is_supported() {
            return Ok(());
        }
        Err(Error::Spawn {
            program: BINARY.to_string(),
            source: std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!(
                    "vcs-git requires git >= {MIN_SUPPORTED_MAJOR} (validated on 2.54), \
                     found {}",
                    self.version
                ),
            ),
        })
    }
}

/// The Git operations this crate exposes — the interface consumers code against
/// and mock in tests.
///
/// **Injection safety:** every method that places a caller-supplied name,
/// revision, range, remote, or URL in a positional argv slot rejects a value
/// that is empty or begins with `-` (it would be parsed as a flag) with an
/// [`Error::Spawn`] *before* spawning. Flag-value slots (`-m <msg>`,
/// `--branch <b>`), filesystem path arguments (`--`-separated pathspecs, plus
/// worktree paths and clone destinations — typed `Path`, caller-trusted), and
/// the `run`/`run_raw` escape hatches are not guarded. For eager validation at
/// an input boundary, see [`RefName`] / [`RevSpec`].
#[cfg_attr(feature = "mock", mockall::automock)]
#[async_trait::async_trait]
pub trait GitApi: Send + Sync {
    /// Run `git <args>` **in the process's current directory**, returning trimmed
    /// stdout (throws on a non-zero exit). A raw escape hatch for unmodelled commands
    /// — you supply the whole argv, so target a specific repo with `-C <dir>` in the
    /// args. The `at(dir)` bound view does **not** re-bind `run`/`run_args` (they and
    /// the other `run*` hatches stay process-cwd, unlike every modelled `GitAt`
    /// method); pass `-C dir` explicitly if you need the bound repo (M15).
    async fn run(&self, args: &[String]) -> Result<String>;
    /// Like [`GitApi::run`] but never errors on a non-zero exit — returns the
    /// captured [`ProcessResult`].
    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>>;
    /// Installed Git version (`git --version`).
    async fn version(&self) -> Result<String>;
    /// The installed binary's parsed version, as [`GitCapabilities`]
    /// (`git --version`). A value type — probe once and keep it; an
    /// unrecognisable version string is an [`Error::Parse`].
    async fn capabilities(&self) -> Result<GitCapabilities>;
    /// Working-tree status (`git status --porcelain=v1 -z`).
    async fn status(&self, dir: &Path) -> Result<Vec<StatusEntry>>;
    /// Raw porcelain status text (`git status --porcelain=v1`) — the unparsed
    /// counterpart of [`status`](GitApi::status), mirroring `vcs_jj` `status_text`.
    async fn status_text(&self, dir: &Path) -> Result<String>;
    /// Like [`status`](GitApi::status) but ignoring untracked files
    /// (`git status --porcelain=v1 -z --untracked-files=no`) — "is the *tracked*
    /// tree dirty", staged or not.
    async fn status_tracked(&self, dir: &Path) -> Result<Vec<StatusEntry>>;
    /// A combined branch + working-tree snapshot in **one** spawn
    /// (`git status --porcelain=v2 --branch -z`): HEAD, branch, upstream,
    /// ahead/behind, and change counts — the data a prompt/status-bar needs
    /// without N round-trips. See [`BranchStatus`].
    async fn branch_status(&self, dir: &Path) -> Result<BranchStatus>;
    /// Paths with unresolved merge conflicts, repo-relative with `/` separators
    /// (`git diff --name-only --diff-filter=U -z`). Empty when there are none.
    async fn conflicted_files(&self, dir: &Path) -> Result<Vec<String>>;
    /// Current branch name, or `None` on a **detached HEAD**
    /// (`git symbolic-ref --quiet --short HEAD`). Returns the branch name for a
    /// normal branch **and for an unborn branch** (a fresh `init`/`clone` before the
    /// first commit); `None` only when HEAD is detached. Mirrors
    /// [`JjApi::current_bookmark`](../vcs_jj/trait.JjApi.html#tymethod.current_bookmark)'s
    /// `Option` shape, so cross-backend code treats "no named branch/bookmark" the
    /// same way on both wrappers.
    async fn current_branch(&self, dir: &Path) -> Result<Option<String>>;
    /// Local branches, current one flagged (`git branch`).
    async fn branches(&self, dir: &Path) -> Result<Vec<Branch>>;
    /// Up to `max` commits reachable from `revspec`, newest first
    /// (`git log <revspec>`). Pass `"HEAD"` for the current branch's history, or
    /// a range like `"main..HEAD"` / `"origin/main..HEAD"` to scope it. Mirrors
    /// [`JjApi::log`](../vcs_jj/trait.JjApi.html#tymethod.log)'s revset argument,
    /// so cross-backend code uses one signature. The `revspec` is guarded against
    /// being parsed as a flag.
    async fn log(&self, dir: &Path, revspec: &str, max: usize) -> Result<Vec<Commit>>;
    /// Resolve a revision to a full hash (`git rev-parse --verify <rev>`). `--verify`
    /// requires `rev` to name exactly one object, so a non-revision (e.g. a filename)
    /// errors instead of being echoed back as a fake id.
    async fn rev_parse(&self, dir: &Path, rev: &str) -> Result<String>;
    /// Resolve a revision to its abbreviated hash (`git rev-parse --short <rev>`) —
    /// e.g. to label a detached HEAD.
    async fn rev_parse_short(&self, dir: &Path, rev: &str) -> Result<String>;
    /// Initialise a repository (`git init`).
    async fn init(&self, dir: &Path) -> Result<()>;
    /// Stage `paths` (`git add -- <paths>`).
    async fn add(&self, dir: &Path, paths: &[PathBuf]) -> Result<()>;
    /// Commit staged changes (`git commit -m`).
    async fn commit(&self, dir: &Path, message: &str) -> Result<()>;
    /// Create a branch without switching to it (`git branch <name>`).
    async fn create_branch(&self, dir: &Path, name: &str) -> Result<()>;
    /// Switch to a branch or revision (`git checkout <reference>`).
    async fn checkout(&self, dir: &Path, reference: &str) -> Result<()>;
    /// Check out a commit as a detached HEAD (`git checkout --detach <commit>`).
    async fn checkout_detach(&self, dir: &Path, commit: &str) -> Result<()>;
    /// Commit exactly the spec's paths' working-tree content, ignoring the index
    /// (`git commit [--amend] -m <message> --only -- <paths>`); see [`CommitPaths`].
    async fn commit_paths(&self, dir: &Path, spec: CommitPaths) -> Result<()>;
    /// The last commit's full message (`git log -1 --format=%B`) — e.g. to
    /// pre-fill an amend.
    async fn last_commit_message(&self, dir: &Path) -> Result<String>;
    /// Whether `HEAD` is unborn — a fresh repo with no commits yet
    /// (`git rev-parse --verify -q HEAD`, exit-code mapped).
    async fn is_unborn(&self, dir: &Path) -> Result<bool>;
    /// Whether the working tree has no unstaged modifications to **tracked** files
    /// (`git diff --quiet`). Untracked files are *not* counted — this is not a full
    /// "is the working tree clean?" check; use [`status`](GitApi::status) for that.
    async fn diff_is_empty(&self, dir: &Path) -> Result<bool>;

    // --- Discovery / identity ------------------------------------------------

    /// The repository's common git directory (`rev-parse --git-common-dir`) —
    /// stable across linked worktrees.
    async fn common_dir(&self, dir: &Path) -> Result<PathBuf>;
    /// This worktree's git directory (`rev-parse --git-dir`).
    async fn git_dir(&self, dir: &Path) -> Result<PathBuf>;
    /// Resolve a revision to a commit hash, peeling tags
    /// (`rev-parse --verify <rev>^{commit}`).
    async fn resolve_commit(&self, dir: &Path, rev: &str) -> Result<String>;
    /// The remote's default branch from `symbolic-ref refs/remotes/origin/HEAD`
    /// (short name only); `None` when `origin/HEAD` is unset.
    async fn remote_head_branch(&self, dir: &Path) -> Result<Option<String>>;
    /// Whether a local branch exists (`show-ref --verify --quiet refs/heads/<name>`).
    async fn branch_exists(&self, dir: &Path, name: &str) -> Result<bool>;
    /// Whether `origin` has `name`, without fetching (`ls-remote origin
    /// refs/heads/<name>` — the fully-qualified ref, so `foo` can't tail-match
    /// `bar/foo`). Runs with `GIT_TERMINAL_PROMPT=0` and a 10s timeout so a missing
    /// credential or a flaky network can't hang the call.
    async fn remote_branch_exists(&self, dir: &Path, name: &str) -> Result<bool>;
    /// A remote's URL (`remote get-url <remote>`).
    async fn remote_url(&self, dir: &Path, remote: &str) -> Result<String>;
    /// The current branch's upstream, e.g. `Some("origin/main")`
    /// (`rev-parse --abbrev-ref --symbolic-full-name @{u}`); `None` when unset.
    async fn upstream(&self, dir: &Path) -> Result<Option<String>>;
    /// Branch names on `remote`, without fetching
    /// (`ls-remote --heads <remote>`).
    async fn remote_branches(&self, dir: &Path, remote: &str) -> Result<Vec<String>>;

    // --- Branches ------------------------------------------------------------

    /// Whether the [`MergeCheck`]'s `branch` is fully merged into its `base`
    /// (`branch --merged <base>`). Build it as
    /// `MergeCheck::branch("feature").into_base("main")` so the two refs can't be
    /// transposed (a swap would invert the answer).
    async fn is_merged(&self, dir: &Path, spec: MergeCheck) -> Result<bool>;
    /// Set `branch`'s upstream to `upstream` (e.g. `origin/main`)
    /// (`branch --set-upstream-to=<upstream> <branch>`).
    async fn set_upstream(&self, dir: &Path, branch: &str, upstream: &str) -> Result<()>;
    /// Delete a local branch (`branch -d`, or `-D` when `force`).
    async fn delete_branch(&self, dir: &Path, name: &str, force: bool) -> Result<()>;
    /// Rename a local branch (`branch -m <old> <new>`).
    async fn rename_branch(&self, dir: &Path, old: &str, new: &str) -> Result<()>;
    /// Count commits in a range (`rev-list --count <range>`).
    async fn rev_list_count(&self, dir: &Path, range: &str) -> Result<usize>;
    /// Whether a diff range is empty (`diff --quiet <range>`).
    async fn diff_range_is_empty(&self, dir: &Path, range: &str) -> Result<bool>;
    /// Aggregate change stats for a range (`diff --shortstat <range>`). Named to
    /// match `vcs_jj::JjApi::diff_stat`.
    async fn diff_stat(&self, dir: &Path, range: &str) -> Result<DiffStat>;
    /// Raw git-format unified diff text for `spec`
    /// (`diff <spec> --no-color --no-ext-diff -M`) — stable machine output, returned
    /// **verbatim** (a trailing blank context line is preserved, so the last hunk
    /// stays in sync with its `@@` line count for a re-parse/re-apply).
    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String>;
    /// Parsed per-file unified diff for `spec`, layered on [`diff_text`](GitApi::diff_text).
    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>>;

    // --- In-progress state ---------------------------------------------------

    /// Whether the index has no staged changes (`diff --cached --quiet`).
    async fn staged_is_empty(&self, dir: &Path) -> Result<bool>;
    /// Whether a rebase is in progress (a `rebase-merge` dir, or a `rebase-apply` dir
    /// **not** left by `git am`, exists under the git dir).
    async fn is_rebase_in_progress(&self, dir: &Path) -> Result<bool>;
    /// Whether a merge is in progress (a `MERGE_HEAD` exists under the git dir).
    async fn is_merge_in_progress(&self, dir: &Path) -> Result<bool>;
    /// Whether a `git am` (mailbox apply) is in progress (`rebase-apply/applying`).
    /// Distinct from a rebase, which shares the `rebase-apply` dir but without the
    /// `applying` marker — aborting an am needs `am --abort`, not `rebase --abort`.
    async fn is_am_in_progress(&self, dir: &Path) -> Result<bool>;

    // --- Mutations -----------------------------------------------------------

    /// Fetch from the default remote (`fetch --quiet`), with `GIT_TERMINAL_PROMPT=0`.
    /// Transient (network) failures are retried (3 attempts, 500 ms backoff).
    async fn fetch(&self, dir: &Path) -> Result<()>;
    /// Fetch from a *named* remote (`fetch --quiet <remote>`), with
    /// `GIT_TERMINAL_PROMPT=0`. Transient failures are retried like
    /// [`fetch`](GitApi::fetch).
    async fn fetch_from(&self, dir: &Path, remote: &str) -> Result<()>;
    /// Fetch a single branch from `origin` into its remote-tracking ref
    /// (`fetch --quiet origin refs/heads/<b>:refs/remotes/origin/<b>`), with
    /// `GIT_TERMINAL_PROMPT=0`. Transient failures are retried (3×, 500 ms).
    async fn fetch_branch(&self, dir: &Path, branch: &str) -> Result<()>;
    /// Push to a remote (`push [-u] <remote> <refspec>`); see [`GitPush`].
    async fn push(&self, dir: &Path, spec: GitPush) -> Result<()>;
    /// Stage a branch's changes without committing (`merge --squash <branch>`).
    async fn merge_squash(&self, dir: &Path, branch: &str) -> Result<()>;
    /// Merge a branch (`merge [--no-ff] [-m <msg> | --no-edit] <branch>`); with no
    /// message it takes the default merge message non-interactively (`--no-edit`).
    /// See [`MergeCommit`].
    async fn merge_commit(&self, dir: &Path, spec: MergeCommit) -> Result<()>;
    /// Merge a branch but stop before committing, so the result can be inspected
    /// (`merge --no-commit [--squash | --no-ff] <branch>`). With `no_ff` (and not
    /// `squash`) git records `MERGE_HEAD`, so the in-progress merge is abortable
    /// via [`merge_abort`](GitApi::merge_abort) — the dry-run pattern. With
    /// `squash`, git stages the squashed result but records **no** `MERGE_HEAD`,
    /// so it is *not* an abortable merge: undo it with
    /// [`reset_merge`](GitApi::reset_merge) / [`reset_hard`](GitApi::reset_hard),
    /// not `merge_abort`. See [`MergeNoCommit`].
    async fn merge_no_commit(&self, dir: &Path, spec: MergeNoCommit) -> Result<()>;
    /// Abort an in-progress merge (`merge --abort`).
    async fn merge_abort(&self, dir: &Path) -> Result<()>;
    /// Finish a merge after resolving conflicts (`commit --no-edit`).
    async fn merge_continue(&self, dir: &Path) -> Result<()>;
    /// Undo an in-progress (or just-staged) merge: `reset --merge` resets the
    /// index and the merge-touched working-tree files back to `HEAD` and drops
    /// `MERGE_HEAD`, **discarding the merge's changes** while keeping unrelated
    /// unstaged edits. Use it after `merge_squash` / `merge_no_commit(squash)`,
    /// where there is no `MERGE_HEAD` for `merge_abort` to act on.
    async fn reset_merge(&self, dir: &Path) -> Result<()>;
    /// Hard-reset the working tree to a revision (`reset --hard <rev>`).
    async fn reset_hard(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Rebase the current branch onto `onto` (`rebase <onto>`); the editor is
    /// suppressed (`GIT_EDITOR=true`) so it never hangs a headless caller.
    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()>;
    /// Abort an in-progress rebase (`rebase --abort`).
    async fn rebase_abort(&self, dir: &Path) -> Result<()>;
    /// Abort an in-progress `git am` (`am --abort`), restoring the pre-`am` HEAD.
    async fn am_abort(&self, dir: &Path) -> Result<()>;
    /// Continue a rebase after resolving conflicts (`rebase --continue`); the
    /// editor is suppressed (`GIT_EDITOR=true`) so the message-confirm never hangs.
    async fn rebase_continue(&self, dir: &Path) -> Result<()>;
    /// Stash the working tree (`stash push`, `--include-untracked` when asked) —
    /// e.g. to save state before a copy-on-write restore.
    async fn stash_push(&self, dir: &Path, include_untracked: bool) -> Result<()>;
    /// Restore the most recent stash and drop it (`stash pop`).
    async fn stash_pop(&self, dir: &Path) -> Result<()>;

    // --- Worktrees -----------------------------------------------------------

    /// List worktrees (`worktree list --porcelain`).
    async fn worktree_list(&self, dir: &Path) -> Result<Vec<Worktree>>;
    /// Add a worktree (`worktree add [-b <branch>] <path> [<commitish>]`).
    async fn worktree_add(&self, dir: &Path, spec: WorktreeAdd) -> Result<()>;
    /// Remove a worktree (`worktree remove [--force] <path>`).
    async fn worktree_remove(&self, dir: &Path, path: &Path, force: bool) -> Result<()>;
    /// Move a worktree (`worktree move <from> <to>`).
    async fn worktree_move(&self, dir: &Path, from: &Path, to: &Path) -> Result<()>;
    /// Prune stale worktree admin entries (`worktree prune`).
    async fn worktree_prune(&self, dir: &Path) -> Result<()>;

    // --- Clone / tags / inspection --------------------------------------------

    /// Clone `url` into `dest` (`git clone <url> <dest>` + [`CloneSpec`] flags).
    /// Runs without a working directory — pass an **absolute** `dest`.
    async fn clone_repo(&self, url: &str, dest: &Path, spec: CloneSpec) -> Result<()>;
    /// Create a lightweight tag at `rev` (`tag <name> [<rev>]`; `None` = HEAD).
    async fn tag_create(&self, dir: &Path, name: &str, rev: Option<String>) -> Result<()>;
    /// Create an annotated tag (`tag -a <name> -m <message> [<rev>]`); see
    /// [`AnnotatedTag`].
    async fn tag_create_annotated(&self, dir: &Path, spec: AnnotatedTag) -> Result<()>;
    /// Tag names, sorted by git's default ordering (`tag --list`).
    async fn tag_list(&self, dir: &Path) -> Result<Vec<String>>;
    /// Delete a tag (`tag -d <name>`).
    async fn tag_delete(&self, dir: &Path, name: &str) -> Result<()>;
    /// A file's content at a revision (`git show <rev>:<path>`). `path` is
    /// repo-relative; backslashes are normalised to `/` (git requires it).
    /// Content is decoded **lossily** — binary files come back mangled rather
    /// than erroring — and returned **verbatim**: the blob's trailing newline(s)
    /// are preserved (not trimmed), so a read-modify-write round-trip is byte-exact.
    async fn show_file(&self, dir: &Path, rev: &str, path: &str) -> Result<String>;
    /// The value of a config key, or `None` when unset (`config --get <key>`,
    /// whose exit 1 covers both "unset" and "no such section" — git doesn't
    /// distinguish). A multi-valued key errors; read those via `run`.
    async fn config_get(&self, dir: &Path, key: &str) -> Result<Option<String>>;
    /// Set a config key in the repository's local config (`config <key> <value>`).
    ///
    /// **Trusted-input sink.** `key` is guarded against a flag-shape, but this
    /// writes whatever key/value it's given — including code-execution keys like
    /// `core.sshCommand` or `filter.<drv>.clean`. Never wire untrusted input into
    /// it; a `harden()`ed client does *not* protect against config *you* write.
    async fn config_set(&self, dir: &Path, key: &str, value: &str) -> Result<()>;
    /// Add a remote (`remote add <name> <url>`).
    async fn remote_add(&self, dir: &Path, name: &str, url: &str) -> Result<()>;
    /// Change a remote's URL (`remote set-url <name> <url>`).
    async fn remote_set_url(&self, dir: &Path, name: &str, url: &str) -> Result<()>;
    /// Per-line authorship of `path` (`blame --line-porcelain [<rev>] -- <path>`;
    /// `None` = the working tree's HEAD).
    async fn blame(&self, dir: &Path, path: &str, rev: Option<String>) -> Result<Vec<BlameLine>>;

    // --- Sequencer -------------------------------------------------------------

    /// Apply a commit onto the current branch (`cherry-pick <rev>`). A conflict
    /// surfaces as an error classified by [`is_merge_conflict`].
    async fn cherry_pick(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Revert a commit with the default message (`revert --no-edit <rev>`).
    async fn revert(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Skip the current patch of a paused rebase (`rebase --skip`). Mainly for
    /// the `apply` backend's "nothing to commit" stop — the default `merge`
    /// backend auto-drops emptied patches on `--continue`.
    async fn rebase_skip(&self, dir: &Path) -> Result<()>;
}

vcs_cli_support::managed_client! {
    /// The real Git client. Generic over the [`ProcessRunner`] so tests can inject a
    /// fake process executor; [`Git::new`] uses the real job-backed runner.
    ///
    /// Wraps a [`ManagedClient`](vcs_cli_support::ManagedClient): enable lock-contention retry with
    /// [`with_retry`](Git::with_retry) (opt-in; off by default).
    ///
    /// **Every** client (not just [`hardened`](Git::hardened)) scrubs the inherited
    /// repo-**redirector** environment variables below, so a `GIT_DIR` (etc.) leaking
    /// from the parent process — e.g. running inside a git hook, which exports
    /// `GIT_DIR`/`GIT_INDEX_FILE` — can't silently redirect commands at a *different*
    /// repository than the bound `dir`. (`harden()` additionally scrubs the
    /// command-hook vars and pins hooks/fsmonitor/sshCommand off.)
    pub struct Git => BINARY, scrub_env = [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_COMMON_DIR",
        "GIT_OBJECT_DIRECTORY",
        "GIT_ALTERNATE_OBJECT_DIRECTORIES",
        "GIT_NAMESPACE",
    ]
}

impl<R: ProcessRunner> Git<R> {
    /// Retry **whole-repo lock-contention** failures (another process holds the
    /// repo's `index.lock`) per `policy` — opt-in, off by default. Safe even for
    /// mutating commands: that lock is acquired before any write, so a failure is
    /// pre-execution (git never ran) and a retry can't double-apply. Per-ref lock
    /// failures are *not* retried (a multi-ref op can fail a ref lock mid-way). See
    /// [`RetryPolicy`] and [`is_lock_contention`].
    pub fn with_retry(mut self, policy: RetryPolicy) -> Self {
        self.core = self.core.with_retry(policy);
        self
    }

    /// Supply credentials for **HTTPS** remote operations (`fetch`/`push`/`clone`/
    /// `ls-remote`) via a [`CredentialProvider`] — opt-in, off by default (ambient
    /// git credential helpers / SSH agent). When the provider yields a credential,
    /// each remote op runs with an inline `credential.helper` that feeds the secret
    /// from an environment variable, so the token never appears in `argv`. Local
    /// operations are unaffected. This covers HTTPS only — an **SSH** remote ignores
    /// the helper and authenticates via the ambient SSH agent, as before.
    #[must_use]
    pub fn with_credentials(mut self, provider: Arc<dyn CredentialProvider>) -> Self {
        self.core = self.core.with_credentials(provider);
        self
    }

    /// Convenience for the common case: authenticate HTTPS remotes with a single
    /// static `token` (a personal-access token; the default username
    /// `x-access-token` is used). Shorthand for
    /// `with_credentials(Arc::new(StaticCredential::token(token)))`. For a specific
    /// username, build a [`Credential::userpass`] and use
    /// [`with_credentials`](Git::with_credentials).
    #[must_use]
    pub fn with_token(self, token: impl Into<Secret>) -> Self {
        self.with_credentials(Arc::new(StaticCredential::token(token)))
    }

    /// Convenience: read the HTTPS token from environment variable `var` at request
    /// time; if `var` is unset/empty, fall back to ambient auth. Shorthand for
    /// `with_credentials(Arc::new(EnvToken::new(var)))`.
    #[must_use]
    pub fn with_env_token(self, var: impl Into<String>) -> Self {
        self.with_credentials(Arc::new(EnvToken::new(var)))
    }

    /// Resolve HTTPS credentials for a remote op into the leading `-c` config args
    /// (an inline `credential.helper`) and the secret env to set on the command.
    /// Both are empty when no provider is configured — ambient git auth, unchanged.
    /// The secret lives only in the returned env, never in the args.
    ///
    /// `expect_host` scopes the helper to a host (the secret is released only for
    /// that host, so a redirect/submodule to another host can't extract it).
    /// Callers that know the operation's target host — e.g. `clone` from its URL —
    /// pass it; the others pass `None` (the helper is ungated, as before).
    async fn remote_credentials(
        &self,
        expect_host: Option<&str>,
    ) -> Result<(Vec<String>, Vec<(String, Secret)>)> {
        match self
            .core
            .resolve_credential(CredentialService::Git, None)
            .await?
        {
            Some(cred) => {
                let helper = git_credential_helper(&cred, expect_host);
                Ok((helper.config_args, helper.env))
            }
            None => Ok((Vec::new(), Vec::new())),
        }
    }
}

/// Set each secret environment variable on `cmd` (the values from
/// [`Git::remote_credentials`]). A no-op when `envs` is empty.
fn apply_secret_env(cmd: Command, envs: &[(String, Secret)]) -> Command {
    envs.iter()
        .fold(cmd, |cmd, (name, value)| cmd.env(name, value.expose()))
}

#[async_trait::async_trait]
impl<R: ProcessRunner> GitApi for Git<R> {
    async fn run(&self, args: &[String]) -> Result<String> {
        self.core.run(args).await
    }

    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>> {
        self.core.output_string(args).await
    }

    async fn version(&self) -> Result<String> {
        self.core.run(["--version"]).await
    }

    async fn capabilities(&self) -> Result<GitCapabilities> {
        let raw = self.version().await?;
        let version = parse::parse_git_version(&raw).ok_or_else(|| Error::Parse {
            program: BINARY.to_string(),
            message: format!("unrecognisable `git --version` output: {raw:?}"),
        })?;
        Ok(GitCapabilities { version })
    }

    async fn status(&self, dir: &Path) -> Result<Vec<StatusEntry>> {
        self.core
            .parse(
                self.core
                    .command_in(dir, ["status", "--porcelain=v1", "-z"]),
                parse::parse_porcelain,
            )
            .await
    }

    async fn status_text(&self, dir: &Path) -> Result<String> {
        self.core
            .run(self.core.command_in(dir, ["status", "--porcelain=v1"]))
            .await
    }

    async fn branch_status(&self, dir: &Path) -> Result<BranchStatus> {
        // `GIT_OPTIONAL_LOCKS=0`: skip the opportunistic index refresh-write a
        // `status` may otherwise persist. This is the snapshot/poll primitive —
        // a filesystem watcher re-querying through it must not have the query
        // itself dirty `.git/index` and re-trigger the watch (verified: with
        // optional locks off, a re-query writes nothing).
        self.core
            .parse(
                self.core
                    .command_in(dir, ["status", "--porcelain=v2", "--branch", "-z"])
                    .env("GIT_OPTIONAL_LOCKS", "0"),
                parse::parse_porcelain_v2,
            )
            .await
    }

    async fn status_tracked(&self, dir: &Path) -> Result<Vec<StatusEntry>> {
        self.core
            .parse(
                self.core.command_in(
                    dir,
                    ["status", "--porcelain=v1", "-z", "--untracked-files=no"],
                ),
                parse::parse_porcelain,
            )
            .await
    }

    async fn conflicted_files(&self, dir: &Path) -> Result<Vec<String>> {
        // `-z` keeps special-character paths literal (no C-style quoting).
        self.core
            .parse(
                self.core
                    .command_in(dir, ["diff", "--name-only", "--diff-filter=U", "-z"]),
                parse::parse_nul_paths,
            )
            .await
    }

    async fn current_branch(&self, dir: &Path) -> Result<Option<String>> {
        // `symbolic-ref --quiet --short HEAD` is the one command that answers all
        // three head states correctly in a single spawn: it prints the branch name
        // (exit 0) for a normal **and an unborn** branch (a fresh `init`/`clone`
        // before the first commit — where `rev-parse --abbrev-ref HEAD` instead
        // *errors* with exit 128), and `--quiet` makes a detached HEAD a silent
        // exit 1 (HEAD isn't a symbolic ref) rather than a `fatal:`. So map exit
        // 0 → `Some(branch)`, exit 1 → `None` (detached), and anything else (e.g.
        // not a repository, exit 128) stays a real error.
        let res = self
            .core
            .output_string(
                self.core
                    .command_in(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
            )
            .await?;
        match res.code() {
            Some(0) => Ok(Some(res.stdout().trim().to_string())),
            Some(1) => Ok(None), // detached HEAD: no named branch
            _ => {
                let _ = res.ensure_success()?;
                Ok(None) // unreachable: a non-zero exit always errors above
            }
        }
    }

    async fn branches(&self, dir: &Path) -> Result<Vec<Branch>> {
        // `--no-column` + `--no-color`: `column.ui = always` would columnate
        // several names onto one line and `color.{ui,branch} = always` would inject
        // ANSI escapes — both even when piped, corrupting the line parser and the
        // returned names.
        self.core
            .parse(
                self.core
                    .command_in(dir, ["branch", "--no-column", "--no-color"]),
                parse::parse_branches,
            )
            .await
    }

    async fn log(&self, dir: &Path, revspec: &str, max: usize) -> Result<Vec<Commit>> {
        reject_flag_like("revspec", revspec)?;
        let n = format!("-n{max}");
        self.core
            .parse(
                self.core.command_in(
                    dir,
                    [
                        "log",
                        revspec,
                        n.as_str(),
                        "-z",
                        "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s",
                    ],
                ),
                parse::parse_log,
            )
            .await
    }

    async fn rev_parse(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        // `--verify`: without it, `git rev-parse Makefile` echoes the *filename* back
        // as a fake object id (exit 0), so a caller resolving an untrusted revision
        // could get a non-hash. `--verify` requires `rev` to name exactly one object,
        // erroring otherwise — a valid revision still resolves to the same full hash
        // (M13; matches `rev_parse_short`/`resolve_commit`, which already `--verify`).
        self.core
            .run(self.core.command_in(dir, ["rev-parse", "--verify", rev]))
            .await
    }

    async fn rev_parse_short(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        self.core
            .run(self.core.command_in(dir, ["rev-parse", "--short", rev]))
            .await
    }

    async fn init(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["init"]))
            .await
    }

    async fn add(&self, dir: &Path, paths: &[PathBuf]) -> Result<()> {
        // `--` separates the pathspecs so a path can never be read as an option.
        let mut command = self.core.command_in(dir, ["add", "--"]);
        for path in paths {
            command = command.arg(path);
        }
        self.core.run_unit(command).await
    }

    async fn commit(&self, dir: &Path, message: &str) -> Result<()> {
        // C locale: a failure's output feeds `is_nothing_to_commit`.
        self.core
            .run_unit(c_locale(
                self.core.command_in(dir, ["commit", "-m", message]),
            ))
            .await
    }

    async fn create_branch(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("branch name", name)?;
        self.core
            .run_unit(self.core.command_in(dir, ["branch", name]))
            .await
    }

    async fn checkout(&self, dir: &Path, reference: &str) -> Result<()> {
        reject_flag_like("reference", reference)?;
        // The trailing `--` marks the end of revisions with no pathspecs
        // following, so git resolves `reference` as a ref *only*. Without it a
        // `reference` that doesn't name a ref but names a tracked path silently
        // falls into pathspec mode and restores that path from the index,
        // discarding unstaged edits (verified: `git checkout notes.txt` →
        // "Updated 1 path", exit 0; `git checkout notes.txt --` → hard error).
        self.core
            .run_unit(self.core.command_in(dir, ["checkout", reference, "--"]))
            .await
    }

    async fn checkout_detach(&self, dir: &Path, commit: &str) -> Result<()> {
        reject_flag_like("commit", commit)?;
        self.core
            .run_unit(self.core.command_in(dir, ["checkout", "--detach", commit]))
            .await
    }

    async fn commit_paths(&self, dir: &Path, spec: CommitPaths) -> Result<()> {
        // `--only -- <paths>` commits exactly these paths' working-tree content
        // regardless of the index; `--` keeps a path from being read as an option.
        // C locale: a failure's output feeds `is_nothing_to_commit`.
        let mut command = c_locale(self.core.command_in(dir, ["commit"]));
        if spec.amend {
            command = command.arg("--amend");
        }
        command = command.arg("-m").arg(spec.message).arg("--only").arg("--");
        for path in &spec.paths {
            command = command.arg(path);
        }
        self.core.run_unit(command).await
    }

    async fn last_commit_message(&self, dir: &Path) -> Result<String> {
        self.core
            .run(self.core.command_in(dir, ["log", "-1", "--format=%B"]))
            .await
    }

    async fn is_unborn(&self, dir: &Path) -> Result<bool> {
        // `rev-parse --verify -q HEAD` resolves HEAD quietly: 0 = a commit exists
        // (not unborn), 1 = no commit yet (unborn). `probe` maps those to a bool
        // and surfaces anything else (e.g. 128, not a repo) as `Error::Exit`.
        Ok(!self
            .core
            .probe(
                self.core
                    .command_in(dir, ["rev-parse", "--verify", "-q", "HEAD"]),
            )
            .await?)
    }

    async fn diff_is_empty(&self, dir: &Path) -> Result<bool> {
        // `git diff --quiet` is an exit-code answer: 0 = clean (empty), 1 = dirty;
        // `probe` errors on any other code / timeout / signal.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--quiet"]))
            .await
    }

    async fn common_dir(&self, dir: &Path) -> Result<PathBuf> {
        Ok(PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-common-dir"]))
                .await?,
        ))
    }

    async fn git_dir(&self, dir: &Path) -> Result<PathBuf> {
        Ok(PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-dir"]))
                .await?,
        ))
    }

    async fn resolve_commit(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        // `^{commit}` peels an annotated tag down to the commit it points at.
        let spec = format!("{rev}^{{commit}}");
        self.core
            .run(
                self.core
                    .command_in(dir, ["rev-parse", "--verify", spec.as_str()]),
            )
            .await
    }

    async fn remote_head_branch(&self, dir: &Path) -> Result<Option<String>> {
        // `--quiet` makes an *unset* origin/HEAD a silent **exit 1** (no `fatal:`
        // on stderr); that's "no default branch", not an error. Map exit 0 → the
        // branch, exit 1 → `None`, and anything else (a real failure like "not a
        // repository" exit 128, or a timeout/signal with no exit code) surfaces via
        // `ensure_success` — mirroring `config_get`, rather than swallowing it.
        let res = self
            .core
            .output_string(
                self.core
                    .command_in(dir, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]),
            )
            .await?;
        match res.code() {
            Some(0) => {
                // "refs/remotes/origin/main" → "main"; strip the whole ref prefix so
                // a slashed default branch (e.g. "release/v2") survives intact.
                let out = res.stdout().trim();
                Ok(Some(
                    out.strip_prefix("refs/remotes/origin/")
                        .unwrap_or(out)
                        .to_string(),
                ))
            }
            Some(1) => Ok(None), // unset origin/HEAD
            _ => {
                let _ = res.ensure_success()?;
                Ok(None) // unreachable: a non-zero/no-code exit always errors above
            }
        }
    }

    async fn branch_exists(&self, dir: &Path, name: &str) -> Result<bool> {
        let refname = format!("refs/heads/{name}");
        // `show-ref --verify --quiet` is an exit-code answer: 0 = exists, 1 = not.
        self.core
            .probe(
                self.core
                    .command_in(dir, ["show-ref", "--verify", "--quiet", refname.as_str()]),
            )
            .await
    }

    async fn remote_branch_exists(&self, dir: &Path, name: &str) -> Result<bool> {
        // No credential prompt, bounded wait: a missing helper or a flaky network
        // must not hang the call. `output_string` reports a timeout as a flagged result
        // (non-zero exit) rather than erroring, so an unreachable remote reads as
        // "absent" (`false`) — the best-effort answer a probe wants. A genuine
        // spawn failure (no `git`) still surfaces as an error.
        //
        // Query the *fully-qualified* ref: `ls-remote origin <name>` tail-matches
        // path components, so a bare `foo` would also match `refs/heads/bar/foo`.
        // `refs/heads/<name>` matches only the exact branch.
        let refname = format!("refs/heads/{name}");
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.extend(["ls-remote", "origin", refname.as_str()].map(String::from));
        let cmd = apply_secret_env(
            self.core
                .command_in(dir, &args)
                .env("GIT_TERMINAL_PROMPT", "0")
                .timeout(Duration::from_secs(10)),
            &envs,
        );
        let res = self.core.output_string(cmd).await?;
        Ok(res.code() == Some(0) && !res.stdout().trim().is_empty())
    }

    async fn remote_url(&self, dir: &Path, remote: &str) -> Result<String> {
        reject_flag_like("remote name", remote)?;
        self.core
            .run(self.core.command_in(dir, ["remote", "get-url", remote]))
            .await
    }

    async fn upstream(&self, dir: &Path) -> Result<Option<String>> {
        // `@{u}` resolves the configured upstream; with no upstream the command
        // exits **128** — but so does a genuine failure (detached HEAD, not a repo),
        // and git gives them all the same exit code, so a *non-zero exit* maps to
        // `None` (the documented "no upstream"). A **timeout/signal** (no exit code
        // at all), however, is a real failure and must surface — not be reported as
        // "no upstream" — so it goes through `ensure_success` like the other
        // exit-code-mapping sites.
        let res = self
            .core
            .output_string(self.core.command_in(
                dir,
                ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
            ))
            .await?;
        match res.code() {
            Some(0) => {
                let name = res.stdout().trim();
                Ok((!name.is_empty()).then(|| name.to_string()))
            }
            Some(_) => Ok(None), // any non-zero exit ⇒ no upstream configured
            None => {
                let _ = res.ensure_success()?; // timeout/signal ⇒ a real error
                Ok(None) // unreachable: ensure_success errors on a no-code outcome
            }
        }
    }

    async fn remote_branches(&self, dir: &Path, remote: &str) -> Result<Vec<String>> {
        reject_flag_like("remote name", remote)?;
        // `GIT_TERMINAL_PROMPT=0`: a remote needing credentials must fail fast,
        // never block on an interactive auth prompt. A provider, if set, supplies
        // the credential via an inline helper (token kept out of argv).
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.extend(["ls-remote", "--heads", remote].map(String::from));
        let cmd = apply_secret_env(
            self.core
                .command_in(dir, &args)
                .env("GIT_TERMINAL_PROMPT", "0"),
            &envs,
        );
        self.core.parse(cmd, parse::parse_ls_remote_heads).await
    }

    async fn is_merged(&self, dir: &Path, spec: MergeCheck) -> Result<bool> {
        reject_flag_like("branch", &spec.branch)?;
        reject_flag_like("base", &spec.base)?;
        // `--no-column` + `--no-color`: under `column.ui = always` git would pack
        // several names per line and under `color.{ui,branch} = always` it would
        // inject ANSI escapes — both even when piped, so the marker-stripping
        // compare below would never match (a false "not merged").
        let out = self
            .core
            .run(self.core.command_in(
                dir,
                [
                    "branch",
                    "--merged",
                    spec.base.as_str(),
                    "--no-column",
                    "--no-color",
                ],
            ))
            .await?;
        // Each line is a fixed 2-column marker (`  `/`* `/`+ `) then the name;
        // drop exactly those two columns rather than trimming a char class (which
        // would over-strip a name that legitimately began with the marker char).
        Ok(out
            .lines()
            .filter_map(|line| line.get(2..))
            .any(|b| b == spec.branch.as_str()))
    }

    async fn set_upstream(&self, dir: &Path, branch: &str, upstream: &str) -> Result<()> {
        reject_flag_like("branch name", branch)?;
        let flag = format!("--set-upstream-to={upstream}");
        self.core
            .run_unit(self.core.command_in(dir, ["branch", flag.as_str(), branch]))
            .await
    }

    async fn delete_branch(&self, dir: &Path, name: &str, force: bool) -> Result<()> {
        reject_flag_like("branch name", name)?;
        let flag = if force { "-D" } else { "-d" };
        self.core
            .run_unit(self.core.command_in(dir, ["branch", flag, name]))
            .await
    }

    async fn rename_branch(&self, dir: &Path, old: &str, new: &str) -> Result<()> {
        reject_flag_like("branch name", old)?;
        reject_flag_like("branch name", new)?;
        self.core
            .run_unit(self.core.command_in(dir, ["branch", "-m", old, new]))
            .await
    }

    async fn rev_list_count(&self, dir: &Path, range: &str) -> Result<usize> {
        reject_flag_like("range", range)?;
        self.core
            .try_parse(
                self.core.command_in(dir, ["rev-list", "--count", range]),
                |s| {
                    s.trim().parse::<usize>().map_err(|e| Error::Parse {
                        program: BINARY.to_string(),
                        message: e.to_string(),
                    })
                },
            )
            .await
    }

    async fn diff_range_is_empty(&self, dir: &Path, range: &str) -> Result<bool> {
        reject_flag_like("range", range)?;
        // `diff --quiet <range>`: 0 = empty range, 1 = has changes.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--quiet", range]))
            .await
    }

    async fn diff_stat(&self, dir: &Path, range: &str) -> Result<DiffStat> {
        reject_flag_like("range", range)?;
        // `LC_ALL=C`: git's `--shortstat` summary ("N file(s) changed, …") is
        // gettext-translated, but `parse_shortstat` keys on the English
        // "file"/"insertion"/"deletion" — without C locale a non-English git
        // returns an all-zero `DiffStat` rather than the real counts.
        self.core
            .parse(
                c_locale(self.core.command_in(dir, ["diff", "--shortstat", range])),
                parse::parse_shortstat,
            )
            .await
    }

    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String> {
        // The target is a single positional arg: `HEAD` for the working tree, or
        // the caller's revision/range. `-M` enables rename detection; `--no-color`
        // / `--no-ext-diff` keep the output stable and machine-parseable.
        let target = match spec {
            DiffSpec::WorkingTree => {
                // On an unborn repo `HEAD` doesn't resolve (`git diff HEAD` errors);
                // diff against the empty tree so a pre-first-commit working tree
                // still yields its additions instead of a hard failure.
                if self.is_unborn(dir).await? {
                    EMPTY_TREE.to_string()
                } else {
                    "HEAD".to_string()
                }
            }
            DiffSpec::Rev(rev) => {
                reject_flag_like("revision", &rev)?;
                rev
            }
        };
        // The explicit prefixes pin the `a/`…`b/` form the shared parser extracts
        // paths from — a user's `diff.noprefix` / `diff.mnemonicPrefix` config
        // would otherwise change the headers and make every file silently vanish
        // from the parse. (Command-line prefixes override both config options.)
        // `run_untrimmed`: trimming the diff would drop a trailing blank context
        // line, desyncing the last hunk from its `@@` line count for a consumer
        // that re-applies or re-parses it (H7).
        self.core
            .run_untrimmed(self.core.command_in(
                dir,
                [
                    "diff",
                    target.as_str(),
                    "--no-color",
                    "--no-ext-diff",
                    "-M",
                    "--src-prefix=a/",
                    "--dst-prefix=b/",
                ],
            ))
            .await
    }

    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>> {
        let text = self.diff_text(dir, spec).await?;
        Ok(parse_diff(&text))
    }

    async fn staged_is_empty(&self, dir: &Path) -> Result<bool> {
        // `diff --cached --quiet`: 0 = nothing staged, 1 = staged changes.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--cached", "--quiet"]))
            .await
    }

    async fn is_rebase_in_progress(&self, dir: &Path) -> Result<bool> {
        let git_dir = self.resolved_git_dir(dir).await?;
        // `rebase-merge/` is a merge-backend rebase. `rebase-apply/` is shared by an
        // apply-backend rebase AND `git am` — but `git am` marks it with an `applying`
        // file, so exclude that (it's an am, aborted with `am --abort`, not
        // `rebase --abort`; see `is_am_in_progress`). M20.
        let rebase_apply = git_dir.join("rebase-apply");
        let is_rebase_apply = rebase_apply.exists() && !rebase_apply.join("applying").exists();
        Ok(git_dir.join("rebase-merge").exists() || is_rebase_apply)
    }

    async fn is_am_in_progress(&self, dir: &Path) -> Result<bool> {
        // `git am` uses `rebase-apply/` with an `applying` marker file (an
        // apply-backend rebase uses the same dir *without* it).
        Ok(self
            .resolved_git_dir(dir)
            .await?
            .join("rebase-apply")
            .join("applying")
            .exists())
    }

    async fn is_merge_in_progress(&self, dir: &Path) -> Result<bool> {
        Ok(self
            .resolved_git_dir(dir)
            .await?
            .join("MERGE_HEAD")
            .exists())
    }

    async fn fetch(&self, dir: &Path) -> Result<()> {
        // `GIT_TERMINAL_PROMPT=0` so a remote needing credentials fails fast
        // rather than blocking on an interactive prompt — matching the other
        // remote ops (`fetch_branch`, `push`, `remote_branch_exists`).
        // Fetch is idempotent, so `retry` replays it on a transient failure
        // (DNS/timeout/dropped connection); a non-transient error fails at once.
        // C locale: the retry decision classifies the failure's message.
        // Leading `-c` credential.helper (+ secret env) when a provider is set.
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.extend(["fetch", "--quiet"].map(String::from));
        let cmd = apply_secret_env(
            c_locale(self.core.command_in(dir, &args))
                .env("GIT_TERMINAL_PROMPT", "0")
                // On a per-client timeout, terminate gracefully (then hard-kill
                // after a grace window) so a timed-out fetch closes cleanly.
                .timeout_grace(FETCH_TIMEOUT_GRACE)
                .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error),
            &envs,
        );
        self.core.run_unit(cmd).await
    }

    async fn fetch_from(&self, dir: &Path, remote: &str) -> Result<()> {
        // A leading-`-` remote is a bare positional here — and a flag like
        // `--upload-pack=<cmd>` would run an arbitrary local program for a
        // local/ext transport, so this guard is load-bearing for security.
        reject_flag_like("remote", remote)?;
        // Same containment as `fetch` (prompt off, C locale, transient retry,
        // optional credential helper), with the remote named explicitly.
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.extend(["fetch", "--quiet", remote].map(String::from));
        let cmd = apply_secret_env(
            c_locale(self.core.command_in(dir, &args))
                .env("GIT_TERMINAL_PROMPT", "0")
                .timeout_grace(FETCH_TIMEOUT_GRACE)
                .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error),
            &envs,
        );
        self.core.run_unit(cmd).await
    }

    async fn fetch_branch(&self, dir: &Path, branch: &str) -> Result<()> {
        let refspec = format!("refs/heads/{branch}:refs/remotes/origin/{branch}");
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.extend(["fetch", "--quiet", "origin", refspec.as_str()].map(String::from));
        let cmd = apply_secret_env(
            c_locale(self.core.command_in(dir, &args))
                .env("GIT_TERMINAL_PROMPT", "0")
                .timeout_grace(FETCH_TIMEOUT_GRACE)
                .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error),
            &envs,
        );
        self.core.run_unit(cmd).await
    }

    async fn push(&self, dir: &Path, spec: GitPush) -> Result<()> {
        reject_flag_like("remote", &spec.remote)?;
        reject_flag_like("refspec", &spec.refspec)?;
        // M16: `reject_flag_like` catches a leading `-`/empty/NUL, but not the refspec
        // metacharacters that silently change what a push *does* — a leading `+`
        // (force-push, overwriting the remote non-fast-forward) or an extra `:` (push
        // to an unexpected remote ref). A valid refspec here is `branch` or
        // `local:remote_branch` (the single `:` is API-constructed by
        // `GitPush::refspec`), so allow at most one `:` and no leading `+` on either
        // side. A caller who genuinely needs a force-push must do it explicitly via
        // `run(["push", "--force", …])`, not smuggle a `+` through a branch name.
        let sides: Vec<&str> = spec.refspec.split(':').collect();
        if sides.len() > 2 || sides.iter().any(|s| s.starts_with('+')) {
            return Err(processkit::Error::Spawn {
                program: BINARY.to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!(
                        "push refspec {:?} contains a force (`+`) or multi-ref (`:`) \
                         metacharacter — pass a plain branch or `local:remote`, or use \
                         `run([\"push\", …])` for a force-push",
                        spec.refspec
                    ),
                ),
            });
        }
        let (pre, envs) = self.remote_credentials(None).await?;
        let mut args: Vec<String> = pre;
        args.push("push".to_string());
        if spec.set_upstream {
            args.push("-u".to_string());
        }
        args.push(spec.remote.clone());
        args.push(spec.refspec.clone());
        let cmd = apply_secret_env(
            self.core
                .command_in(dir, &args)
                .env("GIT_TERMINAL_PROMPT", "0")
                // On a per-client timeout, terminate gracefully (then hard-kill
                // after a grace window) so a timed-out push releases its lock and
                // doesn't leave the remote ref half-updated. No-op without a
                // deadline (matches `fetch`).
                .timeout_grace(FETCH_TIMEOUT_GRACE),
            &envs,
        );
        self.core.run_unit(cmd).await
    }

    async fn merge_squash(&self, dir: &Path, branch: &str) -> Result<()> {
        reject_flag_like("branch", branch)?;
        // C locale: a conflict's output feeds `is_merge_conflict` (same reason as
        // `merge_commit`/`merge_no_commit`). `--squash` never commits, so no editor.
        self.core
            .run_unit(c_locale(
                self.core.command_in(dir, ["merge", "--squash", branch]),
            ))
            .await
    }

    async fn merge_commit(&self, dir: &Path, spec: MergeCommit) -> Result<()> {
        reject_flag_like("branch", &spec.branch)?;
        let mut args: Vec<&str> = vec!["merge"];
        if spec.no_ff {
            args.push("--no-ff");
        }
        if let Some(msg) = spec.message.as_deref() {
            args.push("-m");
            args.push(msg);
        } else {
            // No message → take the default merge message non-interactively
            // instead of opening `$EDITOR` (which would hang a headless caller).
            args.push("--no-edit");
        }
        args.push(&spec.branch);
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(c_locale(self.core.command_in(dir, args)))
            .await
    }

    async fn merge_no_commit(&self, dir: &Path, spec: MergeNoCommit) -> Result<()> {
        reject_flag_like("branch", &spec.branch)?;
        let mut args: Vec<&str> = vec!["merge", "--no-commit"];
        // `--squash` and `--no-ff` are mutually exclusive (git rejects the pair);
        // a squash never fast-forwards anyway, so it takes precedence.
        if spec.squash {
            args.push("--squash");
        } else if spec.no_ff {
            args.push("--no-ff");
        }
        args.push(&spec.branch);
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(c_locale(self.core.command_in(dir, args)))
            .await
    }

    async fn merge_abort(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["merge", "--abort"])))
            .await
    }

    async fn merge_continue(&self, dir: &Path) -> Result<()> {
        // `--no-edit` already reuses the prepared MERGE_MSG; `no_editor` is a
        // headless backstop so a commit hook re-opening the editor can't hang.
        // C locale: the failure output feeds the classifiers (a still-conflicted
        // tree reports "nothing to commit"-adjacent / conflict messages).
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["commit", "--no-edit"]),
            )))
            .await
    }

    async fn reset_merge(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["reset", "--merge"]))
            .await
    }

    async fn reset_hard(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        self.core
            .run_unit(self.core.command_in(dir, ["reset", "--hard", rev]))
            .await
    }

    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()> {
        reject_flag_like("rebase target", onto)?;
        // Force a no-op editor so a rebase that would open `$EDITOR` (reword, or
        // the message-confirm on `--continue`) never hangs a headless caller.
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", onto]),
            )))
            .await
    }

    async fn rebase_abort(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["rebase", "--abort"])))
            .await
    }

    async fn am_abort(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["am", "--abort"])))
            .await
    }

    async fn rebase_continue(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", "--continue"]),
            )))
            .await
    }

    async fn stash_push(&self, dir: &Path, include_untracked: bool) -> Result<()> {
        let mut command = self.core.command_in(dir, ["stash", "push"]);
        if include_untracked {
            command = command.arg("--include-untracked");
        }
        self.core.run_unit(command).await
    }

    async fn stash_pop(&self, dir: &Path) -> Result<()> {
        // C locale: a conflicting `stash pop` emits git's merge-machinery
        // `CONFLICT (...)` output, which feeds `is_merge_conflict` (e.g. via
        // `switch_with_stash`) — a translated message would defeat it.
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["stash", "pop"])))
            .await
    }

    async fn worktree_list(&self, dir: &Path) -> Result<Vec<Worktree>> {
        self.core
            .parse(
                self.core
                    .command_in(dir, ["worktree", "list", "--porcelain"]),
                parse::parse_worktree_porcelain,
            )
            .await
    }

    async fn worktree_add(&self, dir: &Path, spec: WorktreeAdd) -> Result<()> {
        if let Some(name) = spec.new_branch.as_deref() {
            reject_flag_like("branch name", name)?;
        }
        if let Some(commitish) = spec.commitish.as_deref() {
            reject_flag_like("commit-ish", commitish)?;
        }
        let mut command = self.core.command_in(dir, ["worktree", "add"]);
        if let Some(name) = spec.new_branch.as_deref() {
            command = command.arg("-b").arg(name);
        }
        if spec.no_checkout {
            command = command.arg("--no-checkout");
        }
        command = command.arg(&spec.path);
        if let Some(commitish) = spec.commitish.as_deref() {
            command = command.arg(commitish);
        }
        self.core.run_unit(command).await
    }

    async fn worktree_remove(&self, dir: &Path, path: &Path, force: bool) -> Result<()> {
        let mut command = self.core.command_in(dir, ["worktree", "remove"]);
        if force {
            command = command.arg("--force");
        }
        command = command.arg(path);
        self.core.run_unit(command).await
    }

    async fn worktree_move(&self, dir: &Path, from: &Path, to: &Path) -> Result<()> {
        let command = self
            .core
            .command_in(dir, ["worktree", "move"])
            .arg(from)
            .arg(to);
        self.core.run_unit(command).await
    }

    async fn worktree_prune(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["worktree", "prune"]))
            .await
    }

    async fn clone_repo(&self, url: &str, dest: &Path, spec: CloneSpec) -> Result<()> {
        // A leading-`-` url is a bare positional — `git clone --upload-pack=<cmd>`
        // would run an arbitrary local program. A real URL never leads with `-`,
        // so this guard has no false positives.
        reject_flag_like("url", url)?;
        // No working directory: clone creates `dest` itself, so `dest` should
        // be absolute (a relative path would resolve against this process' cwd).
        // Leading `-c` credential.helper (+ secret env) when a provider is set,
        // scoped to the clone URL's host so a cross-host redirect/submodule during
        // the clone can't extract the token (the URL is often externally supplied).
        let (pre, envs) = self
            .remote_credentials(vcs_cli_support::https_host(url).as_deref())
            .await?;
        let mut initial: Vec<String> = pre;
        initial.push("clone".to_string());
        let mut command = self.core.command(&initial);
        if let Some(branch) = spec.branch.as_deref() {
            command = command.arg("--branch").arg(branch);
        }
        if let Some(depth) = spec.depth {
            command = command.arg("--depth").arg(depth.to_string());
        }
        if spec.bare {
            command = command.arg("--bare");
        }
        let command = apply_secret_env(
            command
                .arg(url)
                .arg(dest)
                .env("GIT_TERMINAL_PROMPT", "0")
                // On a per-client timeout, terminate gracefully (then hard-kill after
                // a grace window). No-op without a deadline (matches `fetch`).
                .timeout_grace(FETCH_TIMEOUT_GRACE),
            &envs,
        );

        // R7: git populates `dest` incrementally, so a failed clone (timeout, network,
        // auth) can leave a **partial, non-empty** `dest` that blocks a retry with
        // "destination path already exists and is not empty". `timeout_grace` alone
        // can't prevent it — Windows' job-kill is atomic (no graceful tier) and the
        // Unix grace is too short to delete a multi-GB partial. So clean it ourselves.
        //
        // Only clean a `dest` we could have *created*: absent, or an empty directory.
        // git refuses to clone into a **non-empty** existing dir, so a non-empty `dest`
        // means the failure was that refusal and the caller's data is untouched — never
        // delete that. (A best-effort blocking remove on the error path; a partial clone
        // may be large, but this path is rare.)
        let cleanable = match std::fs::read_dir(dest) {
            Err(_) => true,                              // absent/unreadable → clone creates it
            Ok(mut entries) => entries.next().is_none(), // an empty directory
        };
        let result = self.core.run_unit(command).await;
        if result.is_err() && cleanable {
            let _ = std::fs::remove_dir_all(dest);
        }
        result
    }

    async fn tag_create(&self, dir: &Path, name: &str, rev: Option<String>) -> Result<()> {
        reject_flag_like("tag name", name)?;
        if let Some(rev) = rev.as_deref() {
            reject_flag_like("revision", rev)?;
        }
        let mut args = vec!["tag", name];
        if let Some(rev) = rev.as_deref() {
            args.push(rev);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn tag_create_annotated(&self, dir: &Path, spec: AnnotatedTag) -> Result<()> {
        reject_flag_like("tag name", &spec.name)?;
        if let Some(rev) = spec.rev.as_deref() {
            reject_flag_like("revision", rev)?;
        }
        let mut args = vec!["tag", "-a", &spec.name, "-m", &spec.message];
        if let Some(rev) = spec.rev.as_deref() {
            args.push(rev);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn tag_list(&self, dir: &Path) -> Result<Vec<String>> {
        // `--no-column`: a user's `column.ui = always` would pack several tags
        // onto one line even when piped, corrupting the one-per-line split.
        let out = self
            .core
            .run(self.core.command_in(dir, ["tag", "--list", "--no-column"]))
            .await?;
        Ok(out.lines().map(str::to_string).collect())
    }

    async fn tag_delete(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("tag name", name)?;
        self.core
            .run_unit(self.core.command_in(dir, ["tag", "-d", name]))
            .await
    }

    async fn show_file(&self, dir: &Path, rev: &str, path: &str) -> Result<String> {
        // A leading-`-` rev makes the whole `<rev>:<path>` token start with `-`,
        // so git would parse it as a flag — guard it before building the spec.
        reject_flag_like("revision", rev)?;
        // git rejects backslash separators in the `<rev>:<path>` spec ("exists
        // on disk, but not in <rev>") — normalise for Windows callers. Only on
        // Windows: on Unix a backslash is a legal filename byte, and rewriting
        // it would make a literal `a\b.txt` unresolvable.
        #[cfg(windows)]
        let path = path.replace('\\', "/");
        let spec = format!("{rev}:{path}");
        // `run_untrimmed`: a blob's trailing newline(s) are part of its content —
        // trimming them corrupts a read-modify-write round-trip (H7).
        self.core
            .run_untrimmed(self.core.command_in(dir, ["show", spec.as_str()]))
            .await
    }

    async fn config_get(&self, dir: &Path, key: &str) -> Result<Option<String>> {
        reject_flag_like("config key", key)?;
        let res = self
            .core
            .output_string(self.core.command_in(dir, ["config", "--get", key]))
            .await?;
        match res.code() {
            // Exit 1 = unset (git lumps "no such key/section" in here too).
            Some(1) => Ok(None),
            // Strip only git's trailing line terminator (`\n`, or `\r\n`), not all
            // trailing whitespace: a config value can legitimately end in spaces or
            // a tab (e.g. a templated prefix), and `--get` returns a single line, so
            // it never itself ends in a newline.
            Some(0) => Ok(Some(
                res.stdout().trim_end_matches(['\r', '\n']).to_string(),
            )),
            _ => {
                let _ = res.ensure_success()?;
                Ok(None) // unreachable: a non-zero exit always errors above.
            }
        }
    }

    async fn config_set(&self, dir: &Path, key: &str, value: &str) -> Result<()> {
        reject_flag_like("config key", key)?;
        self.core
            .run_unit(self.core.command_in(dir, ["config", key, value]))
            .await
    }

    async fn remote_add(&self, dir: &Path, name: &str, url: &str) -> Result<()> {
        reject_flag_like("remote name", name)?;
        reject_flag_like("url", url)?;
        self.core
            .run_unit(self.core.command_in(dir, ["remote", "add", name, url]))
            .await
    }

    async fn remote_set_url(&self, dir: &Path, name: &str, url: &str) -> Result<()> {
        reject_flag_like("remote name", name)?;
        reject_flag_like("url", url)?;
        self.core
            .run_unit(self.core.command_in(dir, ["remote", "set-url", name, url]))
            .await
    }

    async fn blame(&self, dir: &Path, path: &str, rev: Option<String>) -> Result<Vec<BlameLine>> {
        let mut args = vec!["blame", "--line-porcelain"];
        if let Some(rev) = rev.as_deref() {
            // A standalone positional rev with a leading `-` would be any blame
            // flag (`-s`, `--reverse`, `-L…`) — guard before the `--`.
            reject_flag_like("revision", rev)?;
            args.push(rev);
        }
        args.push("--");
        args.push(path);
        self.core
            .parse(
                self.core.command_in(dir, args),
                parse::parse_blame_porcelain,
            )
            .await
    }

    async fn cherry_pick(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        // No editor opens non-interactively, but keep the headless backstop.
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["cherry-pick", rev]),
            )))
            .await
    }

    async fn revert(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["revert", "--no-edit", rev]),
            )))
            .await
    }

    async fn rebase_skip(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", "--skip"]),
            )))
            .await
    }
}

// --- Internal helpers --------------------------------------------------------
//
// The error classifiers (`is_merge_conflict`/`is_nothing_to_commit`/
// `is_transient_fetch_error`), the fetch-retry policy, and the argv injection
// guard now live in the shared `vcs-cli-support` crate (re-exported at the top of
// this module); what remains here is git-specific.

/// Git's well-known empty-tree object id — a stable stand-in for `HEAD` when
/// diffing the working tree of an unborn (no-commits-yet) repository. Public so a
/// caller can diff/stat a pre-first-commit working tree against it directly.
pub const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// Total attempts / fixed backoff for a transient-retried `fetch` — the shared
/// policy from `vcs-cli-support`, aliased so the retry call sites read locally.
const FETCH_ATTEMPTS: u32 = vcs_cli_support::FETCH_ATTEMPTS;
const FETCH_BACKOFF: Duration = vcs_cli_support::FETCH_BACKOFF;
const FETCH_TIMEOUT_GRACE: Duration = vcs_cli_support::FETCH_TIMEOUT_GRACE;

/// Point git's editor at a no-op so any command that would open `$EDITOR`
/// (a rebase reword, the message-confirm on `rebase --continue`) succeeds
/// non-interactively instead of hanging a headless caller.
fn no_editor(cmd: processkit::Command) -> processkit::Command {
    cmd.env("GIT_EDITOR", "true")
        .env("GIT_SEQUENCE_EDITOR", "true")
}

/// Force the C locale on a command whose output feeds the error classifiers
/// (`is_merge_conflict`, `is_nothing_to_commit`, `is_transient_fetch_error`):
/// they match untranslated English substrings, and a localized git would emit
/// translated messages, silently turning a classified failure (conflict /
/// clean-tree / transient) into an unclassified one.
fn c_locale(cmd: processkit::Command) -> processkit::Command {
    cmd.env("LC_ALL", "C")
}

/// Injection guard for bare positional argv slots — delegates to the shared
/// [`vcs_cli_support::reject_flag_like`], naming this crate's binary so the
/// ~45 call sites stay `reject_flag_like(what, value)`.
fn reject_flag_like(what: &str, value: &str) -> Result<()> {
    vcs_cli_support::reject_flag_like(BINARY, what, value)
}

impl<R: ProcessRunner> Git<R> {
    /// Run `git <args>` over string slices — `git.run_args(&["status", "-s"])`
    /// without allocating a `Vec<String>`. Inherent (not on the object-safe
    /// trait), so it can take `&[&str]`; forwards to the same path as
    /// [`GitApi::run`].
    pub async fn run_args(&self, args: &[&str]) -> Result<String> {
        self.core.run(args).await
    }

    /// Like [`run_args`](Git::run_args) but never errors on a non-zero exit
    /// (mirrors [`GitApi::run_raw`]).
    pub async fn run_raw_args(&self, args: &[&str]) -> Result<ProcessResult<String>> {
        self.core.output_string(args).await
    }

    /// Bind this client to `dir`, returning a [`GitAt`] handle whose methods omit
    /// the `dir` argument: `git.at(dir).status()` runs [`status`](GitApi::status)
    /// against `dir`. The dir-taking [`GitApi`] methods stay on [`Git`] for
    /// driving many directories (e.g. linked worktrees) from one client.
    pub fn at<'a>(&'a self, dir: &'a Path) -> GitAt<'a, R> {
        GitAt { git: self, dir }
    }

    /// Harden this client for driving repositories it didn't create: running
    /// `git` inside an untrusted checkout executes that repository's hooks and
    /// honours its config — arbitrary code execution by default. The profile
    /// (applied to **every** command this client runs):
    ///
    /// **⚠ Requires git ≥ 2.31.** The hook / `fsmonitor` / `sshCommand` pins ride
    /// git's env-based config (`GIT_CONFIG_COUNT`), which older git **silently
    /// ignores** — so on git < 2.31 `harden()` still scrubs the environment and
    /// turns prompts off, but repo-local hooks/fsmonitor/sshCommand are **not**
    /// disabled (no error is raised). There is **no built-in 2.31 gate yet**
    /// ([`capabilities().ensure_supported()`](GitCapabilities::ensure_supported)
    /// only checks the major version, so it passes on 2.0–2.30). Before relying on
    /// `harden()` against a fully untrusted repo on a host you don't control, check
    /// the version yourself — `Git::new().capabilities().await?.version` exposes
    /// `major`/`minor` — and require ≥ 2.31, or add an OS-level sandbox. (A
    /// machine-checked minor-version floor is tracked for a future release; see
    /// `docs/audit-2026-07.md` H3.)
    ///
    /// - **Disables hooks** — `core.hooksPath=/dev/null` pinned via git's
    ///   env-based config (`GIT_CONFIG_COUNT`/`KEY_n`/`VALUE_n`, git ≥ 2.31;
    ///   verified to suppress hooks on Windows too) — and `core.fsmonitor`
    ///   (a config-driven daemon launch). Env-config overrides even the
    ///   *repo-local* `.git/config` for the keys it names, so these pins beat a
    ///   poisoned `.git/config`.
    /// - **Neutralizes `core.sshCommand`** (pinned empty) — the config-key twin of
    ///   the scrubbed `GIT_SSH_COMMAND`, an arbitrary program git would run for the
    ///   SSH transport. Empty is falsy to git, so the default `ssh` (ambient
    ///   `~/.ssh/config`/agent) still works; only the repo's override is dropped.
    /// - **Removes inherited repo redirectors** so a poisoned parent
    ///   environment can't point commands at another repository: `GIT_DIR`,
    ///   `GIT_WORK_TREE`, `GIT_INDEX_FILE`, `GIT_COMMON_DIR`,
    ///   `GIT_OBJECT_DIRECTORY`, `GIT_ALTERNATE_OBJECT_DIRECTORIES`,
    ///   `GIT_NAMESPACE`, `GIT_CEILING_DIRECTORIES`, `GIT_CONFIG_PARAMETERS`,
    ///   `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`. (The first seven are also
    ///   scrubbed by *every* client — see the type-level doc — not just here.)
    /// - **Removes inherited command hooks** that make git spawn an arbitrary
    ///   program from the *environment* (a second code-execution path besides
    ///   repo hooks): `GIT_SSH_COMMAND`/`GIT_SSH` (transport), `GIT_ASKPASS`
    ///   (credential prompt), `GIT_EXTERNAL_DIFF` (diff driver), `GIT_PAGER`,
    ///   `GIT_EDITOR`/`GIT_SEQUENCE_EDITOR`, `GIT_PROXY_COMMAND` (a program for a
    ///   `git://` connection), `GIT_EXEC_PATH` (relocates git's own sub-commands),
    ///   and `GIT_TEMPLATE_DIR` (seeds hooks/config on `init`/`clone`). It also drops
    ///   the pathspec-mode vars (`GIT_LITERAL_PATHSPECS` / `GIT_GLOB_PATHSPECS` /
    ///   `GIT_NOGLOB_PATHSPECS` / `GIT_ICASE_PATHSPECS`), which silently change which
    ///   paths a command matches. The library's own auth seam
    ///   ([`with_credentials`](Git::with_credentials)) injects credentials via a
    ///   git `credential.helper` / token env, **not** these variables, so it keeps
    ///   working through a hardened client; an operator who deliberately relies on
    ///   an ambient `GIT_SSH_COMMAND`/`GIT_ASKPASS` should inject it per-call
    ///   instead of inheriting it into an untrusted-repo run.
    /// - **Skips system config** (`GIT_CONFIG_NOSYSTEM=1`) and keeps terminal
    ///   prompts off everywhere (`GIT_TERMINAL_PROMPT=0`).
    ///
    /// **Residual repo-local-config vectors (NOT neutralized).** `harden()` closes
    /// the *hooks*, `fsmonitor`, `core.sshCommand`, and the env redirector/command-
    /// hook paths — but a few **repo-local `.git/config` / `.gitattributes`** keys
    /// still run an arbitrary program and are not pinned: `filter.<drv>.clean`/
    /// `smudge` (run on any working-tree materialization — `checkout`, `stash pop`,
    /// `worktree add`), and `diff.<drv>.textconv` / `diff.external` (run when a diff
    /// is produced; [`diff_text`](GitApi::diff_text) defends itself with
    /// `--no-ext-diff`, but other diff/blame reads do not). So for a **fully
    /// untrusted** repo, do not materialize its working tree or run diffs through a
    /// hardened client without an OS-level sandbox — `harden()` is hardening, not a
    /// sandbox.
    ///
    /// What it does NOT do beyond that: sandbox the git binary itself, or stop the
    /// repo's *content* from being malicious. In a **colocated jj repo**, git hooks
    /// only run when *git* commands run — harden the `Git` client; `Jj` needs
    /// no equivalent (jj has no repo-local hooks; see the vcs-jj docs).
    ///
    /// Chainable — `Git::with_runner(rec).harden()` works in tests; use
    /// [`Git::hardened()`](Git::hardened) for the common case.
    pub fn harden(self) -> Self {
        let removed = [
            // Repo redirectors — point git at another repo/index/object store.
            // (`GIT_DIR`…`GIT_NAMESPACE` are also scrubbed by *every* client via the
            // `managed_client!` `scrub_env`; re-listed here so the hardened profile is
            // self-contained and its double-removal is harmless.)
            "GIT_DIR",
            "GIT_WORK_TREE",
            "GIT_INDEX_FILE",
            "GIT_COMMON_DIR",
            "GIT_OBJECT_DIRECTORY",
            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
            "GIT_NAMESPACE",
            "GIT_CEILING_DIRECTORIES",
            "GIT_CONFIG_PARAMETERS",
            "GIT_CONFIG_GLOBAL",
            "GIT_CONFIG_SYSTEM",
            // Command hooks — make git spawn an arbitrary program from the env.
            "GIT_SSH_COMMAND",
            "GIT_SSH",
            "GIT_ASKPASS",
            "GIT_EXTERNAL_DIFF",
            "GIT_PAGER",
            "GIT_EDITOR",
            "GIT_SEQUENCE_EDITOR",
            // More env command-hooks (M14): `GIT_PROXY_COMMAND` runs an arbitrary
            // program for a `git://` connection; `GIT_EXEC_PATH` relocates where git
            // finds its own sub-commands (so `git-<x>` becomes attacker-chosen);
            // `GIT_TEMPLATE_DIR` seeds hooks/config into a repo on `init`/`clone`.
            "GIT_PROXY_COMMAND",
            "GIT_EXEC_PATH",
            "GIT_TEMPLATE_DIR",
            // Pathspec interpretation (M14) — not code-execution, but they silently
            // change which paths a command matches, so pin deterministic behavior.
            "GIT_LITERAL_PATHSPECS",
            "GIT_GLOB_PATHSPECS",
            "GIT_NOGLOB_PATHSPECS",
            "GIT_ICASE_PATHSPECS",
        ];
        let mut hardened = self;
        for key in removed {
            hardened = hardened.default_env_remove(key);
        }
        hardened
            .default_env("GIT_CONFIG_NOSYSTEM", "1")
            .default_env("GIT_TERMINAL_PROMPT", "0")
            // Env-config (`GIT_CONFIG_COUNT`/`KEY_n`/`VALUE_n`) overrides even the
            // *repo-local* `.git/config` for the keys it names — so these pins beat
            // a poisoned `.git/config`, which `GIT_CONFIG_NOSYSTEM` (system) and the
            // scrubbed `GIT_CONFIG_GLOBAL` (global) do not reach.
            .default_env("GIT_CONFIG_COUNT", "3")
            .default_env("GIT_CONFIG_KEY_0", "core.hooksPath")
            // `/dev/null` as the hooks dir disables hooks on every platform,
            // Windows included: git looks for `<hooksPath>/<hook-name>`, and no
            // such file can exist under `/dev/null` (it is not a directory), so the
            // lookup always misses and no hook runs. A literal POSIX path is fine
            // on Windows here — it is used as a path *prefix* to probe, never
            // opened — and it reads unambiguously as "nowhere."
            .default_env("GIT_CONFIG_VALUE_0", "/dev/null")
            .default_env("GIT_CONFIG_KEY_1", "core.fsmonitor")
            .default_env("GIT_CONFIG_VALUE_1", "false")
            // Neutralize a repo-local `core.sshCommand` (an arbitrary program git
            // runs for the SSH transport on fetch/push/clone) — the config-key twin
            // of the scrubbed `GIT_SSH_COMMAND` env var. An empty value is falsy to
            // git, so it falls back to the default `ssh` (ambient `~/.ssh/config` /
            // agent still work); only the repo's override is dropped.
            .default_env("GIT_CONFIG_KEY_2", "core.sshCommand")
            .default_env("GIT_CONFIG_VALUE_2", "")
    }

    /// Switch to `branch`, carrying uncommitted changes (tracked *and*
    /// untracked) across via the stash: `stash push -u` → `checkout` →
    /// `stash pop --index`. `--index` restores the staged/unstaged split faithfully
    /// (a bare `pop` returns everything unstaged). A clean tree skips the round-trip;
    /// and because `stash push` can exit 0 having saved **nothing** (e.g. a
    /// submodule-only change), the stash-list depth is checked around the push so a
    /// no-op push doesn't leave the later pop grabbing an older, unrelated stash.
    ///
    /// **Single-actor contract:** this assumes no other process pushes or pops a
    /// stash in the same repository between this call's own `stash push` and `pop`.
    ///
    /// Failure behaviour:
    /// - `checkout` fails (atomic — the working copy stays on the original
    ///   branch): the stash is popped back to restore the original state, and
    ///   the checkout error is returned. If that restoring pop *also* fails,
    ///   the changes stay safe in the stash (`git stash list`).
    /// - `stash pop` on the target branch conflicts: the error is returned with
    ///   the target branch checked out; git keeps the stash entry, so the
    ///   changes can be resolved or re-applied manually.
    ///
    /// Inherent (not on the object-safe trait): a composed operation, not a 1:1
    /// CLI verb — mock the underlying `status`/`stash_*`/`checkout` instead.
    pub async fn switch_with_stash(&self, dir: &Path, branch: &str) -> Result<()> {
        // Untracked-inclusive guard to match `stash push -u`: "dirty" must mean
        // the same thing to the guard and to the stash. Fast path for a clean tree.
        if self.status(dir).await?.is_empty() {
            return self.checkout(dir, branch).await;
        }
        // `stash push` exits 0 having saved **nothing** when the only dirt is
        // unstashable (e.g. a submodule-only change that `status` still reports), so a
        // bare `stash pop` afterwards would splat an UNRELATED pre-existing stash — data
        // loss. Bracket the push with the stash-list depth to learn whether it actually
        // saved, and only pop when it did. (Single-actor contract: a concurrent
        // `stash push`/`pop` by another process between our two calls is out of scope.)
        let depth_before = self.stash_depth(dir).await?;
        self.stash_push(dir, true).await?;
        if self.stash_depth(dir).await? <= depth_before {
            // Nothing was stashed — switch as-is rather than pop someone else's entry.
            return self.checkout(dir, branch).await;
        }
        // `--index` restores the staged/unstaged split faithfully; a bare `pop` would
        // bring everything back UNSTAGED, silently flattening the index.
        match self.checkout(dir, branch).await {
            Ok(()) => self.stash_pop_index(dir).await,
            Err(err) => {
                // A failed checkout is atomic — we are still on the original branch, so
                // popping restores the exact pre-call state. If the pop fails too, the
                // stash entry is preserved for the caller.
                let _ = self.stash_pop_index(dir).await;
                Err(err)
            }
        }
    }

    /// The number of entries in the stash list (`git stash list`) — used by
    /// [`switch_with_stash`](Git::switch_with_stash) to tell whether a `stash push`
    /// actually saved anything.
    async fn stash_depth(&self, dir: &Path) -> Result<usize> {
        let out = self
            .core
            .run(self.core.command_in(dir, ["stash", "list"]))
            .await?;
        Ok(out.lines().filter(|l| !l.is_empty()).count())
    }

    /// `git stash pop --index` — restore the top stash *preserving* the staged/unstaged
    /// split (a bare `pop` returns everything unstaged). C locale so a conflicting pop's
    /// `CONFLICT (...)` output still feeds `is_merge_conflict`.
    async fn stash_pop_index(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(
                self.core.command_in(dir, ["stash", "pop", "--index"]),
            ))
            .await
    }

    /// `git_dir` resolved to an absolute path — `rev-parse --git-dir` may report
    /// it relative to `dir` (e.g. `.git`), which the filesystem probes need joined.
    async fn resolved_git_dir(&self, dir: &Path) -> Result<PathBuf> {
        let git_dir = PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-dir"]))
                .await?,
        );
        Ok(if git_dir.is_absolute() {
            git_dir
        } else {
            dir.join(git_dir)
        })
    }
}

impl Git {
    /// A hardened real (job-backed) client — `Git::new().harden()`; see
    /// [`harden`](Git::harden) for what the profile does.
    pub fn hardened() -> Self {
        Self::new().harden()
    }
}

/// A [`Git`] client with a working directory bound, so calls drop the leading
/// `dir` argument — `git.at(dir).status()` is `git.status(dir)`. Construct one
/// with [`Git::at`] (or, through the facade, `vcs_core::Repo::git_at`). Cheap to
/// copy: it only borrows the client and the path.
pub struct GitAt<'a, R: ProcessRunner = processkit::JobRunner> {
    git: &'a Git<R>,
    dir: &'a Path,
}

// Hand-written rather than derived: the view only holds two references, so it is
// `Copy` for *every* runner. `#[derive(Copy)]` would add a spurious `R: Copy`
// bound that the real default `JobRunner` doesn't satisfy, silently dropping
// `Copy` on the production `Repo::git_at()` handle.
impl<R: ProcessRunner> Clone for GitAt<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<R: ProcessRunner> Copy for GitAt<'_, R> {}

// Generate [`GitAt`] forwarders from a method list: `bare` methods forward
// verbatim, `dir` methods inject `self.dir` as the first argument. The shared
// macro lives in `vcs-cli-support` (see `vcs_cli_support::at_forwarders!`).
vcs_cli_support::at_forwarders! {
    GitAt, git, "Git",
    bare {
        fn run(args: &[String]) -> Result<String>;
        fn run_raw(args: &[String]) -> Result<ProcessResult<String>>;
        fn run_args(args: &[&str]) -> Result<String>;
        fn run_raw_args(args: &[&str]) -> Result<ProcessResult<String>>;
        fn version() -> Result<String>;
        fn capabilities() -> Result<GitCapabilities>;
        fn clone_repo(url: &str, dest: &Path, spec: CloneSpec) -> Result<()>;
    }
    dir {
        fn status() -> Result<Vec<StatusEntry>>;
        fn status_text() -> Result<String>;
        fn status_tracked() -> Result<Vec<StatusEntry>>;
        fn branch_status() -> Result<BranchStatus>;
        fn conflicted_files() -> Result<Vec<String>>;
        fn current_branch() -> Result<Option<String>>;
        fn branches() -> Result<Vec<Branch>>;
        fn log(revspec: &str, max: usize) -> Result<Vec<Commit>>;
        fn rev_parse(rev: &str) -> Result<String>;
        fn rev_parse_short(rev: &str) -> Result<String>;
        fn init() -> Result<()>;
        fn add(paths: &[PathBuf]) -> Result<()>;
        fn commit(message: &str) -> Result<()>;
        fn create_branch(name: &str) -> Result<()>;
        fn checkout(reference: &str) -> Result<()>;
        fn checkout_detach(commit: &str) -> Result<()>;
        fn commit_paths(spec: CommitPaths) -> Result<()>;
        fn last_commit_message() -> Result<String>;
        fn is_unborn() -> Result<bool>;
        fn diff_is_empty() -> Result<bool>;
        fn common_dir() -> Result<PathBuf>;
        fn git_dir() -> Result<PathBuf>;
        fn resolve_commit(rev: &str) -> Result<String>;
        fn remote_head_branch() -> Result<Option<String>>;
        fn branch_exists(name: &str) -> Result<bool>;
        fn remote_branch_exists(name: &str) -> Result<bool>;
        fn remote_url(remote: &str) -> Result<String>;
        fn upstream() -> Result<Option<String>>;
        fn remote_branches(remote: &str) -> Result<Vec<String>>;
        fn is_merged(spec: MergeCheck) -> Result<bool>;
        fn set_upstream(branch: &str, upstream: &str) -> Result<()>;
        fn delete_branch(name: &str, force: bool) -> Result<()>;
        fn rename_branch(old: &str, new: &str) -> Result<()>;
        fn rev_list_count(range: &str) -> Result<usize>;
        fn diff_range_is_empty(range: &str) -> Result<bool>;
        fn diff_stat(range: &str) -> Result<DiffStat>;
        fn diff_text(spec: DiffSpec) -> Result<String>;
        fn diff(spec: DiffSpec) -> Result<Vec<FileDiff>>;
        fn staged_is_empty() -> Result<bool>;
        fn is_rebase_in_progress() -> Result<bool>;
        fn is_merge_in_progress() -> Result<bool>;
        fn is_am_in_progress() -> Result<bool>;
        fn fetch() -> Result<()>;
        fn fetch_from(remote: &str) -> Result<()>;
        fn fetch_branch(branch: &str) -> Result<()>;
        fn push(spec: GitPush) -> Result<()>;
        fn merge_squash(branch: &str) -> Result<()>;
        fn merge_commit(spec: MergeCommit) -> Result<()>;
        fn merge_no_commit(spec: MergeNoCommit) -> Result<()>;
        fn merge_abort() -> Result<()>;
        fn merge_continue() -> Result<()>;
        fn reset_merge() -> Result<()>;
        fn reset_hard(rev: &str) -> Result<()>;
        fn rebase(onto: &str) -> Result<()>;
        fn rebase_abort() -> Result<()>;
        fn am_abort() -> Result<()>;
        fn rebase_continue() -> Result<()>;
        fn stash_push(include_untracked: bool) -> Result<()>;
        fn stash_pop() -> Result<()>;
        fn switch_with_stash(branch: &str) -> Result<()>;
        fn worktree_list() -> Result<Vec<Worktree>>;
        fn worktree_add(spec: WorktreeAdd) -> Result<()>;
        fn worktree_remove(path: &Path, force: bool) -> Result<()>;
        fn worktree_move(from: &Path, to: &Path) -> Result<()>;
        fn worktree_prune() -> Result<()>;
        fn tag_create(name: &str, rev: Option<String>) -> Result<()>;
        fn tag_create_annotated(spec: AnnotatedTag) -> Result<()>;
        fn tag_list() -> Result<Vec<String>>;
        fn tag_delete(name: &str) -> Result<()>;
        fn show_file(rev: &str, path: &str) -> Result<String>;
        fn config_get(key: &str) -> Result<Option<String>>;
        fn config_set(key: &str, value: &str) -> Result<()>;
        fn remote_add(name: &str, url: &str) -> Result<()>;
        fn remote_set_url(name: &str, url: &str) -> Result<()>;
        fn blame(path: &str, rev: Option<String>) -> Result<Vec<BlameLine>>;
        fn cherry_pick(rev: &str) -> Result<()>;
        fn revert(rev: &str) -> Result<()>;
        fn rebase_skip() -> Result<()>;
    }
}

/// Synchronous, best-effort helpers for contexts that cannot `.await` — chiefly
/// a `Drop` guard. They shell out through `std::process` directly (no async, no
/// job-containment), so reserve them for short-lived cleanup.
pub mod blocking {
    use std::path::Path;
    use std::process::Command;

    /// Remove a worktree synchronously (`git worktree remove [--force] <path>`).
    pub fn worktree_remove(dir: &Path, path: &Path, force: bool) -> std::io::Result<()> {
        let mut cmd = Command::new(super::BINARY);
        cmd.current_dir(dir).args(["worktree", "remove"]);
        if force {
            cmd.arg("--force");
        }
        cmd.arg(path);
        let status = cmd.status()?;
        if status.success() {
            Ok(())
        } else {
            Err(std::io::Error::other(format!(
                "`git worktree remove` exited with {status}"
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use processkit::testing::{RecordingRunner, Reply, ScriptedRunner};

    #[test]
    fn binary_name_is_git() {
        assert_eq!(BINARY, "git");
    }

    // Compile-time guard: the bound view must stay `Copy` for the *default*
    // `JobRunner` (the production `Repo::git_at()` handle), not just for the
    // `&RecordingRunner` the other tests use. A derived `Copy` would regress this.
    #[allow(dead_code)]
    fn bound_view_is_copy_for_default_runner() {
        fn assert_copy<T: Copy>() {}
        assert_copy::<GitAt<'static, processkit::JobRunner>>();
    }

    // The bound view (`git.at(dir)`) must produce byte-identical argv to the
    // dir-taking call (`git.method(dir, …)`) — the forwarder injects `self.dir`
    // in the right place and nothing else changes.
    #[tokio::test]
    async fn bound_view_matches_dir_taking_calls() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);

        // A method with trailing args (dir injected first).
        git.merge_commit(dir, MergeCommit::branch("feat").no_ff())
            .await
            .unwrap();
        git.at(dir)
            .merge_commit(MergeCommit::branch("feat").no_ff())
            .await
            .unwrap();
        // A method taking a path arg after dir.
        git.worktree_remove(dir, Path::new("/wt"), true)
            .await
            .unwrap();
        git.at(dir)
            .worktree_remove(Path::new("/wt"), true)
            .await
            .unwrap();
        // One of the new query methods.
        git.conflicted_files(dir).await.unwrap();
        git.at(dir).conflicted_files().await.unwrap();
        // One of the §4 additions.
        git.tag_delete(dir, "v1").await.unwrap();
        git.at(dir).tag_delete("v1").await.unwrap();

        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), calls[1].args_str());
        assert_eq!(calls[2].args_str(), calls[3].args_str());
        assert_eq!(calls[4].args_str(), calls[5].args_str());
        assert_eq!(calls[6].args_str(), calls[7].args_str());
        // The bound calls also carried the bound dir as their working directory.
        assert_eq!(calls[1].cwd.as_deref(), Some(dir));
        assert_eq!(calls[3].cwd.as_deref(), Some(dir));
    }

    // Hermetic: the real status() command-building + porcelain parsing run
    // against a scripted runner — no `git` binary needed, so this runs on CI.
    #[tokio::test]
    async fn status_parses_scripted_output() {
        // `-z` output: NUL-delimited records, raw paths.
        let git = Git::with_runner(
            ScriptedRunner::new().on(["git", "status"], Reply::ok(" M a.rs\0?? b.rs\0")),
        );
        let entries = git.status(Path::new(".")).await.expect("status");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].code, " M");
        assert_eq!(entries[1].path, "b.rs");
    }

    // `status_tracked` is `status` minus untracked files — same parser, extra flag.
    #[tokio::test]
    async fn status_tracked_excludes_untracked_flag() {
        let rec = RecordingRunner::replying(Reply::ok(" M a.rs\0"));
        let git = Git::with_runner(&rec);
        let entries = git.status_tracked(Path::new(".")).await.expect("status");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].code, " M");
        assert_eq!(
            rec.only_call().args_str(),
            ["status", "--porcelain=v1", "-z", "--untracked-files=no"]
        );
    }

    // `branch_status` builds the porcelain v2 + branch + -z argv and parses the
    // combined header/entry output in one call.
    #[tokio::test]
    async fn branch_status_builds_v2_branch_args_and_parses() {
        let out = concat!(
            "# branch.oid abc\0",
            "# branch.head main\0",
            "# branch.upstream origin/main\0",
            "# branch.ab +1 -0\0",
            "1 .M N... 100644 100644 100644 1 2 a.rs\0",
            "? new.txt\0",
        );
        let rec = RecordingRunner::replying(Reply::ok(out));
        let git = Git::with_runner(&rec);
        let s = git
            .branch_status(Path::new("."))
            .await
            .expect("branch_status");
        assert_eq!(
            rec.only_call().args_str(),
            ["status", "--porcelain=v2", "--branch", "-z"]
        );
        // The poll primitive must not itself write the index (and re-trigger a
        // filesystem watcher re-querying through it).
        assert!(rec.only_call().envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_OPTIONAL_LOCKS")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
        assert_eq!(s.branch.as_deref(), Some("main"));
        assert_eq!(s.upstream.as_deref(), Some("origin/main"));
        assert_eq!((s.ahead, s.behind), (Some(1), Some(0)));
        assert_eq!(s.tracked_changes, 1);
        assert_eq!(s.untracked, 1);
        assert!(s.is_dirty());
    }

    // `conflicted_files` lists unmerged paths NUL-delimited (no quoting).
    #[tokio::test]
    async fn conflicted_files_builds_args_and_parses_nul_list() {
        let rec = RecordingRunner::replying(Reply::ok("a.rs\0sub/spaced name.rs\0"));
        let git = Git::with_runner(&rec);
        let paths = git
            .conflicted_files(Path::new("."))
            .await
            .expect("conflicted_files");
        assert_eq!(paths, ["a.rs", "sub/spaced name.rs"]);
        assert_eq!(
            rec.only_call().args_str(),
            ["diff", "--name-only", "--diff-filter=U", "-z"]
        );
    }

    #[tokio::test]
    async fn rev_parse_short_builds_short_flag() {
        let rec = RecordingRunner::replying(Reply::ok("a1b2c3d\n"));
        let git = Git::with_runner(&rec);
        let out = git.rev_parse_short(Path::new("/r"), "HEAD").await.unwrap();
        assert_eq!(out, "a1b2c3d");
        assert_eq!(rec.only_call().args_str(), ["rev-parse", "--short", "HEAD"]);
    }

    // M13: `rev_parse` passes `--verify` so a non-revision (a filename) errors
    // instead of being echoed back as a fake object id.
    #[tokio::test]
    async fn rev_parse_verifies_the_revision() {
        let rec = RecordingRunner::replying(Reply::ok("deadbeef\n"));
        let git = Git::with_runner(&rec);
        let out = git.rev_parse(Path::new("/r"), "HEAD").await.unwrap();
        assert_eq!(out, "deadbeef");
        assert_eq!(
            rec.only_call().args_str(),
            ["rev-parse", "--verify", "HEAD"]
        );
    }

    // M20: `git am` and an apply-backend rebase share the `rebase-apply/` dir, but am
    // marks it with an `applying` file. `is_am_in_progress` must fire only for the am,
    // and `is_rebase_in_progress` must NOT (so an am isn't aborted with `rebase --abort`).
    #[tokio::test]
    async fn distinguishes_git_am_from_an_apply_backend_rebase() {
        use vcs_testkit::TempDir;
        let gd = TempDir::new("m20-am");
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "rev-parse", "--git-dir"],
            Reply::ok(gd.path().to_str().unwrap()),
        ));
        let apply = gd.path().join("rebase-apply");
        std::fs::create_dir_all(&apply).unwrap();

        // With the `applying` marker → a `git am`.
        std::fs::write(apply.join("applying"), b"").unwrap();
        assert!(
            git.is_am_in_progress(Path::new("/r")).await.unwrap(),
            "am detected"
        );
        assert!(
            !git.is_rebase_in_progress(Path::new("/r")).await.unwrap(),
            "a git am is NOT reported as a rebase"
        );

        // Without it → an apply-backend rebase.
        std::fs::remove_file(apply.join("applying")).unwrap();
        assert!(!git.is_am_in_progress(Path::new("/r")).await.unwrap());
        assert!(
            git.is_rebase_in_progress(Path::new("/r")).await.unwrap(),
            "a bare rebase-apply dir is a rebase"
        );
    }

    // A non-zero exit surfaces as a structured `Error::Exit`.
    #[tokio::test]
    async fn nonzero_exit_is_structured_error() {
        let git = Git::with_runner(
            ScriptedRunner::new().on(["git", "status"], Reply::fail(128, "not a git repository")),
        );
        match git.status(Path::new(".")).await.unwrap_err() {
            Error::Exit { code, stderr, .. } => {
                assert_eq!(code, 128);
                assert!(stderr.contains("not a git repository"), "{stderr}");
            }
            other => panic!("expected Exit, got {other:?}"),
        }
    }

    // diff_is_empty maps the raw exit code itself: 0 → clean, 1 → dirty, and
    // anything else is a real failure surfaced as Error::Exit.
    #[tokio::test]
    async fn diff_is_empty_maps_exit_codes() {
        let clean =
            Git::with_runner(ScriptedRunner::new().on(["git", "diff", "--quiet"], Reply::ok("")));
        assert!(clean.diff_is_empty(Path::new(".")).await.unwrap());

        let dirty = Git::with_runner(
            ScriptedRunner::new().on(["git", "diff", "--quiet"], Reply::fail(1, "")),
        );
        assert!(!dirty.diff_is_empty(Path::new(".")).await.unwrap());

        let broken = Git::with_runner(ScriptedRunner::new().on(
            ["git", "diff", "--quiet"],
            Reply::fail(128, "fatal: not a repo"),
        ));
        assert!(matches!(
            broken.diff_is_empty(Path::new(".")).await.unwrap_err(),
            Error::Exit { code: 128, .. }
        ));
    }

    // `add` must insert `--` before the pathspecs so a path can never be parsed
    // as an option. No fallback rule: the run only matches if `add --` was built.
    #[tokio::test]
    async fn add_inserts_pathspec_separator() {
        let git = Git::with_runner(ScriptedRunner::new().on(["git", "add", "--"], Reply::ok("")));
        git.add(Path::new("."), &[PathBuf::from("f.rs")])
            .await
            .expect("add should build `add -- <paths>`");
    }

    #[tokio::test]
    async fn worktree_list_parses_porcelain() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "worktree", "list"],
            Reply::ok("worktree /repo\nHEAD abc\nbranch refs/heads/main\n"),
        ));
        let wts = git.worktree_list(Path::new(".")).await.expect("list");
        assert_eq!(wts.len(), 1);
        assert_eq!(wts[0].branch.as_deref(), Some("main"));
        assert_eq!(wts[0].head.as_deref(), Some("abc"));
    }

    // The new-branch worktree must build `worktree add -b <name> <path> <base>`,
    // in that exact order; only the full argv is scripted (no fallback).
    #[tokio::test]
    async fn worktree_add_builds_branch_path_and_base() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_add(
            Path::new("/repo"),
            WorktreeAdd::create_branch("/wt", "feature", "main"),
        )
        .await
        .expect("worktree add");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "add", "-b", "feature", "/wt", "main"]
        );
    }

    #[tokio::test]
    async fn worktree_remove_passes_force_then_path() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_remove(Path::new("/repo"), Path::new("/wt"), true)
            .await
            .expect("remove");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "remove", "--force", "/wt"]
        );
    }

    // `--no-checkout` must land between `-b <name>` and the path.
    #[tokio::test]
    async fn worktree_add_no_checkout_inserts_flag() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_add(
            Path::new("/repo"),
            WorktreeAdd::checkout("/wt", "main").no_checkout(),
        )
        .await
        .expect("worktree add");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "add", "--no-checkout", "/wt", "main"]
        );
    }

    #[tokio::test]
    async fn checkout_detach_builds_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.checkout_detach(Path::new("."), "abc123")
            .await
            .expect("detach");
        assert_eq!(
            rec.only_call().args_str(),
            ["checkout", "--detach", "abc123"]
        );
    }

    // current_branch reads `symbolic-ref --quiet --short HEAD`: exit 0 → the branch
    // name (a normal *or* unborn branch), exit 1 → None (detached HEAD), and any
    // other non-zero (e.g. not a repository) stays a real error.
    #[tokio::test]
    async fn current_branch_reads_symbolic_ref_with_exit_mapping() {
        // A normal branch (exit 0) — and the argv is pinned.
        let rec = RecordingRunner::replying(Reply::ok("feature/x\n"));
        let on_branch = Git::with_runner(&rec);
        assert_eq!(
            on_branch.current_branch(Path::new(".")).await.unwrap(),
            Some("feature/x".to_string())
        );
        assert_eq!(
            rec.only_call().args_str(),
            ["symbolic-ref", "--quiet", "--short", "HEAD"]
        );
        // An unborn branch also exits 0 with the branch name (the bug this fixes:
        // the old `rev-parse --abbrev-ref HEAD` errored with exit 128 here).
        let unborn = Git::with_runner(
            ScriptedRunner::new().on(["git", "symbolic-ref"], Reply::ok("main\n")),
        );
        assert_eq!(
            unborn.current_branch(Path::new(".")).await.unwrap(),
            Some("main".to_string())
        );
        // A detached HEAD exits 1 silently → None.
        let detached =
            Git::with_runner(ScriptedRunner::new().on(["git", "symbolic-ref"], Reply::fail(1, "")));
        assert_eq!(detached.current_branch(Path::new(".")).await.unwrap(), None);
        // Any other non-zero (not a repository, exit 128) is a real error.
        let not_repo = Git::with_runner(ScriptedRunner::new().on(
            ["git", "symbolic-ref"],
            Reply::fail(128, "fatal: not a git repository"),
        ));
        assert!(not_repo.current_branch(Path::new(".")).await.is_err());
    }

    // Partial amend commit must build `commit --amend -m <msg> --only -- <paths>`.
    #[tokio::test]
    async fn commit_paths_builds_only_amend_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.commit_paths(
            Path::new("."),
            CommitPaths::new([PathBuf::from("a.rs"), PathBuf::from("b.rs")], "msg").amend(),
        )
        .await
        .expect("commit_paths");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "commit", "--amend", "-m", "msg", "--only", "--", "a.rs", "b.rs"
            ]
        );
    }

    // is_unborn maps the rev-parse exit code: 0 → has commits (false), 1 →
    // unborn (true), anything else is a structured error.
    #[tokio::test]
    async fn is_unborn_maps_exit_codes() {
        let born =
            Git::with_runner(ScriptedRunner::new().on(["git", "rev-parse"], Reply::ok("abc\n")));
        assert!(!born.is_unborn(Path::new(".")).await.unwrap());
        let unborn =
            Git::with_runner(ScriptedRunner::new().on(["git", "rev-parse"], Reply::fail(1, "")));
        assert!(unborn.is_unborn(Path::new(".")).await.unwrap());
        let broken = Git::with_runner(
            ScriptedRunner::new().on(["git", "rev-parse"], Reply::fail(128, "boom")),
        );
        assert!(matches!(
            broken.is_unborn(Path::new(".")).await.unwrap_err(),
            Error::Exit { code: 128, .. }
        ));
    }

    #[tokio::test]
    async fn log_builds_revspec_and_format() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.log(Path::new("."), "main..HEAD", 5).await.expect("log");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "log",
                "main..HEAD",
                "-n5",
                "-z",
                "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s"
            ]
        );
    }

    #[tokio::test]
    async fn stash_push_adds_include_untracked() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.stash_push(Path::new("."), true).await.expect("stash");
        assert_eq!(
            rec.only_call().args_str(),
            ["stash", "push", "--include-untracked"]
        );
    }

    // `diff_text` for the working tree must build `diff HEAD` plus the stable
    // machine-output flags, in order.
    #[tokio::test]
    async fn diff_text_builds_working_tree_args() {
        // The `rev-parse` unborn probe replies exit 0 (HEAD resolves), so the diff
        // targets HEAD. The probe is the first call; the diff is the last.
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.diff_text(Path::new("."), DiffSpec::WorkingTree)
            .await
            .expect("diff_text");
        assert_eq!(
            rec.calls().last().unwrap().args_str(),
            [
                "diff",
                "HEAD",
                "--no-color",
                "--no-ext-diff",
                "-M",
                // Pin the parser's `a/`…`b/` headers against a user's
                // `diff.noprefix`/`diff.mnemonicPrefix` config.
                "--src-prefix=a/",
                "--dst-prefix=b/",
            ]
        );
    }

    // On an unborn repo the working-tree diff targets the empty tree instead of
    // the unresolvable `HEAD`, so it returns additions rather than erroring. The
    // diff rule only matches the empty-tree argv, so a `HEAD` target would miss it.
    #[tokio::test]
    async fn diff_text_working_tree_uses_empty_tree_when_unborn() {
        let git = Git::with_runner(
            ScriptedRunner::new()
                .on(["git", "rev-parse"], Reply::fail(1, "")) // unborn: HEAD doesn't resolve
                .on(["git", "diff", EMPTY_TREE], Reply::ok("EMPTY")),
        );
        let out = git
            .diff_text(Path::new("."), DiffSpec::WorkingTree)
            .await
            .expect("diff_text");
        assert_eq!(out, "EMPTY");
    }

    // Hermetic: real diff() arg-building (`Rev`) + the ported parser against
    // canned git-format output.
    #[tokio::test]
    async fn diff_parses_scripted_output() {
        let out = "diff --git a/m b/m\n--- a/m\n+++ b/m\n@@ -1 +1 @@\n-a\n+b\n";
        let git = Git::with_runner(ScriptedRunner::new().on(["git", "diff"], Reply::ok(out)));
        let files = git
            .diff(Path::new("."), DiffSpec::Rev("HEAD~1".into()))
            .await
            .expect("diff");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "m");
        assert_eq!(files[0].change, ChangeKind::Modified);
    }

    #[tokio::test]
    async fn branch_exists_maps_exit_codes() {
        let yes = Git::with_runner(ScriptedRunner::new().on(["git", "show-ref"], Reply::ok("")));
        assert!(yes.branch_exists(Path::new("."), "main").await.unwrap());
        let no =
            Git::with_runner(ScriptedRunner::new().on(["git", "show-ref"], Reply::fail(1, "")));
        assert!(!no.branch_exists(Path::new("."), "nope").await.unwrap());
    }

    // The full ref prefix is stripped but a slashed default branch survives; an
    // unset origin/HEAD (non-zero exit) is `None`, not an error.
    #[tokio::test]
    async fn remote_head_branch_strips_prefix_and_keeps_slashes() {
        let simple = Git::with_runner(ScriptedRunner::new().on(
            ["git", "symbolic-ref"],
            Reply::ok("refs/remotes/origin/main\n"),
        ));
        assert_eq!(
            simple
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("main")
        );

        let slashed = Git::with_runner(ScriptedRunner::new().on(
            ["git", "symbolic-ref"],
            Reply::ok("refs/remotes/origin/release/v2\n"),
        ));
        assert_eq!(
            slashed
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("release/v2")
        );

        let unset =
            Git::with_runner(ScriptedRunner::new().on(["git", "symbolic-ref"], Reply::fail(1, "")));
        assert!(
            unset
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .is_none()
        );
    }

    // remote_branch_exists must pass `GIT_TERMINAL_PROMPT=0` and treat empty
    // stdout as "absent".
    #[tokio::test]
    async fn remote_branch_exists_sets_env_and_reads_stdout() {
        let rec = RecordingRunner::replying(Reply::ok("abc123\trefs/heads/main\n"));
        let git = Git::with_runner(&rec);
        assert!(
            git.remote_branch_exists(Path::new("/repo"), "main")
                .await
                .unwrap()
        );
        let call = rec.only_call();
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
        // Exact-ref query — a bare `main` would tail-match `bar/main`.
        assert_eq!(call.args_str(), ["ls-remote", "origin", "refs/heads/main"]);

        let empty = Git::with_runner(ScriptedRunner::new().on(["git", "ls-remote"], Reply::ok("")));
        assert!(
            !empty
                .remote_branch_exists(Path::new("."), "x")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn diff_stat_parses_counts() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "diff", "--shortstat"],
            Reply::ok(" 2 files changed, 5 insertions(+), 1 deletion(-)\n"),
        ));
        let stat = git.diff_stat(Path::new("."), "main..HEAD").await.unwrap();
        assert_eq!(
            (stat.files_changed, stat.insertions, stat.deletions),
            (2, 5, 1)
        );
    }

    #[tokio::test]
    async fn status_text_returns_raw_porcelain() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "status", "--porcelain=v1"],
            Reply::ok(" M a.rs\n?? b.rs\n"),
        ));
        let text = git.status_text(Path::new(".")).await.expect("status_text");
        assert!(text.contains(" M a.rs") && text.contains("?? b.rs"));
    }

    #[tokio::test]
    async fn run_args_forwards_str_slices() {
        let git =
            Git::with_runner(ScriptedRunner::new().on(["git", "status", "-s"], Reply::ok("ok\n")));
        assert_eq!(git.run_args(&["status", "-s"]).await.unwrap(), "ok");
    }

    #[tokio::test]
    async fn merge_commit_builds_no_ff_and_message() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.merge_commit(
            Path::new("/r"),
            MergeCommit::branch("feature").no_ff().message("merge it"),
        )
        .await
        .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["merge", "--no-ff", "-m", "merge it", "feature"]
        );
    }

    // No message → `--no-edit` (default message, non-interactive) instead of `$EDITOR`.
    #[tokio::test]
    async fn merge_commit_without_message_uses_no_edit() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.merge_commit(Path::new("/r"), MergeCommit::branch("feature"))
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["merge", "--no-edit", "feature"]
        );
    }

    // rebase/rebase_continue force a no-op editor so a headless caller never hangs.
    #[tokio::test]
    async fn rebase_suppresses_editor() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.rebase(Path::new("/r"), "main").await.unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["rebase", "main"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_EDITOR")
                && v.as_deref().and_then(|o| o.to_str()) == Some("true")
        }));
    }

    #[tokio::test]
    async fn push_builds_set_upstream_remote_refspec() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(
            Path::new("/r"),
            GitPush::refspec("feat", "feature").set_upstream(),
        )
        .await
        .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["push", "-u", "origin", "feat:feature"]
        );
    }

    // The common bare-branch push: `push origin <branch>` (no `-u`), with prompts
    // off so a credential-needing remote fails fast instead of hanging.
    #[tokio::test]
    async fn push_bare_branch_builds_origin_branch_prompt_off() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(Path::new("/r"), GitPush::branch("feature"))
            .await
            .unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["push", "origin", "feature"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
    }

    // M16: a `+` (force-push) or an extra `:` (multi-ref) smuggled into a branch name
    // is refused before spawning — force-pushing must be explicit via `run`.
    #[tokio::test]
    async fn push_rejects_force_and_multiref_metacharacters() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        for bad in ["+main", "+main:main", "a:b:c"] {
            assert!(
                git.push(Path::new("/r"), GitPush::branch(bad))
                    .await
                    .is_err(),
                "{bad:?} must be rejected"
            );
        }
        // A legitimate `local:remote` refspec still works (one `:`, no `+`).
        assert!(
            git.push(Path::new("/r"), GitPush::refspec("main", "prod"))
                .await
                .is_ok()
        );
        assert!(
            rec.calls()
                .iter()
                .all(|c| c.args_str().last().unwrap() != "+main")
        );
    }

    // `.remote()` swaps the remote token in place.
    #[tokio::test]
    async fn push_remote_override_swaps_remote() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(
            Path::new("/r"),
            GitPush::branch("feature").remote("upstream"),
        )
        .await
        .unwrap();
        assert_eq!(rec.only_call().args_str(), ["push", "upstream", "feature"]);
    }

    // With a credential provider, a remote op gets a leading `-c credential.helper`
    // pair (the secret referenced by env-var NAME) plus the secret in the env — and
    // the token value never appears in argv. Covers push (mutating) and fetch.
    #[tokio::test]
    async fn with_credentials_injects_helper_and_secret_env_for_remote_ops() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec)
            .with_credentials(Arc::new(StaticCredential::token("ghp_secret123")));
        git.push(Path::new("/r"), GitPush::branch("feature"))
            .await
            .unwrap();
        let call = rec.only_call();
        let args = call.args_str();
        // A leading helper-reset + inline helper precede the subcommand.
        assert_eq!(args[0], "-c", "config flag leads the argv");
        assert!(
            args.iter().any(|a| a == "credential.helper="),
            "inherited helpers are cleared first: {args:?}"
        );
        assert!(
            args.iter()
                .any(|a| a.contains("credential.helper=!f()")
                    && a.contains("VCS_TOOLKIT_GIT_PASSWORD")),
            "inline helper references the secret by env-var name: {args:?}"
        );
        assert!(
            args.contains(&"push".to_string()) && args.contains(&"feature".to_string()),
            "the real subcommand still runs: {args:?}"
        );
        // The secret value is NEVER in argv.
        assert!(
            !args.iter().any(|a| a.contains("ghp_secret123")),
            "secret leaked into argv: {args:?}"
        );
        // The secret lives in the env, under the helper's var name.
        let pw = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("VCS_TOOLKIT_GIT_PASSWORD"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(pw, Some("ghp_secret123"), "secret carried in env");
    }

    // Without a provider, remote ops are byte-identical to before — no `-c`
    // credential helper, no secret env (ambient git auth, unchanged).
    #[tokio::test]
    async fn default_client_injects_no_credential_helper() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(Path::new("/r"), GitPush::branch("feature"))
            .await
            .unwrap();
        let call = rec.only_call();
        assert_eq!(
            call.args_str(),
            ["push", "origin", "feature"],
            "no credential `-c` args without a provider"
        );
        assert!(
            !call
                .envs
                .iter()
                .any(|(k, _)| k.to_str() == Some("VCS_TOOLKIT_GIT_PASSWORD")),
            "no secret env without a provider"
        );
    }

    // `clone_repo` builds its argv via a different path (`command()` + `.arg()`
    // chaining, not `command_in` + extend), so verify the `-c` credential args
    // still LEAD it and the real clone flags/url/dest follow the subcommand.
    #[tokio::test]
    async fn with_credentials_clone_puts_config_flags_before_subcommand() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git =
            Git::with_runner(&rec).with_credentials(Arc::new(StaticCredential::token("s3cr3t")));
        git.clone_repo(
            "https://example.com/r.git",
            Path::new("/dest"),
            CloneSpec::default().branch("main"),
        )
        .await
        .unwrap();
        let call = rec.only_call();
        let args = call.args_str();
        assert_eq!(args[0], "-c", "config flags lead the clone argv");
        let clone_at = args
            .iter()
            .position(|a| a == "clone")
            .expect("clone present");
        // Only credential `-c` flags precede the `clone` subcommand.
        assert!(
            args[..clone_at]
                .iter()
                .all(|a| a == "-c" || a.starts_with("credential.helper")),
            "only credential -c flags precede `clone`: {args:?}"
        );
        // The real clone flags/url/dest follow the subcommand.
        let tail = &args[clone_at..];
        assert!(tail.iter().any(|a| a == "--branch") && tail.iter().any(|a| a == "main"));
        assert!(tail.iter().any(|a| a == "https://example.com/r.git"));
        assert!(
            !args.iter().any(|a| a.contains("s3cr3t")),
            "secret not in argv"
        );
        // H5: clone scopes the helper to the URL's host (in env, never argv), so a
        // cross-host redirect/submodule during the clone can't extract the token.
        let host = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("VCS_TOOLKIT_GIT_HOST"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(
            host,
            Some("example.com"),
            "the clone URL's host scopes the credential helper"
        );
        // The host scoping travels in env; the credential `-c` flags that precede
        // `clone` must not bake the host into the helper config.
        assert!(
            args[..clone_at].iter().all(|a| !a.contains("example.com")),
            "host stays in env, not the credential config args: {:?}",
            &args[..clone_at]
        );
    }

    // A `Credential::userpass` username threads through to the helper's env on a
    // remote op (here `fetch`) — the non-default-username path, end-to-end.
    #[tokio::test]
    async fn with_credentials_userpass_threads_username_through_env() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec).with_credentials(Arc::new(StaticCredential::new(
            Credential::userpass("alice", "s3cr3t"),
        )));
        git.fetch(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        let user = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("VCS_TOOLKIT_GIT_USERNAME"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(user, Some("alice"), "userpass username reaches the env");
        assert_eq!(call.args_str()[0], "-c", "helper `-c` leads fetch too");
        assert!(call.args_str().contains(&"fetch".to_string()));
    }

    // No-provider is byte-identical for the read/clone arg-construction paths too,
    // not only `push` (fetch uses `command_in`+extend; clone uses `command`+chain).
    #[tokio::test]
    async fn default_client_no_helper_on_fetch_and_clone() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        Git::with_runner(&rec).fetch(Path::new("/r")).await.unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["fetch", "--quiet"],
            "fetch unchanged without a provider"
        );

        let rec = RecordingRunner::replying(Reply::ok(""));
        Git::with_runner(&rec)
            .clone_repo(
                "https://example.com/r.git",
                Path::new("/dest"),
                CloneSpec::default(),
            )
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str()[0],
            "clone",
            "clone leads with the subcommand (no `-c`) without a provider"
        );
    }

    // The `with_token` convenience drives the same HTTPS credential.helper path as
    // `with_credentials` (secret in env, helper `-c` leads, not in argv).
    #[tokio::test]
    async fn with_token_convenience_authenticates_https_remote() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec).with_token("ghp_conv");
        git.fetch(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str()[0], "-c", "helper `-c` leads");
        let pw = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("VCS_TOOLKIT_GIT_PASSWORD"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(pw, Some("ghp_conv"), "secret carried in env");
        assert!(
            !call.args_str().iter().any(|a| a.contains("ghp_conv")),
            "secret not in argv"
        );
    }

    #[tokio::test]
    async fn upstream_maps_unset_to_none() {
        let set = Git::with_runner(
            ScriptedRunner::new().on(["git", "rev-parse"], Reply::ok("origin/main\n")),
        );
        assert_eq!(
            set.upstream(Path::new(".")).await.unwrap().as_deref(),
            Some("origin/main")
        );
        // No upstream configured exits 128 (indistinguishable from a real failure by
        // code, since git uses 128 for both) → None.
        let unset =
            Git::with_runner(ScriptedRunner::new().on(["git", "rev-parse"], Reply::fail(128, "")));
        assert!(unset.upstream(Path::new(".")).await.unwrap().is_none());
        // A timeout (no exit code) is a real failure — it must surface, not read as
        // "no upstream".
        let timed_out =
            Git::with_runner(ScriptedRunner::new().on(["git", "rev-parse"], Reply::timeout()));
        assert!(timed_out.upstream(Path::new(".")).await.is_err());
    }

    // remote_head_branch maps the `symbolic-ref --quiet` exit code: 0 → the branch
    // (ref prefix stripped), 1 → None (unset origin/HEAD), and anything else (a real
    // failure / timeout) surfaces rather than being swallowed as "no default branch".
    #[tokio::test]
    async fn remote_head_branch_maps_exit_codes() {
        let set = Git::with_runner(ScriptedRunner::new().on(
            ["git", "symbolic-ref"],
            Reply::ok("refs/remotes/origin/release/v2\n"),
        ));
        assert_eq!(
            set.remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("release/v2"),
            "the full ref prefix is stripped, slashes preserved"
        );
        let unset =
            Git::with_runner(ScriptedRunner::new().on(["git", "symbolic-ref"], Reply::fail(1, "")));
        assert!(
            unset
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .is_none()
        );
        // A real failure (exit 128, not the silent --quiet exit 1) surfaces.
        let err = Git::with_runner(ScriptedRunner::new().on(
            ["git", "symbolic-ref"],
            Reply::fail(128, "fatal: not a git repository"),
        ));
        assert!(err.remote_head_branch(Path::new(".")).await.is_err());
        // A timeout surfaces too.
        let timed_out =
            Git::with_runner(ScriptedRunner::new().on(["git", "symbolic-ref"], Reply::timeout()));
        assert!(timed_out.remote_head_branch(Path::new(".")).await.is_err());
    }

    #[tokio::test]
    async fn set_upstream_builds_branch_flag() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.set_upstream(Path::new("/r"), "feat", "origin/feature")
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["branch", "--set-upstream-to=origin/feature", "feat"]
        );
    }

    #[tokio::test]
    async fn remote_branches_parses_ls_remote() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "ls-remote"],
            Reply::ok("aaa\trefs/heads/main\nbbb\trefs/heads/feat/x\n"),
        ));
        let branches = git.remote_branches(Path::new("."), "origin").await.unwrap();
        assert_eq!(branches, ["main", "feat/x"]);
    }

    #[tokio::test]
    async fn delete_branch_force_uses_capital_d() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.delete_branch(Path::new("/r"), "old", true)
            .await
            .unwrap();
        assert_eq!(rec.only_call().args_str(), ["branch", "-D", "old"]);
    }

    // `branch --merged` marks the current branch with `*` and a branch checked out
    // in another worktree with `+`; both must still match after marker stripping.
    #[tokio::test]
    async fn is_merged_strips_branch_markers() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "branch", "--merged"],
            Reply::ok("  main\n* feature\n+ wt-branch\n"),
        ));
        for name in ["main", "feature", "wt-branch"] {
            assert!(
                git.is_merged(Path::new("."), MergeCheck::branch(name).into_base("main"))
                    .await
                    .unwrap(),
                "{name} should be reported merged"
            );
        }
        assert!(
            !git.is_merged(
                Path::new("."),
                MergeCheck::branch("absent").into_base("main")
            )
            .await
            .unwrap()
        );
    }

    // A5: the `MergeCheck` builder lands branch/base in the right slots, and
    // `is_merged` queries `branch --merged <base>` — so a transposed pair would
    // change the emitted command, not silently invert a same-shaped call.
    #[tokio::test]
    async fn merge_check_names_branch_and_base_without_transposition() {
        use processkit::testing::RecordingRunner;
        let spec = MergeCheck::branch("feature").into_base("main");
        assert_eq!(spec.branch, "feature");
        assert_eq!(spec.base, "main");

        let rec = RecordingRunner::replying(Reply::ok("  feature\n* main\n"));
        let merged = Git::with_runner(&rec)
            .is_merged(
                Path::new("/repo"),
                MergeCheck::branch("feature").into_base("main"),
            )
            .await
            .unwrap();
        // `feature` appears under `branch --merged main`, so it reports merged — and
        // the emitted args put `base` (main) in the `--merged` slot, not `branch`.
        assert!(merged, "feature is listed as merged into main");
        assert_eq!(
            rec.only_call().args_str(),
            ["branch", "--merged", "main", "--no-column", "--no-color"]
        );
    }

    // `fetch` must disable the credential prompt so it fails fast (never hangs) on
    // a remote needing auth — matching the other remote ops.
    #[tokio::test]
    async fn fetch_disables_terminal_prompt() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.fetch(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["fetch", "--quiet"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
    }

    // A transient failure (DNS/network) is retried up to FETCH_ATTEMPTS times.
    #[tokio::test]
    async fn fetch_retries_transient_failures() {
        let rec = RecordingRunner::replying(Reply::fail(
            128,
            "fatal: unable to access: Could not resolve host: example.com",
        ));
        let git = Git::with_runner(&rec);
        assert!(git.fetch(Path::new("/r")).await.is_err());
        assert_eq!(rec.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // R6 (a `fetch` timeout is NOT retried) is pinned at the unit level by
    // `vcs_cli_support`'s `classifies_nothing_to_commit_and_transient_fetch`
    // (`is_transient_fetch_error(&Timeout) == false`); together with
    // `fetch_retries_transient_failures` above (the loop retries exactly what the
    // predicate accepts) that proves the timeout is terminal for the fetch-retry. A
    // faithful end-to-end timeout is awkward to simulate hermetically (a paused-clock
    // `Reply::pending()` doesn't auto-fire the per-command deadline), so it isn't
    // duplicated here.

    // Opt-in lock-contention retry: a mutation that fails because another process
    // holds `index.lock` is retried and succeeds — the command never ran, so the
    // retry is safe. `RetryPolicy::none().attempts(3)` keeps the backoff at zero so
    // the test never sleeps.
    #[tokio::test]
    async fn with_retry_retries_lock_contention_on_a_mutation() {
        let rec = RecordingRunner::new(ScriptedRunner::new().on_sequence(
            ["git", "commit"],
            [
                Reply::fail(
                    128,
                    "fatal: Unable to create '/r/.git/index.lock': File exists.",
                ),
                Reply::ok(""),
            ],
        ));
        let git = Git::with_runner(&rec).with_retry(RetryPolicy::none().attempts(3));
        git.commit(Path::new("/r"), "msg")
            .await
            .expect("retried past the lock");
        assert_eq!(rec.calls().len(), 2, "one retry after the lock failure");
    }

    // Retry is off by default — the same lock failure propagates without `with_retry`.
    #[tokio::test]
    async fn default_client_does_not_retry_lock_contention() {
        let rec = RecordingRunner::new(ScriptedRunner::new().on_sequence(
            ["git", "commit"],
            [
                Reply::fail(
                    128,
                    "fatal: Unable to create '/r/.git/index.lock': File exists.",
                ),
                Reply::ok(""),
            ],
        ));
        let git = Git::with_runner(&rec);
        assert!(git.commit(Path::new("/r"), "msg").await.is_err());
        assert_eq!(rec.calls().len(), 1, "no retry without with_retry");
    }

    // Even with retry on, a real (non-lock) failure is returned immediately — only
    // lock contention is retried, so a genuine error is never silently repeated.
    #[tokio::test]
    async fn with_retry_does_not_retry_a_real_failure() {
        let rec = RecordingRunner::new(ScriptedRunner::new().on_sequence(
            ["git", "commit"],
            [
                Reply::fail(1, "error: pathspec 'x' did not match"),
                Reply::ok(""),
            ],
        ));
        let git = Git::with_runner(&rec).with_retry(RetryPolicy::none().attempts(3));
        assert!(git.commit(Path::new("/r"), "msg").await.is_err());
        assert_eq!(rec.calls().len(), 1, "a non-lock failure is not retried");
    }

    // A non-transient failure fails fast — no retry.
    #[tokio::test]
    async fn fetch_does_not_retry_permanent_failures() {
        let rec = RecordingRunner::replying(Reply::fail(1, "fatal: couldn't find remote ref"));
        let git = Git::with_runner(&rec);
        assert!(git.fetch(Path::new("/r")).await.is_err());
        assert_eq!(rec.calls().len(), 1);
    }

    // Client-level cancellation (processkit 0.8 `cancellation` feature) on a
    // *retried* op: a `fetch` built on a client with `default_cancel_on(token)`
    // parks until the token fires, then surfaces `Error::Cancelled` — and because
    // cancellation is **terminal** (not transient), the fetch-retry does NOT
    // replay it (one spawn, not FETCH_ATTEMPTS). Hermetic via `Reply::pending()`
    // on a paused clock.
    #[tokio::test(start_paused = true)]
    async fn fetch_cancels_and_does_not_retry() {
        use processkit::CancellationToken;
        let token = CancellationToken::new();
        let rec =
            RecordingRunner::new(ScriptedRunner::new().on(["git", "fetch"], Reply::pending()));
        let git = Git::with_runner(&rec).default_cancel_on(token.clone());
        let call = git.fetch(Path::new("/r"));
        tokio::pin!(call);
        assert!(
            tokio::time::timeout(std::time::Duration::from_secs(3600), &mut call)
                .await
                .is_err(),
            "fetch must park until the token fires"
        );
        token.cancel();
        assert!(matches!(call.await.unwrap_err(), Error::Cancelled { .. }));
        assert_eq!(
            rec.calls().len(),
            1,
            "cancellation is terminal — the fetch-retry must not replay it"
        );
    }

    // The injection guard: a flag-shaped value in any exposed positional slot
    // must be refused BEFORE anything spawns.
    #[tokio::test]
    async fn flag_like_positionals_are_rejected_before_spawning() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        let dir = Path::new("/r");

        assert!(git.checkout(dir, "-evil").await.is_err());
        assert!(git.create_branch(dir, "--force").await.is_err());
        assert!(git.delete_branch(dir, "-D", false).await.is_err());
        assert!(git.rename_branch(dir, "ok", "-bad").await.is_err());
        assert!(
            git.merge_commit(dir, MergeCommit::branch("-evil"))
                .await
                .is_err()
        );
        assert!(
            git.merge_no_commit(dir, MergeNoCommit::branch("-evil").no_ff())
                .await
                .is_err()
        );
        assert!(git.merge_squash(dir, "-evil").await.is_err());
        assert!(git.rebase(dir, "-i").await.is_err());
        assert!(git.cherry_pick(dir, "-n").await.is_err());
        assert!(git.revert(dir, "-evil").await.is_err());
        assert!(git.tag_create(dir, "-d", None).await.is_err());
        assert!(
            git.tag_create(dir, "ok", Some("-evil".into()))
                .await
                .is_err()
        );
        assert!(git.tag_delete(dir, "-evil").await.is_err());
        assert!(git.remote_add(dir, "-evil", "url").await.is_err());
        assert!(git.remote_set_url(dir, "-evil", "url").await.is_err());
        assert!(git.set_upstream(dir, "-evil", "origin/x").await.is_err());
        assert!(git.log(dir, "-evil", 5).await.is_err());
        assert!(git.rev_list_count(dir, "-evil").await.is_err());
        assert!(git.diff_stat(dir, "-evil").await.is_err());
        assert!(git.diff_range_is_empty(dir, "-evil").await.is_err());
        assert!(
            git.diff_text(dir, DiffSpec::Rev("-evil".into()))
                .await
                .is_err()
        );
        assert!(git.rev_parse(dir, "-evil").await.is_err());
        assert!(git.rev_parse_short(dir, "-evil").await.is_err());
        assert!(git.resolve_commit(dir, "-evil").await.is_err());
        assert!(git.reset_hard(dir, "-evil").await.is_err());
        assert!(git.checkout_detach(dir, "-evil").await.is_err());
        assert!(git.config_set(dir, "-evil", "v").await.is_err());
        assert!(
            git.push(dir, GitPush::branch("-evil")).await.is_err(),
            "refspec guard"
        );
        // Embedded-token-prefix and standalone-rev positionals:
        assert!(git.show_file(dir, "-evil", "f.txt").await.is_err());
        assert!(git.blame(dir, "f.txt", Some("-s".into())).await.is_err());
        assert!(git.remote_url(dir, "-evil").await.is_err());
        assert!(git.remote_branches(dir, "-evil").await.is_err());
        assert!(git.fetch_from(dir, "--upload-pack=x").await.is_err());
        // URL positionals (a leading-`-` url is an RCE-class flag injection).
        assert!(
            git.clone_repo("--upload-pack=x", Path::new("/d"), CloneSpec::new())
                .await
                .is_err()
        );
        assert!(git.remote_add(dir, "ok", "--upload-pack=x").await.is_err());
        assert!(git.remote_set_url(dir, "ok", "-evil").await.is_err());
        assert!(
            git.is_merged(dir, MergeCheck::branch("-evil").into_base("main"))
                .await
                .is_err()
        );
        assert!(git.config_get(dir, "-evil").await.is_err());
        assert!(
            git.worktree_add(
                dir,
                WorktreeAdd::create_branch(Path::new("/wt"), "-evil", "HEAD")
            )
            .await
            .is_err()
        );
        // Empty values are refused too.
        assert!(git.checkout(dir, "").await.is_err());

        assert!(
            rec.calls().is_empty(),
            "nothing may spawn: {:?}",
            rec.calls()
        );

        // …and legitimate values still pass through unchanged (with the trailing
        // `--` that keeps a path-like ref out of pathspec mode — C2).
        git.checkout(dir, "feature/x").await.expect("checkout");
        assert_eq!(rec.only_call().args_str(), ["checkout", "feature/x", "--"]);
    }

    // The hardened profile lands its env pairs/removals on EVERY command, and
    // composes with per-command env like GIT_TERMINAL_PROMPT.
    #[tokio::test]
    async fn harden_applies_env_profile_to_every_command() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec).harden();
        git.status(Path::new("/r")).await.expect("status");
        git.fetch(Path::new("/r")).await.expect("fetch");

        for call in rec.calls() {
            let has = |k: &str, v: &str| {
                call.envs.iter().any(|(key, val)| {
                    key.to_str() == Some(k) && val.as_deref().and_then(|o| o.to_str()) == Some(v)
                })
            };
            let removed = |k: &str| {
                call.envs
                    .iter()
                    .any(|(key, val)| key.to_str() == Some(k) && val.is_none())
            };
            assert!(has("GIT_CONFIG_NOSYSTEM", "1"), "{:?}", call.args_str());
            assert!(has("GIT_CONFIG_COUNT", "3"));
            assert!(has("GIT_CONFIG_KEY_0", "core.hooksPath"));
            assert!(has("GIT_CONFIG_VALUE_0", "/dev/null"));
            assert!(has("GIT_CONFIG_KEY_1", "core.fsmonitor"));
            // The repo-local core.sshCommand kill-switch (pinned empty).
            assert!(has("GIT_CONFIG_KEY_2", "core.sshCommand"));
            assert!(has("GIT_CONFIG_VALUE_2", ""));
            assert!(has("GIT_TERMINAL_PROMPT", "0"));
            assert!(removed("GIT_DIR"), "GIT_DIR scrubbed");
            assert!(removed("GIT_CONFIG_GLOBAL"), "global config scrubbed");
            // Command-hook env vectors are scrubbed too.
            assert!(removed("GIT_SSH_COMMAND"), "GIT_SSH_COMMAND scrubbed");
            assert!(removed("GIT_ASKPASS"), "GIT_ASKPASS scrubbed");
            assert!(removed("GIT_EXTERNAL_DIFF"), "GIT_EXTERNAL_DIFF scrubbed");
            assert!(removed("GIT_PAGER"), "GIT_PAGER scrubbed");
            // M14: the additional code-execution vectors + pathspec-mode vars.
            assert!(removed("GIT_PROXY_COMMAND"), "GIT_PROXY_COMMAND scrubbed");
            assert!(removed("GIT_EXEC_PATH"), "GIT_EXEC_PATH scrubbed");
            assert!(removed("GIT_TEMPLATE_DIR"), "GIT_TEMPLATE_DIR scrubbed");
            assert!(
                removed("GIT_ICASE_PATHSPECS"),
                "GIT_ICASE_PATHSPECS scrubbed"
            );
        }
    }

    // H4: EVERY git client (not just `harden()`) scrubs the repo-**redirector** env
    // vars, so a `GIT_DIR`/`GIT_INDEX_FILE` leaking from the parent (e.g. running
    // inside a git hook, which exports them) can't silently retarget a command at a
    // different repository than the bound `dir`. The command-hook scrubs and config
    // pins stay `harden()`-only.
    #[tokio::test]
    async fn default_client_scrubs_repo_redirector_env() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec); // NOT hardened
        git.status(Path::new("/r")).await.expect("status");
        let call = rec.only_call();
        let removed = |k: &str| {
            call.envs
                .iter()
                .any(|(key, val)| key.to_str() == Some(k) && val.is_none())
        };
        let has_key = |k: &str| call.envs.iter().any(|(key, _)| key.to_str() == Some(k));
        for var in [
            "GIT_DIR",
            "GIT_WORK_TREE",
            "GIT_INDEX_FILE",
            "GIT_COMMON_DIR",
            "GIT_OBJECT_DIRECTORY",
            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
            "GIT_NAMESPACE",
        ] {
            assert!(removed(var), "{var} must be scrubbed on the default client");
        }
        // `harden()`-only surface is absent on a plain client.
        assert!(
            !has_key("GIT_SSH_COMMAND"),
            "command-hook scrub is harden()-only"
        );
        assert!(
            !has_key("GIT_CONFIG_NOSYSTEM"),
            "config pins are harden()-only"
        );
    }

    // RefName/RevSpec accept/reject tables.
    #[test]
    fn ref_name_and_rev_spec_validate() {
        for ok in ["main", "feature/x", "v1.2.3", "a-b_c"] {
            assert!(RefName::new(ok).is_ok(), "{ok}");
        }
        for bad in [
            "", "-evil", ".hidden", "a..b", "a b", "a~b", "a^b", "a:b", "a?b", "a*b", "a[b",
            "a\\b", "end/", "x.lock",
        ] {
            assert!(RefName::new(bad).is_err(), "{bad:?} must be rejected");
        }
        assert!(RevSpec::new("HEAD~2").is_ok());
        assert!(RevSpec::new("main..feature").is_ok());
        assert!(RevSpec::new("-evil").is_err());
        assert!(RevSpec::new("").is_err());
    }

    // capabilities parses real-world version shapes (incl. the Windows build
    // trailer) and gates on the major floor only.
    #[tokio::test]
    async fn capabilities_parse_and_gate_versions() {
        let gh = Git::with_runner(ScriptedRunner::new().on(
            ["git", "--version"],
            Reply::ok("git version 2.54.0.windows.1\n"),
        ));
        let caps = gh.capabilities().await.expect("capabilities");
        assert_eq!(caps.version.to_string(), "2.54.0");
        assert!(caps.is_supported());
        caps.ensure_supported().expect("supported");

        // Two-part versions parse (patch defaults to 0); an ancient major fails
        // the gate with a clear message.
        let old = Git::with_runner(
            ScriptedRunner::new().on(["git", "--version"], Reply::ok("git version 1.9\n")),
        );
        let caps = old.capabilities().await.expect("capabilities");
        assert_eq!(
            caps.version,
            GitVersion {
                major: 1,
                minor: 9,
                patch: 0
            }
        );
        let err = caps.ensure_supported().expect_err("unsupported");
        // The message must name the floor and the found version.
        let Error::Spawn { source, .. } = &err else {
            panic!("expected Spawn, got {err:?}");
        };
        let message = source.to_string();
        assert!(message.contains(">= 2"), "names the floor: {message}");
        assert!(
            message.contains("1.9.0"),
            "names the found version: {message}"
        );

        // Garbage output is a parse error, not a silent zero version.
        let garbage = Git::with_runner(
            ScriptedRunner::new().on(["git", "--version"], Reply::ok("not a version")),
        );
        assert!(matches!(
            garbage.capabilities().await.unwrap_err(),
            Error::Parse { .. }
        ));
    }

    // clone_repo is dir-less and appends only the requested flags.
    #[tokio::test]
    async fn clone_repo_builds_flags_and_runs_dirless() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.clone_repo(
            "https://example.com/r.git",
            Path::new("/dest"),
            CloneSpec::new().branch("main").depth(1).bare(),
        )
        .await
        .expect("clone");
        let call = rec.only_call();
        assert_eq!(
            call.args_str(),
            [
                "clone",
                "--branch",
                "main",
                "--depth",
                "1",
                "--bare",
                "https://example.com/r.git",
                "/dest"
            ]
        );
        assert_eq!(call.cwd, None, "clone runs without a working directory");

        let bare = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&bare);
        git.clone_repo("u", Path::new("/d"), CloneSpec::new())
            .await
            .expect("clone");
        assert_eq!(bare.only_call().args_str(), ["clone", "u", "/d"]);
    }

    // R7: a failed clone cleans a `dest` it could have *created* (absent or empty) so
    // a retry isn't blocked by "destination already exists and is not empty" — but it
    // must NEVER delete a non-empty pre-existing dir (git would have refused, so the
    // caller's data is untouched). Scripted-fail clone + real temp dirs (only the fs
    // cleanup is real; nothing spawns).
    #[tokio::test]
    async fn clone_failure_cleans_only_a_dest_it_could_have_created() {
        use vcs_testkit::TempDir;
        let tmp = TempDir::new("r7-clone");
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["git", "clone"],
            Reply::fail(
                128,
                "fatal: could not read Username for 'https://x': prompts disabled",
            ),
        ));

        // A non-empty caller dir must survive a failed clone.
        let occupied = tmp.path().join("occupied");
        std::fs::create_dir(&occupied).unwrap();
        std::fs::write(occupied.join("keep.txt"), b"caller data").unwrap();
        assert!(
            git.clone_repo("https://x/r", &occupied, CloneSpec::new())
                .await
                .is_err()
        );
        assert!(
            occupied.join("keep.txt").exists(),
            "a non-empty caller dir must survive a failed clone"
        );

        // An empty dest we could have populated is removed on failure.
        let empty = tmp.path().join("empty");
        std::fs::create_dir(&empty).unwrap();
        assert!(
            git.clone_repo("https://x/r", &empty, CloneSpec::new())
                .await
                .is_err()
        );
        assert!(
            !empty.exists(),
            "an empty dest is cleaned so a retry isn't blocked"
        );

        // A pre-existing FILE at `dest` must survive (read_dir errs → cleanable, but
        // remove_dir_all refuses a non-dir). Pins that a future "also remove a file"
        // change can't slip in unnoticed.
        let file_dest = tmp.path().join("a-file");
        std::fs::write(&file_dest, b"caller file").unwrap();
        assert!(
            git.clone_repo("https://x/r", &file_dest, CloneSpec::new())
                .await
                .is_err()
        );
        assert!(
            file_dest.exists() && std::fs::read(&file_dest).unwrap() == b"caller file",
            "a caller's file at dest must survive a failed clone"
        );

        // A symlink `dest` → an EMPTY dir the caller owns: `read_dir` follows the
        // link and sees empty, so `cleanable` is true and `remove_dir_all` DOES run on
        // the link — it must unlink only the symlink, never delete THROUGH it. The
        // target dir (and a sibling sentinel) must survive.
        #[cfg(unix)]
        {
            let target = tmp.path().join("link-target"); // stays empty → cleanable path
            std::fs::create_dir(&target).unwrap();
            let sentinel = tmp.path().join("sibling.txt");
            std::fs::write(&sentinel, b"untouched").unwrap();
            let link = tmp.path().join("a-symlink");
            std::os::unix::fs::symlink(&target, &link).unwrap();
            assert!(
                git.clone_repo("https://x/r", &link, CloneSpec::new())
                    .await
                    .is_err()
            );
            assert!(
                target.exists() && sentinel.exists(),
                "a failed clone must unlink at most the symlink, never delete through it"
            );
        }
    }

    #[tokio::test]
    async fn tag_methods_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.tag_create(Path::new("/r"), "v1", None).await.unwrap();
        git.tag_create(Path::new("/r"), "v1", Some("abc".into()))
            .await
            .unwrap();
        git.tag_create_annotated(Path::new("/r"), AnnotatedTag::new("v2", "notes"))
            .await
            .unwrap();
        git.tag_delete(Path::new("/r"), "v1").await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["tag", "v1"]);
        assert_eq!(calls[1].args_str(), ["tag", "v1", "abc"]);
        assert_eq!(calls[2].args_str(), ["tag", "-a", "v2", "-m", "notes"]);
        assert_eq!(calls[3].args_str(), ["tag", "-d", "v1"]);
    }

    #[tokio::test]
    async fn tag_list_splits_lines() {
        let git = Git::with_runner(
            ScriptedRunner::new().on(["git", "tag", "--list"], Reply::ok("v1\nv2.0\n")),
        );
        assert_eq!(git.tag_list(Path::new(".")).await.unwrap(), ["v1", "v2.0"]);
    }

    // The line-parsed list commands must pass `--no-column`: a user's
    // `column.ui = always` would pack several names per line, and
    // `color.{ui,branch} = always` would inject ANSI escapes — both even when
    // piped. Branch listings disable both; `git tag` isn't colorized, so it only
    // needs `--no-column`.
    #[tokio::test]
    async fn list_commands_disable_column_and_color() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.branches(Path::new(".")).await.unwrap();
        git.is_merged(Path::new("."), MergeCheck::branch("b").into_base("main"))
            .await
            .unwrap();
        git.tag_list(Path::new(".")).await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["branch", "--no-column", "--no-color"]);
        assert_eq!(
            calls[1].args_str(),
            ["branch", "--merged", "main", "--no-column", "--no-color"]
        );
        assert_eq!(calls[2].args_str(), ["tag", "--list", "--no-column"]);
    }

    // Commands whose failure output feeds the error classifiers must force the
    // C locale — a translated message would defeat the substring matching.
    #[tokio::test]
    async fn classified_commands_force_c_locale() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.commit(Path::new("."), "msg").await.unwrap();
        git.merge_commit(Path::new("."), MergeCommit::branch("b"))
            .await
            .unwrap();
        git.merge_squash(Path::new("."), "b").await.unwrap();
        git.merge_no_commit(Path::new("."), MergeNoCommit::branch("b"))
            .await
            .unwrap();
        git.cherry_pick(Path::new("."), "abc").await.unwrap();
        git.stash_pop(Path::new(".")).await.unwrap();
        git.fetch(Path::new(".")).await.unwrap();
        for call in rec.calls() {
            assert!(
                call.envs.iter().any(|(k, v)| {
                    k.to_str() == Some("LC_ALL")
                        && v.as_deref().and_then(|o| o.to_str()) == Some("C")
                }),
                "{:?} should force LC_ALL=C",
                call.args_str()
            );
        }
    }

    // The `<rev>:<path>` spec requires forward slashes — Windows callers may
    // hand in backslashes. The normalisation is Windows-only.
    #[cfg(windows)]
    #[tokio::test]
    async fn show_file_normalises_path_separators() {
        let rec = RecordingRunner::replying(Reply::ok("content\n"));
        let git = Git::with_runner(&rec);
        let out = git
            .show_file(Path::new("/r"), "HEAD", "sub\\dir\\f.txt")
            .await
            .expect("show_file");
        // The blob's trailing newline is preserved verbatim (H7) — not trimmed.
        assert_eq!(out, "content\n");
        assert_eq!(rec.only_call().args_str(), ["show", "HEAD:sub/dir/f.txt"]);
    }

    // H7: content verbs return git's output byte-for-byte — the round-trip-corrupting
    // cases are multiple trailing newlines and a missing final newline.
    #[tokio::test]
    async fn content_verbs_preserve_exact_trailing_bytes() {
        for raw in ["a\nb\n\n", "no-final-newline", "trailing spaces   \n"] {
            let rec = RecordingRunner::replying(Reply::ok(raw));
            let git = Git::with_runner(&rec);
            let out = git
                .show_file(Path::new("/r"), "HEAD", "f.txt")
                .await
                .expect("show_file");
            assert_eq!(out, raw, "show_file returns bytes verbatim");
        }
        // diff_text is verbatim too (its trailing blank context line must survive so
        // the last hunk stays in sync with its `@@` count).
        let diff = "diff --git a/f b/f\n@@ -1,2 +1,2 @@\n-x\n+y\n \n";
        let rec = RecordingRunner::replying(Reply::ok(diff));
        let git = Git::with_runner(&rec);
        assert_eq!(
            git.diff_text(Path::new("/r"), DiffSpec::Rev("HEAD".into()))
                .await
                .expect("diff_text"),
            diff
        );
    }

    // On Unix a backslash is a legal filename byte — the spec must pass through
    // verbatim so a literal `a\b.txt` stays resolvable.
    #[cfg(not(windows))]
    #[tokio::test]
    async fn show_file_keeps_backslashes_on_unix() {
        let rec = RecordingRunner::replying(Reply::ok("content\n"));
        let git = Git::with_runner(&rec);
        git.show_file(Path::new("/r"), "HEAD", "sub\\dir\\f.txt")
            .await
            .expect("show_file");
        assert_eq!(rec.only_call().args_str(), ["show", "HEAD:sub\\dir\\f.txt"]);
    }

    // config --get: exit 0 → Some(value), exit 1 → None (unset), other → error.
    #[tokio::test]
    async fn config_get_maps_exit_codes() {
        let set = Git::with_runner(
            ScriptedRunner::new().on(["git", "config", "--get"], Reply::ok("Alice\n")),
        );
        assert_eq!(
            set.config_get(Path::new("."), "user.name").await.unwrap(),
            Some("Alice".to_string())
        );
        // Only git's trailing newline (here `\r\n`) is stripped — a value's own
        // trailing spaces are preserved (they can be meaningful).
        let spaced = Git::with_runner(
            ScriptedRunner::new().on(["git", "config", "--get"], Reply::ok("prefix:  \r\n")),
        );
        assert_eq!(
            spaced.config_get(Path::new("."), "x.y").await.unwrap(),
            Some("prefix:  ".to_string())
        );
        let unset = Git::with_runner(
            ScriptedRunner::new().on(["git", "config", "--get"], Reply::fail(1, "")),
        );
        assert_eq!(
            unset.config_get(Path::new("."), "user.name").await.unwrap(),
            None
        );
        // A multi-valued key (exit 2) or worse is a real error.
        let multi = Git::with_runner(ScriptedRunner::new().on(
            ["git", "config", "--get"],
            Reply::fail(2, "multiple values"),
        ));
        assert!(
            multi
                .config_get(Path::new("."), "remote.all")
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn blame_builds_rev_before_pathspec_separator() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.blame(Path::new("/r"), "src/lib.rs", Some("HEAD~1".into()))
            .await
            .unwrap();
        git.blame(Path::new("/r"), "src/lib.rs", None)
            .await
            .unwrap();
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["blame", "--line-porcelain", "HEAD~1", "--", "src/lib.rs"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["blame", "--line-porcelain", "--", "src/lib.rs"]
        );
    }

    // revert must never open an editor: --no-edit plus the env backstop.
    #[tokio::test]
    async fn sequencer_methods_suppress_editors() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.revert(Path::new("/r"), "abc").await.unwrap();
        git.cherry_pick(Path::new("/r"), "abc").await.unwrap();
        git.rebase_skip(Path::new("/r")).await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["revert", "--no-edit", "abc"]);
        assert_eq!(calls[1].args_str(), ["cherry-pick", "abc"]);
        assert_eq!(calls[2].args_str(), ["rebase", "--skip"]);
        for call in &calls {
            assert!(
                call.envs
                    .iter()
                    .any(|(k, _)| k.to_str() == Some("GIT_EDITOR")),
                "editor suppressed on {:?}",
                call.args_str()
            );
        }
    }

    // harden() scrubs GIT_EDITOR/GIT_SEQUENCE_EDITOR from the inherited
    // environment, but a sequencer command sets its own `GIT_EDITOR=true` per call
    // (no_editor). `command_in` applies the client-level removal eagerly, so the env
    // list ends up `[…, (GIT_EDITOR, None), …, (GIT_EDITOR, "true")]` — and at spawn
    // each op is applied in order (processkit's `Command` does `env_remove` then
    // `env`), so the LAST write wins. The effective value MUST be `true`, else a
    // hardened `revert`/`cherry-pick`/`rebase` would lose its no-op editor and hang
    // a headless caller. Pin that effective-precedence (fold in spawn order).
    #[tokio::test]
    async fn hardened_sequencer_keeps_its_no_op_editor() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec).harden();
        git.revert(Path::new("/r"), "abc").await.unwrap();
        let call = rec.only_call();
        // Resolve each editor var the way the OS does: last op for the key wins.
        let effective = |var: &str| {
            call.envs
                .iter()
                .rfind(|(k, _)| k.to_str() == Some(var))
                .and_then(|(_, v)| v.as_deref())
                .and_then(|v| v.to_str())
        };
        // Both no-op editors must survive harden()'s scrub (symmetric precedence),
        // else a hardened sequencer command hangs a headless caller.
        assert_eq!(
            effective("GIT_EDITOR"),
            Some("true"),
            "the per-command no-op editor must survive harden()'s scrub"
        );
        assert_eq!(
            effective("GIT_SEQUENCE_EDITOR"),
            Some("true"),
            "the per-command no-op sequence editor must survive harden()'s scrub"
        );
    }

    #[tokio::test]
    async fn remote_add_and_set_url_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.remote_add(Path::new("/r"), "up", "https://x/y.git")
            .await
            .unwrap();
        git.remote_set_url(Path::new("/r"), "up", "https://x/z.git")
            .await
            .unwrap();
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["remote", "add", "up", "https://x/y.git"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["remote", "set-url", "up", "https://x/z.git"]
        );
    }

    // Dirty tree that stashes: status → list(before) → push → list(after, deeper) →
    // checkout → pop --index, in that order.
    #[tokio::test]
    async fn switch_with_stash_round_trips_dirty_tree() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["git", "status"], Reply::ok(" M a.rs\0"))
                // Stash-list depth goes 0 → 1, so the push is known to have saved.
                .on_sequence(
                    ["git", "stash", "list"],
                    [Reply::ok(""), Reply::ok("stash@{0}: WIP on main\n")],
                )
                .on(["git", "stash", "push"], Reply::ok(""))
                .on(["git", "checkout"], Reply::ok(""))
                .on(["git", "stash", "pop"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        git.switch_with_stash(Path::new("/r"), "feature")
            .await
            .expect("switch");
        let calls = rec.calls();
        assert_eq!(calls.len(), 6);
        assert_eq!(
            calls[2].args_str(),
            ["stash", "push", "--include-untracked"]
        );
        assert_eq!(calls[4].args_str(), ["checkout", "feature", "--"]);
        // `--index` restores the staged/unstaged split (M12).
        assert_eq!(calls[5].args_str(), ["stash", "pop", "--index"]);
    }

    // M12: a dirty tree whose dirt `stash push` can't save (e.g. a submodule-only
    // change) — the stash-list depth is unchanged, so we must NOT pop an unrelated
    // pre-existing stash. Switch as-is.
    #[tokio::test]
    async fn switch_with_stash_does_not_pop_when_push_saved_nothing() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["git", "status"], Reply::ok(" M sub\0"))
                // Depth stays 1 across the push → nothing was actually stashed.
                .on(
                    ["git", "stash", "list"],
                    Reply::ok("stash@{0}: someone else's WIP\n"),
                )
                .on(
                    ["git", "stash", "push"],
                    Reply::ok("No local changes to save\n"),
                )
                .on(["git", "checkout"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        git.switch_with_stash(Path::new("/r"), "feature")
            .await
            .expect("switch");
        assert!(
            rec.calls()
                .iter()
                .all(|c| c.args_str() != ["stash", "pop", "--index"]
                    && c.args_str() != ["stash", "pop"]),
            "must not pop an unrelated stash when the push saved nothing"
        );
    }

    // A clean tree skips the stash round-trip — a no-op `stash push` would make
    // the later pop grab an older, unrelated stash.
    #[tokio::test]
    async fn switch_with_stash_skips_stash_on_clean_tree() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["git", "status"], Reply::ok(""))
                .on(["git", "checkout"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        git.switch_with_stash(Path::new("/r"), "feature")
            .await
            .expect("switch");
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert!(calls.iter().all(|c| c.args_str()[0] != "stash"));
    }

    // A failed checkout pops the stash back (we are still on the original
    // branch) and surfaces the checkout error.
    #[tokio::test]
    async fn switch_with_stash_restores_on_checkout_failure() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["git", "status"], Reply::ok(" M a.rs\0"))
                .on_sequence(
                    ["git", "stash", "list"],
                    [Reply::ok(""), Reply::ok("stash@{0}: WIP on main\n")],
                )
                .on(["git", "stash", "push"], Reply::ok(""))
                .on(
                    ["git", "checkout"],
                    Reply::fail(1, "error: pathspec 'nope'"),
                )
                .on(["git", "stash", "pop"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        let err = git
            .switch_with_stash(Path::new("/r"), "nope")
            .await
            .expect_err("checkout error must surface");
        assert!(matches!(err, Error::Exit { .. }));
        let calls = rec.calls();
        assert_eq!(
            calls.last().unwrap().args_str(),
            ["stash", "pop", "--index"],
            "restoring pop ran with --index"
        );
    }

    // `fetch_from` names the remote, keeps the prompt off, and shares the
    // transient retry.
    #[tokio::test]
    async fn fetch_from_builds_args_and_retries() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.fetch_from(Path::new("/r"), "upstream")
            .await
            .expect("fetch_from");
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["fetch", "--quiet", "upstream"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));

        let failing = RecordingRunner::replying(Reply::fail(128, "fatal: Connection timed out"));
        let git = Git::with_runner(&failing);
        assert!(git.fetch_from(Path::new("/r"), "upstream").await.is_err());
        assert_eq!(failing.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // The consumer-facing mock seam: a function depending on `&dyn GitApi` is
    // tested with a generated mock.
    #[cfg(feature = "mock")]
    #[tokio::test]
    async fn consumer_mocks_the_interface() {
        async fn on_branch(git: &dyn GitApi, want: &str) -> bool {
            git.current_branch(Path::new(".")).await.unwrap().as_deref() == Some(want)
        }
        let mut mock = MockGitApi::new();
        mock.expect_current_branch()
            .returning(|_| Ok(Some("main".to_string())));
        assert!(on_branch(&mock, "main").await);
    }
}

// Long-form how-to guides, rendered from this crate's docs/*.md on docs.rs.
#[doc = include_str!("../docs/git.md")]
#[allow(rustdoc::broken_intra_doc_links)]
pub mod guide {
    #[doc = include_str!("../docs/security.md")]
    #[allow(rustdoc::broken_intra_doc_links)]
    pub mod security {}
    #[doc = include_str!("../docs/conflicts.md")]
    #[allow(rustdoc::broken_intra_doc_links)]
    pub mod conflicts {}
}