mahbot 0.10.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Git subprocess wrappers — run git commands and parse porcelain/numstat output.
//! Diff output parsing lives in [`crate::git::diff_parse`].

use anyhow::Context;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tracing::warn;

use crate::tools::shell::{internal_env_pairs, program_command};
use crate::util::unquote_c_style;

/// Result of a successful `git commit` — the full hash and line stats.
#[derive(Debug, Clone)]
pub struct CommitInfo {
    /// Full 40-character SHA from `git rev-parse HEAD`.
    pub hash: String,
    pub lines_added: i64,
    pub lines_removed: i64,
}

impl CommitInfo {
    /// First 7 characters of the hash, or the whole hash if it is shorter.
    #[must_use]
    pub fn short_hash(&self) -> &str {
        self.hash.get(..7).unwrap_or(&self.hash)
    }
}

/// Maximum size (1 MiB) for reading untracked files. Larger ones are surfaced via
/// [`DiffStats::huge_binary_file_count`] and shown as a placeholder, never line-counted.
pub(crate) const MAX_UNTRACKED_SIZE: u64 = 1024 * 1024;

/// Cap on untracked files classified per snapshot refresh; the rest land in
/// [`DiffStats::omitted_file_count`].
const MAX_UNTRACKED_FILES_COUNTED: usize = 500;
/// Cap on bytes read from untracked files per snapshot refresh.
const MAX_UNTRACKED_BYTES_READ: u64 = 10 * 1024 * 1024;

/// Classification of an untracked file read for diff display / line counting.
pub(crate) enum UntrackedFileRead {
    Text(String),
    TooLarge(u64),
    Binary,
    Skip,
}

/// Classify an in-memory buffer whose size already passed the [`MAX_UNTRACKED_SIZE`]
/// gate; `None` means binary (a null byte, or invalid UTF-8). The rule lives here so the
/// snapshot and the diff window cannot disagree about it.
fn classify_untracked_content(content: Vec<u8>) -> Option<String> {
    if content.contains(&0) {
        return None;
    }
    String::from_utf8(content).ok()
}

/// Read and classify an untracked file whose metadata the caller already holds, so
/// neither this nor the snapshot's byte budget stats the file twice.
async fn read_untracked_file_with_meta(path: &Path, meta: &std::fs::Metadata) -> UntrackedFileRead {
    if !meta.is_file() {
        return UntrackedFileRead::Skip;
    }
    if meta.len() > MAX_UNTRACKED_SIZE {
        return UntrackedFileRead::TooLarge(meta.len());
    }
    let Ok(content) = tokio::fs::read(path).await else {
        return UntrackedFileRead::Skip;
    };
    // Invalid UTF-8 without a null byte is still binary — never Skip, or the
    // GUI would silently drop the file instead of showing a placeholder.
    classify_untracked_content(content).map_or(UntrackedFileRead::Binary, UntrackedFileRead::Text)
}

/// Read and classify one untracked file for the diff window: fetch its metadata, then
/// delegate to the shared [`read_untracked_file_with_meta`] core.
pub(crate) async fn read_untracked_file(path: &Path) -> UntrackedFileRead {
    let Ok(meta) = tokio::fs::metadata(path).await else {
        return UntrackedFileRead::Skip;
    };
    read_untracked_file_with_meta(path, &meta).await
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscardTarget {
    File,
    /// Recursively, including subdirectories.
    Directory,
}

/// Whether the directory holds a `.git` entry (a file for worktrees, a directory otherwise).
#[must_use]
pub fn is_git_repo(path: &Path) -> bool {
    path.join(".git").exists()
}

/// Run `git show -m <hash> --no-color --find-renames --format=` — the diff a historical
/// commit introduced. `-m` splits merges into per-parent diffs, so the same path may
/// appear once per parent in the tree; that is expected. `--format=` drops the log header.
pub(crate) async fn run_git_show_diff(repo_path: &Path, hash: &str) -> anyhow::Result<String> {
    run_git_command(
        repo_path,
        &[
            "show",
            "-m",
            hash,
            "--no-color",
            "--find-renames",
            "--format=",
        ],
    )
    .await
}

/// Run `git diff <base> --no-color --find-renames` against the working tree, where `base` is `HEAD`
/// or this repository's empty tree on an unborn HEAD. `--find-renames` is explicit so rename
/// detection matches [`run_git_worktree_numstat`] regardless of repository config.
pub(crate) async fn run_git_worktree_diff(
    repo_path: &Path,
    unborn_head: bool,
) -> anyhow::Result<String> {
    let base = if unborn_head {
        run_git_empty_tree(repo_path).await?
    } else {
        "HEAD".to_string()
    };
    run_git_command(repo_path, &["diff", &base, "--no-color", "--find-renames"]).await
}

/// Run `git status --porcelain --untracked-files=normal`.
pub async fn run_git_status(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(
        repo_path,
        &["status", "--porcelain", "--untracked-files=normal"],
    )
    .await
}

/// Run `git status --porcelain --untracked-files=all`: `-uall` names individual files inside
/// untracked directories (repo-root-relative) rather than collapsing them to `dir/`, so one reading
/// names every file the footer counts and the diff window shows. It is the snapshot's one unbounded
/// read — a collapsed entry cannot be expanded later — while content reads stay capped by
/// `MAX_UNTRACKED_*`.
async fn run_git_status_all(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(
        repo_path,
        &["status", "--porcelain", "--untracked-files=all"],
    )
    .await
}

/// Run `git show HEAD:<path>` or, when `commit_ref` is `Some`, `git show <ref>:<path>`.
/// `None` means the file is absent at that ref (new/untracked, or `~1` of a root commit)
/// or git failed. Callers build the parent ref themselves: `format!("{hash}~1")`.
pub async fn run_git_show(
    repo_path: &Path,
    file_path: &str,
    commit_ref: Option<&str>,
) -> Option<String> {
    let show_arg = if let Some(hash) = commit_ref {
        format!("{hash}:{file_path}")
    } else {
        format!("HEAD:{file_path}")
    };
    run_git_command(repo_path, &["show", &show_arg]).await.ok()
}

/// Resolve the repository top-level (the `.git`-containing ancestor of `repo_path`, which may
/// itself be a subdirectory). [`is_git_repo`] uses `exists()` because `.git` is a directory for
/// normal repos and a *file* for linked worktrees/submodules. Deliberately not `git rev-parse
/// --show-toplevel`: discovery runs the dubious-ownership check this exists to satisfy, so it would
/// recurse into the same failure. The result is canonicalized and has the Windows verbatim prefix
/// dropped, because git receives it and must see its own spelling.
pub(crate) fn resolve_git_top_level(repo_path: &Path) -> Option<PathBuf> {
    let dir = repo_path.ancestors().find(|dir| is_git_repo(dir))?;
    Some(crate::util::strip_verbatim_prefix(
        &std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()),
    ))
}

/// Inject the repo top-level into git's per-process config as `safe.directory` via the
/// `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` env form: it never writes the user's
/// global gitconfig and never uses `*` (which would opt out of the CVE ownership guard). Git < 2.38
/// silently ignores the env form — acceptable while the repo is owned by the running user.
fn inject_safe_directory(cmd: &mut std::process::Command, repo_path: &Path) {
    let Some(top_level) = resolve_git_top_level(repo_path) else {
        return;
    };
    cmd.env("GIT_CONFIG_COUNT", "1");
    cmd.env("GIT_CONFIG_KEY_0", "safe.directory");
    cmd.env("GIT_CONFIG_VALUE_0", top_level.as_path());
}

/// Create a `git` [`std::process::Command`] with the product's internal environment — the
/// shared setup of every git subprocess here. The environment is cleared and re-populated
/// with the reduced set of [`internal_env_pairs`] to prevent credential leakage (CWE-200),
/// plus `LC_ALL=C` for consistent locale behavior. [`git_command`] wraps this for async
/// callers; [`tracked_paths`] runs it directly mid directory-walk.
///
/// `repo_root` is the workspace/`current_dir` for repo-bound invocations, and its resolved
/// top-level is injected as `safe.directory` (see [`inject_safe_directory`]) so git works on
/// repos owned by another UID. Pass `None` for repo-agnostic calls (e.g. [`git_is_installed`]).
fn git_std_command(repo_root: Option<&Path>) -> std::process::Command {
    // `program_command` applies the pairs it names `git` under. No directory is passed:
    // the internal list is absolute, so a later `current_dir` cannot change the program.
    let mut cmd = program_command("git", &internal_env_pairs(), None);
    cmd.env("LC_ALL", "C");
    if let Some(path) = repo_root {
        inject_safe_directory(&mut cmd, path);
    }
    cmd
}

/// Async form of [`git_std_command`] and the only entry point for production async git
/// subprocess creation in this module.
fn git_command(repo_root: Option<&Path>) -> tokio::process::Command {
    git_std_command(repo_root).into()
}

/// Every UTF-8 path `repo`'s index holds, repository-relative and `/`-separated — git's own answer
/// to "is this path tracked?", which no ignore rule overrides. Non-UTF-8 entries are left out, as
/// such a walked path never reaches the snapshot either.
///
/// `None` when git cannot answer (not installed, not a repo, unreadable index, failed run); callers
/// read that as "git cannot say", so paths the rules would hide stay visible. Synchronous on
/// purpose — its only caller asks mid directory-walk — and `GIT_OPTIONAL_LOCKS=0` keeps the read
/// from locking the index.
pub(crate) fn tracked_paths(repo: &Path) -> Option<Vec<String>> {
    let mut cmd = git_std_command(Some(repo));
    cmd.current_dir(repo)
        // `core.fsmonitor` would run a command this repository's own config names; a
        // passive read of the index never needs that.
        .args(["-c", "core.fsmonitor=false", "ls-files", "-z", "--cached"])
        .env("GIT_OPTIONAL_LOCKS", "0")
        .stdin(Stdio::null())
        .stderr(Stdio::null());
    let output = cmd.output().ok()?;
    if !output.status.success() {
        return None;
    }
    Some(
        output
            .stdout
            .split(|&byte| byte == 0)
            .filter_map(|path| std::str::from_utf8(path).ok())
            .filter(|path| !path.is_empty())
            .map(str::to_string)
            .collect(),
    )
}

/// Run a git command without interpreting the exit code: the raw [`std::process::Output`], so each
/// caller decides; [`run_git_command_env`] is the checked-output sibling.
pub(crate) async fn run_git_output(
    repo_path: &Path,
    args: &[&str],
) -> anyhow::Result<std::process::Output> {
    run_git_output_env(repo_path, &[], args).await
}

/// [`run_git_output`] with extra environment variables — used to point git at a throwaway
/// index file instead of the repository's own.
async fn run_git_output_env(
    repo_path: &Path,
    env: &[(&str, &OsStr)],
    args: &[&str],
) -> anyhow::Result<std::process::Output> {
    let mut cmd = git_command(Some(repo_path));
    for (name, value) in env {
        cmd.env(name, value);
    }
    cmd.args(args).current_dir(repo_path);
    // Tokio's `output()` inherits stdin (std's nulls it) and no git command here reads
    // stdin; `hash-object --stdin` needs EOF, not a terminal, so it can never wait on us.
    cmd.stdin(Stdio::null());
    cmd.output()
        .await
        .with_context(|| format!("Failed to run git {}", args.join(" ")))
}

/// Run a git command and return stdout as a string, erroring on a non-zero exit status.
pub async fn run_git_command(repo_path: &Path, args: &[&str]) -> anyhow::Result<String> {
    run_git_command_env(repo_path, &[], args).await
}

/// [`run_git_command`] with extra environment variables set (a throwaway index, say).
async fn run_git_command_env(
    repo_path: &Path,
    env: &[(&str, &OsStr)],
    args: &[&str],
) -> anyhow::Result<String> {
    let output = run_git_output_env(repo_path, env, args).await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git {} failed: {stderr}", args.join(" "));
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Run a git command and return its trimmed stdout — shared by the helpers that return a
/// single scalar (hash, branch, message).
async fn run_git_trimmed(repo_path: &Path, args: &[&str]) -> anyhow::Result<String> {
    Ok(run_git_command(repo_path, args).await?.trim().to_string())
}

/// [`run_git_trimmed`] with extra environment variables set.
async fn run_git_trimmed_env(
    repo_path: &Path,
    env: &[(&str, &OsStr)],
    args: &[&str],
) -> anyhow::Result<String> {
    Ok(run_git_command_env(repo_path, env, args)
        .await?
        .trim()
        .to_string())
}

/// Whether `git status --porcelain` output holds any unstaged change: a line whose worktree column
/// (byte 1) is non-space — an unstaged modification, deletion or `??` untracked. Fully-staged
/// entries are ignored.
///
/// Byte-level rather than a record parse: an entry whose path no parser accepts still counts, so a
/// dirty tree is never mistaken for a clean one (`!!` lines would count too; no caller asks for
/// them). Pure parsing — callers run `git status` and pass the stdout.
#[must_use]
pub fn has_unstaged_changes(porcelain: &str) -> bool {
    porcelain.lines().any(|line| {
        let line = line.trim_end();
        if line.is_empty() {
            return false;
        }
        // Worktree column (byte 1): non-space for `??`, ` M`, `MM`, ` D`; space for `M `.
        line.as_bytes().get(1).is_some_and(|&b| b != b' ')
    })
}

/// Stage all changes — tracked modifications, untracked files, deletions — via `git add -A`.
/// Staging only: unlike [`run_git_commit`], nothing is committed.
pub async fn run_git_add_all(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(repo_path, &["add", "-A"]).await
}

/// Run `git rev-parse HEAD` and return the trimmed commit hash. Errors when HEAD cannot be
/// resolved (no commits yet); use `.ok()` where unknown must read as `None`.
pub async fn run_git_head(repo_path: &Path) -> anyhow::Result<String> {
    run_git_trimmed(repo_path, &["rev-parse", "HEAD"]).await
}

/// Run `git write-tree` and return the trimmed index tree hash — the exact staged content.
/// Errors when the index cannot be written (unmerged entries); `.ok()` for `None` semantics.
pub async fn run_git_write_tree(repo_path: &Path) -> anyhow::Result<String> {
    run_git_trimmed(repo_path, &["write-tree"]).await
}

/// The current content identity of the working tree: `(HEAD, tree)`, where the tree is what
/// a `git add -A` would stage (tracked modifications, untracked files, deletions,
/// `.gitignore` honoured).
pub async fn run_git_worktree_identity(repo_path: &Path) -> anyhow::Result<(String, String)> {
    let dir = tempfile::tempdir().context("Failed to create a throwaway git index")?;
    let index = dir.path().join("index");
    // Seed from the repository's own index: unseeded, a tracked path matched by `.gitignore` is
    // dropped (ignore rules govern new index entries), so the tree would disagree with the real
    // `git add -A`. A split index needs nothing extra — its shared file is looked up through
    // the repository.
    //
    // No index yet is normal: git creates the throwaway one from nothing. A failed copy is
    // warned, since the tree would be built unseeded. A repo git cannot resolve is not reported
    // here — `add -A` fails on the same condition.
    if let Ok(path) = run_git_trimmed(repo_path, &["rev-parse", "--git-path", "index"]).await {
        let path = PathBuf::from(path);
        let path = if path.is_absolute() {
            path
        } else {
            repo_path.join(path)
        };
        match tokio::fs::copy(&path, &index).await {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                warn!(error = %e, path = %path.display(), "Could not seed the throwaway git index");
            }
            _ => {}
        }
    }
    let env = [("GIT_INDEX_FILE", index.as_os_str())];
    run_git_trimmed_env(repo_path, &env, &["add", "-A"]).await?;
    let tree = run_git_trimmed_env(repo_path, &env, &["write-tree"]).await?;
    Ok((run_git_head(repo_path).await?, tree))
}

/// Stage all changes and commit: `git add -A`, `git commit -m <message>`, then the SHA via
/// `git rev-parse HEAD` and line stats via `git diff --numstat`.
pub async fn run_git_commit(repo_path: &Path, message: &str) -> anyhow::Result<CommitInfo> {
    run_git_add_all(repo_path).await?;

    run_git_command(repo_path, &["commit", "-m", message])
        .await
        .context("Failed to commit changes")?;

    // The full 40-char SHA from `rev-parse`, not an abbreviation.
    let hash = match run_git_head(repo_path).await {
        Ok(hash) => hash,
        Err(e) => {
            warn!(
                error = %e,
                "git rev-parse HEAD failed after successful commit — commit exists, returning unknown hash"
            );
            return Ok(CommitInfo {
                hash: "unknown".into(),
                lines_added: 0,
                lines_removed: 0,
            });
        }
    };

    // Line stats from `--numstat`, trying HEAD~1..HEAD first.
    let (lines_added, lines_removed) =
        if let Ok(stats) = parse_numstat(repo_path, &["HEAD~1..HEAD"]).await {
            stats
        } else if let Ok(base) = run_git_empty_tree(repo_path).await {
            // HEAD~1 does not exist (first commit) — diff against this repository's empty tree.
            parse_numstat(repo_path, &[&base, "HEAD"])
                .await
                .unwrap_or((0, 0))
        } else {
            (0, 0)
        };
    Ok(CommitInfo {
        hash,
        lines_added,
        lines_removed,
    })
}

/// Broadcast for pipeline auto-commit notifications: the pipeline sends the repo path after a
/// successful auto-commit (sanitation → Done) and the GUI subscription refreshes the footer,
/// since a commit is a ref-only change the file watcher never reports. It lives here so the
/// pipeline can signal without depending on the GUI layer.
pub(crate) static GIT_COMMIT_TX: OnceLock<tokio::sync::broadcast::Sender<PathBuf>> =
    OnceLock::new();

/// Initialise the git-commit broadcast; called from [`crate::gui::init_git_commit_tx`] in
/// `main` before the iced application runs.
pub(crate) fn init_git_commit_tx() {
    let _ = GIT_COMMIT_TX.set(tokio::sync::broadcast::channel(64).0);
}

/// Notify the GUI that a pipeline auto-commit completed on `repo_path`, so the git footer
/// refreshes promptly instead of waiting for the periodic timer.
pub(crate) fn notify_git_commit(repo_path: &Path) {
    if let Some(tx) = GIT_COMMIT_TX.get() {
        let _ = tx.send(repo_path.to_path_buf());
    }
}

/// A single entry from `git diff --numstat` / `git show --numstat` output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumstatEntry {
    /// `None` if the file is binary.
    pub additions: Option<i64>,
    /// `None` if the file is binary.
    pub deletions: Option<i64>,
    /// File path as printed by git.
    pub path: String,
}

/// Parse `git diff --numstat` / `git show --numstat` output. Malformed lines are skipped.
/// Pure parsing, no I/O — callers run git and pass the captured stdout here.
#[must_use]
pub fn parse_numstat_lines(stdout: &str) -> Vec<NumstatEntry> {
    let mut result = Vec::new();
    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        // Format: <additions>\t<deletions>\t<path>
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() != 3 {
            continue;
        }

        let additions_str = parts[0];
        let deletions_str = parts[1];
        let path = parts[2].to_string();

        // Binary files print "-\t-\t<path>": if either field is "-", treat both as None.
        // Git always prints both, but the mixed case is handled conservatively.
        if additions_str == "-" || deletions_str == "-" {
            result.push(NumstatEntry {
                additions: None,
                deletions: None,
                path,
            });
            continue;
        }

        let additions: i64 = additions_str.parse().unwrap_or(0);
        let deletions: i64 = deletions_str.parse().unwrap_or(0);
        result.push(NumstatEntry {
            additions: Some(additions),
            deletions: Some(deletions),
            path,
        });
    }
    result
}

/// Run `git diff --numstat <range...>` and return the per-file entries. Callers pass only the
/// range (e.g. `&["HEAD"]` or `&["<empty-tree>", "HEAD"]`).
async fn run_git_diff_numstat(
    repo_path: &Path,
    range: &[&str],
) -> anyhow::Result<Vec<NumstatEntry>> {
    let mut args = vec!["diff", "--numstat"];
    args.extend_from_slice(range);
    let stdout = run_git_command(repo_path, &args).await?;
    Ok(parse_numstat_lines(&stdout))
}

/// Run `git diff --numstat <range...>` and sum the line stats across all files, returning
/// `Ok((added, removed))` even for an empty diff; a git failure comes back as the error.
async fn parse_numstat(repo_path: &Path, range: &[&str]) -> anyhow::Result<(i64, i64)> {
    let entries = run_git_diff_numstat(repo_path, range).await?;

    let mut lines_added: i64 = 0;
    let mut lines_removed: i64 = 0;

    for entry in entries {
        // Binary files are None — they contribute 0 lines.
        if let Some(added) = entry.additions {
            lines_added += added;
        }
        if let Some(removed) = entry.deletions {
            lines_removed += removed;
        }
    }

    Ok((lines_added, lines_removed))
}

/// Whether git is installed.
pub async fn git_is_installed() -> bool {
    let mut cmd = git_command(None);
    cmd.arg("--version");
    cmd.output().await.is_ok_and(|o| o.status.success())
}

/// Whether the repo has any commits (spawn/git failures count as `false`).
async fn git_has_commits(repo_path: &Path) -> bool {
    run_git_head(repo_path).await.is_ok()
}

/// This repository's empty tree hash.
async fn run_git_empty_tree(repo_path: &Path) -> anyhow::Result<String> {
    run_git_trimmed(repo_path, &["hash-object", "-t", "tree", "--stdin"]).await
}

/// The current branch name (e.g. `main`, `feature/xyz`).
pub async fn run_git_current_branch(repo_path: &Path) -> anyhow::Result<String> {
    run_git_trimmed(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]).await
}

/// What the branch and its upstream each carry without the other.
#[derive(Debug, Clone, Copy)]
struct UpstreamCounts {
    behind: usize,
    ahead: usize,
}

/// Measure the branch against `upstream` (`--left-right` puts upstream first).
async fn ahead_behind(repo_path: &Path, upstream: &str) -> anyhow::Result<UpstreamCounts> {
    let counts = run_git_trimmed(
        repo_path,
        &[
            "rev-list",
            "--count",
            "--left-right",
            &format!("{upstream}...HEAD"),
        ],
    )
    .await?;
    let (behind, ahead) = counts
        .split_once('\t')
        .with_context(|| format!("git rev-list printed {counts:?}"))?;
    Ok(UpstreamCounts {
        behind: behind.trim().parse()?,
        ahead: ahead.trim().parse()?,
    })
}

/// Where the sync control pushes the checked-out branch, and what it carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitPushTarget {
    pub remote: String,
    /// Commits a press carries: what `remote` lacks of the branch as the update step
    /// leaves it, or every commit the branch carries when it is published or `remote`
    /// could not be asked.
    pub commits: usize,
    /// Whether `remote` lacks a branch of this name: `Some(true)` publishes it (the
    /// update step is skipped), `Some(false)` it exists, `None` when `remote` could not
    /// be asked — then neither is claimed.
    pub publish: Option<bool>,
}

/// Where the checked-out branch can be pushed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitPushDestination {
    /// A remote accepts pushes: the one a plain `git push` reaches, the branch's tracked
    /// remote, or the only push-capable remote.
    Target(GitPushTarget),
    /// No remote accepts pushes, or several do: nothing is guessed and the control says
    /// why instead of staying hidden.
    Nowhere { reason: String },
}

/// The checked-out branch's remote state, as the footer's sync control shows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitRemoteState {
    /// The branch this state describes: the footer caches it across refreshes, so a branch
    /// switched since then makes the state stale rather than wrong.
    pub branch: String,
    /// Commits the branch would pull from its own update source.
    pub behind: usize,
    /// Where a push would go.
    pub push: GitPushDestination,
}

impl GitRemoteState {
    /// Whether the sync control has anything to offer: commits to pull, commits to push, or
    /// a branch no reachable remote can take (which the control says plainly, not by hiding).
    #[must_use]
    pub fn has_sync_work(&self) -> bool {
        match &self.push {
            GitPushDestination::Nowhere { .. } => true,
            GitPushDestination::Target(target) => self.behind > 0 || target.commits > 0,
        }
    }
}

/// Resolve the checked-out branch's remote state for the footer's sync control.
pub async fn run_git_remote_state(repo_path: &Path) -> anyhow::Result<Option<GitRemoteState>> {
    let Some(lane) = resolve_push_lane(repo_path).await? else {
        return Ok(None);
    };
    Ok(Some(GitRemoteState {
        branch: lane.branch,
        behind: lane.upstream_counts.map_or(0, |counts| counts.behind),
        push: lane.destination,
    }))
}

/// The remotes git resolves for a branch: the one it tracks for updates and the one a plain
/// `git push` sends to.
struct BranchRemotes {
    /// The tracked remote, even when its remote-tracking ref is gone; `None` if it tracks nothing.
    upstream: Option<String>,
    /// The remote-tracking ref the upstream names, when it exists — the exact local measure
    /// of what a pull would take and of what a push to the upstream still owes.
    upstream_ref: Option<String>,
    /// The remote a plain `git push` sends to — honours `branch.<name>.pushRemote` and
    /// `remote.pushDefault`.
    push: Option<String>,
}

/// The checked-out branch's push lane: the branch, git's own view of its remotes, and where
/// a push of it would go.
struct PushLane {
    branch: String,
    remotes: BranchRemotes,
    /// Distance from the upstream ref, when the branch has one.
    upstream_counts: Option<UpstreamCounts>,
    destination: GitPushDestination,
}

/// Resolve where the checked-out branch can be pushed; `None` when `HEAD` names no branch
/// (detached or unborn).
///
/// Which remote accepts pushes decides this, not what the branch tracks: a fetch-only
/// tracked remote is the update source, never a push destination. The remote git itself
/// would push to comes first, so the control names the one a plain `git push` reaches.
async fn resolve_push_lane(repo_path: &Path) -> anyhow::Result<Option<PushLane>> {
    let Some(branch) = checked_out_branch(repo_path).await else {
        return Ok(None);
    };
    let pushable: Vec<String> = remotes(repo_path)
        .await?
        .into_iter()
        .filter_map(|(name, accepts_pushes)| accepts_pushes.then_some(name))
        .collect();
    let own = branch_remotes(repo_path, &branch).await?;
    let upstream_counts = match &own.upstream_ref {
        Some(upstream) => Some(ahead_behind(repo_path, upstream).await?),
        None => None,
    };
    // A press fast-forwards the branch from its own update source before pushing, so the
    // count belongs to the tip it carries then: the upstream it can fast-forward to, or the
    // branch itself when the update cannot move it there (no upstream ref, level, diverged).
    let push_tip = match (&own.upstream_ref, upstream_counts) {
        (Some(upstream), Some(counts)) if counts.behind > 0 && counts.ahead == 0 => {
            upstream.as_str()
        }
        _ => "HEAD",
    };
    // Prefer the remote git itself would push to, then the tracked one, then the only
    // push-capable remote; a fetch-only remote is never chosen.
    let accepts = |name: Option<&str>| {
        name.filter(|name| pushable.iter().any(|remote| remote == name))
            .map(str::to_string)
    };
    let destination_remote = accepts(own.push.as_deref())
        .or_else(|| accepts(own.upstream.as_deref()))
        .or_else(|| match pushable.as_slice() {
            [only] => Some(only.clone()),
            _ => None,
        });
    let destination = match destination_remote.as_deref() {
        Some(remote) => {
            // The upstream ref the fetch keeps current is exact: a push to the branch's own
            // upstream needs no network round trip.
            let tracked_destination = own.upstream.as_deref() == Some(remote);
            let position = match upstream_counts {
                Some(counts) if tracked_destination => DestinationPosition {
                    publish: Some(false),
                    commits: counts.ahead,
                },
                _ => destination_position(repo_path, remote, &branch, push_tip).await?,
            };
            GitPushDestination::Target(GitPushTarget {
                remote: remote.to_string(),
                commits: position.commits,
                publish: position.publish,
            })
        }
        None => GitPushDestination::Nowhere {
            reason: match pushable.as_slice() {
                [] => "no remote accepts pushes".to_string(),
                several => format!("several remotes accept pushes ({})", several.join(", ")),
            },
        },
    };
    Ok(Some(PushLane {
        branch,
        remotes: own,
        upstream_counts,
        destination,
    }))
}

/// The branch `HEAD` names, if any — a detached or unborn `HEAD` prints `HEAD` or fails.
async fn checked_out_branch(repo_path: &Path) -> Option<String> {
    run_git_current_branch(repo_path)
        .await
        .ok()
        .filter(|branch| branch != "HEAD")
}

/// What the destination answered for a branch: what it would take, and whether it carries
/// it at all.
struct DestinationPosition {
    /// Whether the destination has no branch of this name; `None` when it could not be asked.
    publish: Option<bool>,
    /// Commits a press carries.
    commits: usize,
}

/// The destination is asked directly (`ls-remote`) rather than trusting the local
/// `refs/remotes/<remote>/<branch>`: a narrowed `remote.<remote>.fetch` refspec never creates that
/// ref and the refresh's fetch follows the branch's own upstream, so the ref is stale exactly where
/// the control matters. An unknown tip's copy of the branch is fetched into the remote-tracking
/// ref, so the count holds whatever refspecs are configured. A destination that cannot be reached,
/// or whose objects cannot be fetched, does not fail the state and claims no publish: the branch is
/// reported with the commits it carries, and a press reports git's own reason.
async fn destination_position(
    repo_path: &Path,
    remote: &str,
    branch: &str,
    push_tip: &str,
) -> anyhow::Result<DestinationPosition> {
    // The full ref, not the short name: `ls-remote` matches a short name against the tail of
    // other refs too (`main` finds `feature/main`).
    let wanted = format!("refs/heads/{branch}");
    let listing = match run_git_network(
        repo_path,
        &["ls-remote", "--branches", remote, &wanted],
        FETCH_TIMEOUT,
    )
    .await
    {
        Ok(output) => output.stdout,
        Err(e) => {
            tracing::debug!(error = %e, %remote, %branch, "git ls-remote failed");
            return unreported_position(repo_path).await;
        }
    };
    let tip = listing.lines().find_map(|line| {
        let (tip, refname) = line.split_once('\t')?;
        (refname.trim() == wanted).then(|| tip.trim().to_string())
    });
    let Some(tip) = tip else {
        // The destination has no such branch: the push publishes it, so the count is
        // everything the branch carries (nothing is pulled first).
        return Ok(DestinationPosition {
            publish: Some(true),
            commits: count_commits(repo_path, "HEAD").await?,
        });
    };
    if !rev_exists(repo_path, &tip).await? && !fetch_destination(repo_path, remote, branch).await {
        return unreported_position(repo_path).await;
    }
    Ok(DestinationPosition {
        publish: Some(false),
        commits: count_commits(repo_path, &format!("{tip}..{push_tip}")).await?,
    })
}

/// The position to report when the destination's copy of the branch is unknown — unreachable,
/// or its tip could not be fetched: every commit the branch carries, so a pushable branch is
/// never hidden behind a zero, and no publish claim for a destination never asked.
async fn unreported_position(repo_path: &Path) -> anyhow::Result<DestinationPosition> {
    Ok(DestinationPosition {
        publish: None,
        commits: count_commits(repo_path, "HEAD").await?,
    })
}

/// Fetch `remote`'s copy of `branch` into its remote-tracking ref. `false` when another fetch
/// is already running or this one failed — the caller then reports what the local refs say.
async fn fetch_destination(repo_path: &Path, remote: &str, branch: &str) -> bool {
    if FETCH_IN_FLIGHT.swap(true, Ordering::AcqRel) {
        tracing::debug!(%remote, %branch, "skipping the destination fetch: another fetch is running");
        return false;
    }
    let _guard = FetchInFlightGuard;
    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
    match run_git_network(
        // `--no-write-fetch-head` keeps this probe from clobbering a concurrent pull's merge
        // source; `--no-tags` keeps it from following tags.
        repo_path,
        &[
            "fetch",
            "--quiet",
            "--no-write-fetch-head",
            "--no-tags",
            remote,
            &refspec,
        ],
        FETCH_TIMEOUT,
    )
    .await
    {
        Ok(_) => true,
        Err(e) => {
            tracing::debug!(error = %e, %remote, %branch, "git fetch of the push destination failed");
            false
        }
    }
}

/// Remotes configured in `repo_path` and whether a push can reach each, in `git remote -v` order.
async fn remotes(repo_path: &Path) -> anyhow::Result<Vec<(String, bool)>> {
    let output = run_git_command(repo_path, &["remote", "-v"]).await?;
    let mut remotes: Vec<(String, bool)> = Vec::new();
    for line in output.lines() {
        let Some((name, target)) = line.split_once('\t') else {
            continue;
        };
        let Some(url) = target.strip_suffix(" (push)") else {
            continue;
        };
        let usable = push_destination_accepts_pushes(repo_path, url);
        match remotes.iter_mut().find(|(remote, _)| remote == name) {
            Some((_, all_usable)) => *all_usable &= usable,
            None => remotes.push((name.to_string(), usable)),
        }
    }
    Ok(remotes)
}

/// Whether a push URL can actually receive a push.
fn push_destination_accepts_pushes(repo_path: &Path, url: &str) -> bool {
    let url = url.trim();
    if url.is_empty() {
        return false;
    }
    if url.contains([':', '/', '\\']) || url.starts_with(['.', '~']) {
        return true;
    }
    repo_path.join(url).exists()
}

/// The remotes git resolves for `branch`: the one it tracks for updates, that upstream's
/// remote-tracking ref when it exists, and the one a plain `git push` sends to.
async fn branch_remotes(repo_path: &Path, branch: &str) -> anyhow::Result<BranchRemotes> {
    let listing = run_git_command(
        repo_path,
        &[
            "for-each-ref",
            "--format=%(upstream)%09%(upstream:remotename)%09%(push:remotename)",
            &format!("refs/heads/{branch}"),
        ],
    )
    .await?;
    let mut fields = listing.trim_end().split('\t');
    let upstream_ref = fields.next().unwrap_or_default();
    let upstream = fields.next().unwrap_or_default();
    let push = fields.next().unwrap_or_default();
    // `%(upstream)` names what the config points at, not proof the ref exists: a pruned or
    // never-fetched tracking ref leaves the name behind while `@{upstream}` stays unresolvable.
    let upstream_ref = if !upstream_ref.is_empty() && rev_exists(repo_path, upstream_ref).await? {
        Some(upstream_ref.to_string())
    } else {
        None
    };
    Ok(BranchRemotes {
        upstream: Some(upstream)
            .filter(|name| !name.is_empty())
            .map(str::to_string),
        upstream_ref,
        push: Some(push)
            .filter(|name| !name.is_empty())
            .map(str::to_string),
    })
}

/// Number of commits `rev` reaches.
async fn count_commits(repo_path: &Path, rev: &str) -> anyhow::Result<usize> {
    let count = run_git_trimmed(repo_path, &["rev-list", "--count", rev]).await?;
    count
        .parse()
        .with_context(|| format!("git rev-list --count {rev} printed {count:?}"))
}

/// Whether `rev` resolves to a commit in this repository.
async fn rev_exists(repo_path: &Path, rev: &str) -> anyhow::Result<bool> {
    Ok(run_git_output(
        repo_path,
        &[
            "rev-parse",
            "--verify",
            "--quiet",
            &format!("{rev}^{{commit}}"),
        ],
    )
    .await?
    .status
    .success())
}

/// Hard timeout for a single network round trip — a `git fetch`, a push, or the destination
/// probe. An unreachable/slow remote must not hang the remote sync indefinitely.
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);

/// Single-flight guard for network fetches ([`run_git_fetch`] and the destination probe): at
/// most one runs at a time so concurrent fetches cannot contend on the same ref locks.
static FETCH_IN_FLIGHT: AtomicBool = AtomicBool::new(false);

/// RAII guard that clears [`FETCH_IN_FLIGHT`] when the fetch task finishes (including on
/// error, timeout or cancellation).
struct FetchInFlightGuard;
impl Drop for FetchInFlightGuard {
    fn drop(&mut self) {
        FETCH_IN_FLIGHT.store(false, Ordering::Release);
    }
}

/// Run `git fetch` so remote refs are refreshed before the branch's remote state is computed
/// (a fetch-free comparison only sees the last-fetched state).
pub async fn run_git_fetch(repo_path: &Path) -> anyhow::Result<String> {
    // Single-flight: skip rather than queue, since a queued fetch would only contend on the
    // same ref locks.
    if FETCH_IN_FLIGHT.swap(true, Ordering::AcqRel) {
        return Ok(String::new());
    }
    let _guard = FetchInFlightGuard;
    run_git_network(repo_path, &["fetch", "--quiet"], FETCH_TIMEOUT)
        .await
        .map(GitNetworkOutput::report)
}

/// What a [`run_git_network`] step printed, both streams trimmed.
struct GitNetworkOutput {
    /// git's progress and report lines — a push reports its ref updates and "Everything
    /// up-to-date" here.
    stderr: String,
    /// The command's own answer, e.g. `ls-remote`'s ref list.
    stdout: String,
}

impl GitNetworkOutput {
    /// The human report, stderr first: a push prints its ref report before its trailing
    /// upstream notice on stdout, so reading stdout alone would show a real push as nothing
    /// to do.
    fn report(self) -> String {
        [self.stderr, self.stdout]
            .into_iter()
            .filter(|stream| !stream.is_empty())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// Run a network git command (fetch/pull/push/ls-remote) with a hard timeout.
///
/// The environment is the product's internal one (see [`git_command`]) plus
/// `GIT_TERMINAL_PROMPT=0`, so git/credential helpers never pop an interactive (osxkeychain) prompt
/// for a credential-less remote, and `SSH_AUTH_SOCK` restored so SSH-agent remotes work. On timeout
/// the `git` child is killed and reaped, and a remote helper it spawned (`git-remote-https`)
/// terminates when its pipe closes, so nothing holds the command open. A non-zero exit reports
/// git's own stderr, so a refused push carries git's reason; the streams stay apart — a command's
/// answer is parsed from stdout while [`GitNetworkOutput::report`] joins both.
async fn run_git_network(
    repo_path: &Path,
    args: &[&str],
    timeout: Duration,
) -> anyhow::Result<GitNetworkOutput> {
    let mut cmd = git_command(Some(repo_path));
    cmd.args(args).current_dir(repo_path);
    cmd.env("GIT_TERMINAL_PROMPT", "0");
    // Restore the SSH agent socket for SSH remotes (dropped by the internal environment).
    if let Some(sock) = std::env::var_os("SSH_AUTH_SOCK") {
        cmd.env("SSH_AUTH_SOCK", sock);
    }
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Kill the child if this task is cancelled (e.g. on shutdown) so a running network
    // operation cannot outlive the runtime and orphan.
    cmd.kill_on_drop(true);

    let mut child = cmd
        .spawn()
        .with_context(|| format!("Failed to spawn git {}", args.join(" ")))?;
    let mut stdout = child.stdout.take();
    let mut stderr = child.stderr.take();
    let mut stdout_buf = Vec::new();
    let mut stderr_buf = Vec::new();

    // Drain the pipes while waiting for the child, all inside the timeout — a slow or
    // unreachable remote (or a subprocess holding the pipes) cannot hang the caller. On
    // timeout, kill and reap so no zombie lingers.
    let wait = child.wait();
    let read_stdout = async {
        if let Some(out) = &mut stdout {
            let _ = out.read_to_end(&mut stdout_buf).await;
        }
    };
    let read_stderr = async {
        if let Some(err) = &mut stderr {
            let _ = err.read_to_end(&mut stderr_buf).await;
        }
    };

    let status = if let Ok(res) = tokio::time::timeout(timeout, async {
        tokio::join!(wait, read_stdout, read_stderr).0
    })
    .await
    {
        res.with_context(|| format!("git {} wait failed", args.join(" ")))?
    } else {
        let _ = child.kill().await;
        let _ = child.wait().await;
        anyhow::bail!(
            "git {} timed out after {}s",
            args.join(" "),
            timeout.as_secs()
        );
    };

    if !status.success() {
        anyhow::bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&stderr_buf)
        );
    }

    Ok(GitNetworkOutput {
        stderr: String::from_utf8_lossy(&stderr_buf).trim().to_string(),
        stdout: String::from_utf8_lossy(&stdout_buf).trim().to_string(),
    })
}

/// Aggregate working-tree diff statistics for the GUI footer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiffStats {
    /// Total lines added (tracked diff + line-counted untracked text files).
    pub added: i64,
    /// Total lines removed (tracked diff only).
    pub removed: i64,
    /// Oversized/binary untracked files, surfaced as a separate "N files" indicator.
    pub huge_binary_file_count: usize,
    /// Untracked files the bounded worktree read left out; both surfaces render
    /// [`Self::omitted_note`] for this.
    pub omitted_file_count: usize,
}

impl DiffStats {
    /// The one description of what the bounded untracked read left out; the footer and the
    /// diff window both render this exact note.
    pub(crate) fn omitted_note(&self) -> Option<String> {
        (self.omitted_file_count > 0).then(|| {
            format!(
                "{} uncommitted file{} left out (worktree read cap)",
                self.omitted_file_count,
                if self.omitted_file_count == 1 {
                    ""
                } else {
                    "s"
                }
            )
        })
    }
}

/// How an untracked file was classified for display / line counting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UntrackedKind {
    Text,
    Binary,
    TooLarge(u64),
}

/// One file in the settled uncommitted change set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeChange {
    /// Relative to the repository root (git reports root-relative paths even from a
    /// subdirectory workspace).
    pub path: String,
    /// Rename/copy source, when git detected one.
    pub old_path: Option<String>,
    /// Lines added; 0 when the content has no lines (binary, oversized).
    pub added: i64,
    /// Lines removed; 0 likewise.
    pub removed: i64,
    /// `Some` exactly when the file is untracked.
    pub untracked: Option<UntrackedKind>,
}

/// Git file status for coloring the file tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitFileStatus {
    /// Modified (`M`).
    Modified,
    /// Untracked (`??`) or newly added (`A`).
    Added,
}

/// Run `git diff --numstat -z --find-renames <base>` and parse it into the tracked part of
/// the change manifest. `-z` keeps paths NUL-delimited and unquoted, so the returned paths are
/// the raw repo-root-relative names.
async fn run_git_worktree_numstat(
    repo_path: &Path,
    base: &str,
) -> anyhow::Result<Vec<WorktreeChange>> {
    let stdout = run_git_command(
        repo_path,
        &["diff", "--numstat", "-z", "--find-renames", base],
    )
    .await?;
    Ok(parse_numstat_z(&stdout))
}

/// Parse `git diff --numstat -z` output.
fn parse_numstat_z(stdout: &str) -> Vec<WorktreeChange> {
    let mut fields = stdout.split('\0');
    let mut result = Vec::new();
    while let Some(field) = fields.next() {
        if field.is_empty() {
            continue;
        }
        let mut parts = field.splitn(3, '\t');
        let added = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0);
        let removed = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0);
        let Some(path) = parts.next() else {
            continue;
        };
        let (path, old_path) = if path.is_empty() {
            let (Some(old), Some(new)) = (fields.next(), fields.next()) else {
                break;
            };
            (new.to_string(), Some(old.to_string()))
        } else {
            (path.to_string(), None)
        };
        result.push(WorktreeChange {
            path,
            old_path,
            added,
            removed,
            untracked: None,
        });
    }
    result
}

/// Working-tree snapshot: aggregate diff stats, per-file porcelain statuses, and the settled
/// change set, from one `git status --porcelain --untracked-files=all` reading plus one
/// numstat pass.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitWorktreeSnapshot {
    /// Aggregate line stats, summed from [`Self::changes`].
    pub stats: DiffStats,
    /// Per-file porcelain status, keyed by the repo-root-relative path as git reports it.
    pub file_statuses: HashMap<String, GitFileStatus>,
    /// The repo has no commits (unborn HEAD): tracked changes are measured against the empty
    /// tree, but `unborn_head` still tells churn consumers there is no valid baseline — ones
    /// that must keep their old error semantics (reviewer churn) check this rather than
    /// treating the snapshot as a valid diff baseline.
    pub unborn_head: bool,
    /// Every uncommitted file: tracked entries in numstat order, then untracked files in
    /// status order.
    pub changes: Vec<WorktreeChange>,
    /// Repository top level; untracked status paths resolve against this.
    pub repo_root: PathBuf,
}

/// A manifest entry for an untracked file: `added` is its line count (0 for content with no
/// lines), and such a file never removes lines.
fn untracked_change(path: &str, kind: UntrackedKind, added: i64) -> WorktreeChange {
    WorktreeChange {
        path: path.to_owned(),
        old_path: None,
        added,
        removed: 0,
        untracked: Some(kind),
    }
}

/// Classify each `??` status path into a [`WorktreeChange`], returning the changes and how
/// many files the per-refresh caps left out.
///
/// `repo_root` resolves the root-relative status paths. Only regular files are classified;
/// collapsed nested repositories (`dir/`) are already excluded by
/// [`parse_untracked_from_porcelain`], so they never inflate the omitted tally. The metadata
/// read gates the byte budget *before* the content read, and the read and its binary/text
/// verdict are shared with the diff window through [`read_untracked_file_with_meta`], so the
/// two cannot drift on what a file is.
async fn classify_untracked_changes(
    repo_root: &Path,
    untracked: &[String],
) -> (Vec<WorktreeChange>, usize) {
    let mut changes = Vec::new();
    let mut files_processed = 0usize;
    let mut bytes_read = 0u64;
    let mut omitted = 0usize;
    for path in untracked {
        if files_processed >= MAX_UNTRACKED_FILES_COUNTED || bytes_read >= MAX_UNTRACKED_BYTES_READ
        {
            omitted += 1;
            continue;
        }
        let full_path = repo_root.join(path);
        let Ok(meta) = tokio::fs::metadata(&full_path).await else {
            continue;
        };
        if !meta.is_file() {
            continue;
        }
        files_processed += 1;
        if meta.len() > MAX_UNTRACKED_SIZE {
            changes.push(untracked_change(
                path,
                UntrackedKind::TooLarge(meta.len()),
                0,
            ));
            continue;
        }
        if bytes_read + meta.len() > MAX_UNTRACKED_BYTES_READ {
            omitted += 1;
            continue;
        }
        match read_untracked_file_with_meta(&full_path, &meta).await {
            UntrackedFileRead::Text(text) => {
                bytes_read += meta.len();
                #[expect(clippy::cast_possible_wrap)] // line count fits i64
                let added = text.lines().count() as i64;
                changes.push(untracked_change(path, UntrackedKind::Text, added));
            }
            UntrackedFileRead::Binary => {
                bytes_read += meta.len();
                changes.push(untracked_change(path, UntrackedKind::Binary, 0));
            }
            // A file that grew between the metadata read and the content read.
            UntrackedFileRead::TooLarge(size) => {
                changes.push(untracked_change(path, UntrackedKind::TooLarge(size), 0));
            }
            UntrackedFileRead::Skip => {}
        }
    }
    (changes, omitted)
}

/// A `git status --porcelain --untracked-files=all` failure is fatal: broken or missing git never
/// yields a snapshot, so callers keep their last-known-good state (or default churn).
pub async fn run_git_worktree_snapshot(repo_path: &Path) -> anyhow::Result<GitWorktreeSnapshot> {
    let repo_root =
        resolve_git_top_level(repo_path).context("Failed to resolve the repository top-level")?;
    let porcelain = run_git_status_all(&repo_root).await?;
    let file_statuses = parse_git_status_porcelain(&porcelain);
    let untracked = parse_untracked_from_porcelain(&porcelain);

    let (tracked, unborn_head) = match run_git_worktree_numstat(&repo_root, "HEAD").await {
        Ok(entries) => (entries, false),
        // `git_has_commits` separates an unborn HEAD (a fresh `git init` with no commits) from
        // other numstat failures — an unborn repo still yields the full change set, measured
        // against the empty tree.
        Err(_) if !git_has_commits(&repo_root).await => {
            let base = run_git_empty_tree(&repo_root).await?;
            (
                run_git_worktree_numstat(&repo_root, &base)
                    .await
                    .context("Failed to compute working-tree diff stats")?,
                true,
            )
        }
        Err(e) => return Err(e.context("Failed to compute working-tree diff stats")),
    };

    let mut changes = tracked;
    let (untracked_changes, omitted) = classify_untracked_changes(&repo_root, &untracked).await;
    changes.extend(untracked_changes);

    let mut stats = DiffStats {
        added: 0,
        removed: 0,
        huge_binary_file_count: 0,
        omitted_file_count: omitted,
    };
    for change in &changes {
        stats.added += change.added;
        stats.removed += change.removed;
        if matches!(
            change.untracked,
            Some(UntrackedKind::Binary | UntrackedKind::TooLarge(_))
        ) {
            stats.huge_binary_file_count += 1;
        }
    }

    Ok(GitWorktreeSnapshot {
        stats,
        file_statuses,
        unborn_head,
        changes,
        repo_root,
    })
}

/// Hard timeout for a `git pull`/`git push` from the sync control.
const SYNC_TIMEOUT: Duration = Duration::from_secs(300);

/// What a sync did, and — when nothing could take a push — why not.
#[derive(Debug, Clone)]
pub struct GitSyncReport {
    /// git's own report from the steps that ran (empty when none did).
    pub output: String,
    /// Why nothing was pushed, when no remote could take the branch.
    pub not_pushed: Option<String>,
}

/// Sync the checked-out branch: update it from its own update source, then push it wherever a
/// push can actually go.
pub async fn run_git_sync(repo_path: &Path) -> anyhow::Result<GitSyncReport> {
    let lane = resolve_push_lane(repo_path)
        .await?
        .context("no branch is checked out")?;
    let publish = matches!(&lane.destination, GitPushDestination::Target(target) if target.publish == Some(true));
    let update = if lane.remotes.upstream_ref.is_some() && !publish {
        Some(
            run_git_network(repo_path, &["pull", "--ff-only"], SYNC_TIMEOUT)
                .await?
                .report(),
        )
    } else {
        None
    };
    let (not_pushed, push) = match &lane.destination {
        GitPushDestination::Nowhere { reason } => (Some(reason.clone()), None),
        GitPushDestination::Target(target) => {
            // A plain `git push` reaches the branch's own push destination — the one the
            // control names whenever it accepts pushes — so it keeps honouring the configured
            // push remote, push refspecs and `push.default`. Everywhere else the destination
            // is named explicitly, and a branch that tracks nothing records its upstream on
            // the remote that received the push.
            let record_upstream = lane.remotes.upstream.is_none();
            let plain =
                !record_upstream && lane.remotes.push.as_deref() == Some(target.remote.as_str());
            let report = if plain {
                run_git_network(repo_path, &["push"], SYNC_TIMEOUT)
                    .await?
                    .report()
            } else {
                let mut args = vec!["push"];
                if record_upstream {
                    args.push("--set-upstream");
                }
                args.push(target.remote.as_str());
                args.push(lane.branch.as_str());
                run_git_network(repo_path, &args, SYNC_TIMEOUT)
                    .await?
                    .report()
            };
            (None, Some(report))
        }
    };
    Ok(GitSyncReport {
        output: update
            .into_iter()
            .chain(push)
            .filter(|part| !part.is_empty())
            .collect::<Vec<_>>()
            .join("\n"),
        not_pushed,
    })
}

/// Discard all changes to a path — `checkout HEAD --`, `reset HEAD --`, then `clean -f[d] --` —
/// covering Modified, Deleted, Renamed, Added and untracked files in one sequence. Errors from
/// all three steps are absorbed (an untracked path fails checkout with "did not match", a
/// restored one makes reset a no-op); success is judged afterwards by
/// `git status --porcelain --untracked-files=normal -- <path>`, empty meaning the discard
/// worked and any remaining output reported as the failure it is. That untracked mode is
/// pinned for the same reason [`run_git_status`] pins it — the owner's
/// `status.showUntrackedFiles` must not decide this answer — so a leftover `git clean`
/// deliberately keeps (a nested repository needs `-ff`) cannot pass as a silent success.
///
/// `path` is repo-root-relative, as the diff window lists it. Every pathspec uses
/// `:(top,literal)`: `top` resolves it against the repository root whatever the caller's
/// working directory — a subdirectory workspace would otherwise rewrite or delete a same-named
/// path beneath itself — and `literal` keeps glob characters in file names from matching other
/// files. `git reset HEAD` also exits non-zero for a path outside the repository, so callers
/// validate paths first.
pub async fn run_git_discard(
    repo_path: &Path,
    path: &str,
    target: DiscardTarget,
) -> anyhow::Result<()> {
    let path = format!(":(top,literal){path}");
    let _ = run_git_command(repo_path, &["checkout", "HEAD", "--", &path]).await;

    let _ = run_git_command(repo_path, &["reset", "HEAD", "--", &path]).await;

    let clean_args: &[&str] = match target {
        DiscardTarget::Directory => &["clean", "-fd", "--", &path],
        DiscardTarget::File => &["clean", "-f", "--", &path],
    };
    let _ = run_git_command(repo_path, clean_args).await;

    // Verify: check if any changes remain.
    let status_args = [
        "status",
        "--porcelain",
        "--untracked-files=normal",
        "--",
        &path,
    ];
    match run_git_command(repo_path, &status_args).await {
        Ok(status) if status.trim().is_empty() => Ok(()),
        Ok(status) => anyhow::bail!("Changes remain after discard:\n{}", status.trim()),
        Err(e) => anyhow::bail!("Discard ran but verification failed: {e}"),
    }
}

/// Get the last commit's subject via `git log -1 --format=%s`, for `commit_hash` if given.
pub async fn run_git_commit_message(
    repo_path: &Path,
    commit_hash: Option<&str>,
) -> anyhow::Result<String> {
    let mut args = vec!["log", "-1", "--format=%s"];
    if let Some(hash) = commit_hash {
        args.push(hash);
    }
    run_git_trimmed(repo_path, &args).await
}

/// List new or untracked files in the working tree: untracked (`??`) and staged-as-new (`A`)
/// entries, the ones a sanitation pass has to inspect.
pub(crate) async fn list_new_or_untracked_files(repo_path: &Path) -> anyhow::Result<Vec<String>> {
    let porcelain = run_git_status(repo_path).await?;
    Ok(parse_new_files_from_porcelain(&porcelain))
}

/// One parsed `git status --porcelain` record: both status columns and the path.
///
/// `<XY><space><path>`, `X` the index status and `Y` the worktree. Git C-quotes a path that
/// needs it, quoting each side of a rename or copy pair independently, so the path comes back
/// unquoted; a rename or copy yields its **destination** — the name that exists in the working
/// tree — for either column, never the `old -> new` text. A record too short to hold a path, or
/// one whose escapes do not decode, yields `None` and is skipped rather than reported as its
/// raw text; a field not wrapped in quotes on both ends (git always wraps a quoted path) is
/// taken literally.
///
/// The status map parses its own records because it classifies rather than lists, sharing only
/// [`split_rename_paths`]. The views differ deliberately: a trailing-slash entry is a directory
/// — kept by the `-unormal` reading of [`parse_new_files_from_porcelain`], dropped by the
/// `-uall` snapshot, and stripped to key a tree row by the map; a deleted entry (`D`) is stored
/// by no view and registers only in the byte-level [`has_unstaged_changes`]; and ` A`
/// (intent-to-add) is `Added` in the map but excluded by both listings, which select on the
/// index column.
struct PorcelainRecord {
    /// Index (staged) status column.
    index: char,
    /// Worktree (unstaged) status column.
    worktree: char,
    /// Path relative to the repository root, unquoted.
    path: String,
}

/// Parse one `git status --porcelain` record — see [`PorcelainRecord`]. The two status columns
/// must be followed by their separator space; anything else is not a record.
fn parse_porcelain_record(line: &str) -> Option<PorcelainRecord> {
    let mut chars = line.chars();
    let index = chars.next()?;
    let worktree = chars.next()?;
    if chars.next()? != ' ' {
        return None;
    }
    let field = chars.as_str();
    if field.is_empty() {
        return None;
    }
    let path = if index == 'R' || index == 'C' || worktree == 'R' || worktree == 'C' {
        split_rename_paths(field)?
    } else {
        unquote_c_style(field)?
    };
    Some(PorcelainRecord {
        index,
        worktree,
        path,
    })
}

/// The paths of the records `select` accepts, in git's order.
fn parse_porcelain_paths(
    porcelain: &str,
    mut select: impl FnMut(&PorcelainRecord) -> bool,
) -> Vec<String> {
    porcelain
        .lines()
        .filter_map(parse_porcelain_record)
        .filter(|record| select(record))
        .map(|record| record.path)
        .collect()
}

/// The destination path of a rename or copy record, from its `<old> -> <new>` field.
///
/// The delimiter is the first ` -> ` outside a quoted span: git quotes each side
/// independently, so neither "the field starts quoted" nor "the last ` -> ` wins" identifies
/// it — a quoted source with a plain destination, a plain source with a quoted destination,
/// and a quoted destination containing the delimiter all split here. The source is only
/// scanned, never returned: the recorded path is the one in the working tree. `None` when
/// there is no delimiter or the destination is not a path, and the caller skips the record.
fn split_rename_paths(field: &str) -> Option<String> {
    let mut quoted = false;
    let mut escaped = false;
    for (at, c) in field.char_indices() {
        if escaped {
            escaped = false;
        } else if quoted && c == '\\' {
            escaped = true;
        } else if c == '"' {
            quoted = !quoted;
        } else if !quoted && let Some(destination) = field[at..].strip_prefix(" -> ") {
            return unquote_c_style(destination).filter(|path| !path.is_empty());
        }
    }
    None
}

/// New/added file paths from a `git status --porcelain` reading: `??` and index-column `A`
/// records (`A `, `AM`, `AD`). Excludes ` A`, the intent-to-add state of `git add -N`, which
/// carries a space in the index column — nothing is staged. For only truly untracked files use
/// [`parse_untracked_from_porcelain`].
#[must_use]
fn parse_new_files_from_porcelain(porcelain: &str) -> Vec<String> {
    parse_porcelain_paths(porcelain, |record| {
        record.index == 'A' || (record.index == '?' && record.worktree == '?')
    })
}

/// Untracked file paths from the snapshot's `--untracked-files=all` reading: `??` records only,
/// so staged-as-new files the tracked half already covers are not listed twice. A
/// trailing-slash entry is a collapsed nested repository rather than a file and is dropped —
/// see [`PorcelainRecord`].
#[must_use]
fn parse_untracked_from_porcelain(porcelain: &str) -> Vec<String> {
    parse_porcelain_paths(porcelain, |record| {
        record.index == '?' && record.worktree == '?'
    })
    .into_iter()
    .filter(|path| !path.ends_with('/'))
    .collect()
}

/// Parse `git status --porcelain` output into a map of file path → `GitFileStatus`.
///
/// If either column is `M` the file is [`GitFileStatus::Modified`]; otherwise staged-new (`A`)
/// and untracked (`??`) map to [`GitFileStatus::Added`], so the unmerged `AA`, `AU` and `UA`
/// store `Added` through their `A` column. Modified wins over added. A rename in either column
/// keys its destination as `Modified` (see [`split_rename_paths`]); a copy is skipped, as is a
/// rename field that does not split. A deleted entry (`D` in either column — `D `, ` D`, `AD`,
/// `DU`, `DD`) is skipped, the deletion taking precedence over an `A` column. Everything else
/// (`UU`, typechange) stores nothing, and a path that does not unquote is skipped.
///
/// Keys are repo-root-relative as git emits them, with a trailing slash stripped so they match
/// a tree row — the same key space as the editor's file tree when the workspace is the root.
/// The differences from the path listings are stated on [`PorcelainRecord`].
#[must_use]
pub(crate) fn parse_git_status_porcelain(output: &str) -> HashMap<String, GitFileStatus> {
    let mut map: HashMap<String, GitFileStatus> = HashMap::new();

    for line in output.lines() {
        let trimmed = line.trim_end();
        if trimmed.len() < 2 {
            continue;
        }

        let chars: Vec<char> = trimmed.chars().take(2).collect();
        if chars.len() < 2 {
            continue;
        }

        let ix = chars[0];
        let wt = chars[1];

        // Skip deleted files — they don't appear in the working tree.
        if ix == 'D' || wt == 'D' {
            continue;
        }

        // "R  old_path -> new_path". Git quotes each side separately, so the split cannot
        // assume a shared quoting style. The worktree column is handled the same way as a
        // robustness rule: ` R` ("renamed in work tree") is documented but not observed, and
        // dropping the row would be worse than keying its destination.
        if ix == 'R' || wt == 'R' {
            let Some(new_path) = split_rename_paths(trimmed[2..].trim_start()) else {
                continue;
            };
            map.insert(new_path, GitFileStatus::Modified);
            continue;
        }

        // Copies are skipped: the classification below knows only M and A.
        if ix == 'C' || wt == 'C' {
            continue;
        }

        // Extract path: strip first 2 chars (status columns) and leading space.
        let path = trimmed[2..].trim_start();
        if path.is_empty() {
            continue;
        }

        let status = if ix == 'M' || wt == 'M' {
            GitFileStatus::Modified
        } else if ix == 'A' || wt == 'A' || (ix == '?' && wt == '?') {
            GitFileStatus::Added
        } else {
            // Clean or ignored — don't store.
            continue;
        };

        let Some(path) = unquote_c_style(path) else {
            continue;
        };
        // Git appends '/' for untracked directories (`?? new_dir/`); a tree full_path has none.
        let path = path.strip_suffix('/').unwrap_or(&path).to_string();

        // Staged + unstaged lines for one file keep the most interesting status:
        // Modified > Added.
        let entry = map.entry(path).or_insert(status);
        if status == GitFileStatus::Modified && *entry == GitFileStatus::Added {
            *entry = GitFileStatus::Modified;
        }
    }

    map
}

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

    /// The worktree identity is a pure reading (the repository's own index and status are left
    /// as found) that agrees with a real `git add -A` — what the reviewed-base skip check
    /// compares an index tree against.
    #[tokio::test]
    async fn worktree_identity_is_read_only_and_matches_a_real_add() {
        let (_dir, repo_path) = init_temp_repo();
        std::fs::write(repo_path.join("tracked.txt"), b"changed\n").unwrap();
        std::fs::write(repo_path.join("untracked.txt"), b"new\n").unwrap();

        let status_before = run_git_status(&repo_path).await.unwrap();
        let index_before = run_git_write_tree(&repo_path).await.unwrap();
        let (head, tree) = run_git_worktree_identity(&repo_path).await.unwrap();

        assert_eq!(
            status_before,
            run_git_status(&repo_path).await.unwrap(),
            "the reading must not change the working-tree status",
        );
        assert_eq!(
            index_before,
            run_git_write_tree(&repo_path).await.unwrap(),
            "the reading must not touch the repository's own index",
        );

        run_git_add_all(&repo_path).await.unwrap();
        assert_eq!(
            tree,
            run_git_write_tree(&repo_path).await.unwrap(),
            "the identity must be what a real add -A stages",
        );
        assert_eq!(head, run_git_head(&repo_path).await.unwrap());
    }

    /// Both cases the seed exists for: a split index (whose shared file git resolves through
    /// the repository, not next to the copy) and a tracked file matched by `.gitignore`, which
    /// an unseeded throwaway index drops.
    #[tokio::test]
    async fn worktree_identity_seeds_a_split_index_and_ignored_tracked_paths() {
        let (_dir, repo_path) = init_temp_repo();
        let status = std::process::Command::new("git")
            .args(["update-index", "--split-index"])
            .current_dir(&repo_path)
            .status()
            .expect("git update-index");
        assert!(status.success());
        std::fs::write(repo_path.join(".gitignore"), b"test.txt\n").unwrap();
        std::fs::write(repo_path.join("test.txt"), b"v2\n").unwrap();
        std::fs::write(repo_path.join("untracked.txt"), b"new\n").unwrap();

        let (_, tree) = run_git_worktree_identity(&repo_path).await.unwrap();
        run_git_add_all(&repo_path).await.unwrap();
        assert_eq!(
            tree,
            run_git_write_tree(&repo_path).await.unwrap(),
            "the identity must be what a real add -A stages",
        );
    }

    /// One rule at every entry point: the walk resolves the `.git`-containing ancestor whether
    /// asked from the repository root, from a subdirectory below it, or from a directory whose
    /// `.git` is a *file* (linked worktree / submodule marker — the walk uses `exists()`, not
    /// `is_dir()`) — and reports no repository outside one.
    #[test]
    fn resolve_git_top_level_cases() {
        let (_dir, repo_path) = init_temp_repo();
        let subdir = repo_path.join("src");
        std::fs::create_dir(&subdir).expect("create subdir");
        let worktree = tempfile::tempdir().expect("create temp dir");
        std::fs::write(worktree.path().join(".git"), b"gitdir: /elsewhere")
            .expect("write .git file");
        let outside = tempfile::tempdir().expect("create temp dir");

        let root = Some(crate::util::test::canonical_without_verbatim_prefix(
            &repo_path,
        ));
        let as_worktree = Some(crate::util::test::canonical_without_verbatim_prefix(
            worktree.path(),
        ));
        let cases: &[(&str, &Path, Option<&PathBuf>)] = &[
            ("repository root", &repo_path, root.as_ref()),
            ("subdirectory below it", &subdir, root.as_ref()),
            (".git file marker", worktree.path(), as_worktree.as_ref()),
            ("outside any repository", outside.path(), None),
        ];
        for (name, path, expected) in cases {
            assert_eq!(
                resolve_git_top_level(path).as_ref(),
                *expected,
                "case {name}: {}",
                path.display()
            );
        }
    }

    /// Build a git command with a hermetic config environment: `safe.directory` must come only
    /// from the injected `GIT_CONFIG_*` env, never from the developer's global/system gitconfig
    /// (which may already list the repo or use `*`). `GIT_TEST_ASSUME_DIFFERENT_OWNER=1`
    /// simulates a repo owned by a different UID without needing `chown`/root.
    fn hermetic_git_command(repo_root: Option<&Path>) -> tokio::process::Command {
        let mut cmd = git_command(repo_root);
        cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
        cmd.env("GIT_CONFIG_NOSYSTEM", "1");
        cmd.env("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1");
        cmd
    }

    /// Simulates a repo owned by a different UID via git's `GIT_TEST_ASSUME_DIFFERENT_OWNER`
    /// hook: the injected top-level `safe.directory` must make git operable.
    #[tokio::test]
    async fn test_safe_directory_injection_bypasses_dubious_ownership() {
        let (_dir, repo_path) = init_temp_repo();

        let mut cmd = hermetic_git_command(Some(&repo_path));
        cmd.arg("status").arg("--porcelain").current_dir(&repo_path);
        let out = cmd.output().await.expect("run git status");
        assert!(
            out.status.success(),
            "git status must succeed with safe.directory injected: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[tokio::test]
    async fn test_without_safe_directory_fails_dubious_ownership() {
        let (_dir, repo_path) = init_temp_repo();

        let mut cmd = hermetic_git_command(None);
        cmd.arg("status").arg("--porcelain").current_dir(&repo_path);
        let out = cmd.output().await.expect("run git status");
        assert!(
            !out.status.success(),
            "git must refuse dubious ownership without safe.directory injection"
        );
    }

    /// The injected value must be the repo *top-level* even from a subdirectory workspace —
    /// git's own discovery normalizes to the top-level, so a subdir value would not match.
    #[tokio::test]
    async fn test_safe_directory_injects_top_level_for_subdir_workspace() {
        let (_dir, repo_path) = init_temp_repo();
        let subdir = repo_path.join("src");
        std::fs::create_dir(&subdir).expect("create subdir");

        let mut cmd = hermetic_git_command(Some(&subdir));
        cmd.arg("status").arg("--porcelain").current_dir(&subdir);
        let out = cmd.output().await.expect("run git status");
        assert!(
            out.status.success(),
            "git from a repo subdir must match the repo top-level safe.directory: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[tokio::test]
    async fn test_run_git_head_and_write_tree_fingerprint() {
        let (_dir, repo_path) = init_temp_repo();
        let head1 = run_git_head(&repo_path).await.expect("repo has commits");
        let tree1 = run_git_write_tree(&repo_path)
            .await
            .expect("index writable");

        // Staged content change → new index tree, unchanged HEAD.
        std::fs::write(repo_path.join("test.txt"), b"line1\nline2\n").expect("write file");
        run_git_add_all(&repo_path).await.expect("git add");
        let head2 = run_git_head(&repo_path).await.expect("repo has commits");
        let tree2 = run_git_write_tree(&repo_path)
            .await
            .expect("index writable");
        assert_eq!(head1, head2, "staging must not change HEAD");
        assert_ne!(tree1, tree2, "staging must change the index tree");
    }

    #[tokio::test]
    async fn test_run_git_head_none_without_commits() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let repo_path = dir.path().to_path_buf();

        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .status()
            .expect("git init");
        assert!(status.success());

        let head = run_git_head(&repo_path).await.ok();
        assert!(head.is_none(), "commit-less repo must not resolve HEAD");
    }

    /// `git_has_commits` and `run_git_commit_message` both resolve against the same HEAD: no
    /// commit → neither answers; one commit → both do; a named hash reads that commit's subject.
    #[tokio::test]
    async fn test_git_has_commits_and_commit_message_read_through_head() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let empty = dir.path().to_path_buf();
        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(&empty)
            .status()
            .expect("git init");
        assert!(status.success());
        assert!(!git_has_commits(&empty).await, "no commits yet");
        assert!(
            run_git_commit_message(&empty, None).await.is_err(),
            "a commit-less repo has no message to read"
        );

        let (_dir, repo_path) = init_temp_repo();
        assert!(
            git_has_commits(&repo_path).await,
            "the fixture commits once"
        );
        assert_eq!(
            run_git_commit_message(&repo_path, None)
                .await
                .expect("commit message without hash"),
            "Initial commit"
        );

        commit_file(&repo_path, "test.txt", "Second commit");
        let second = rev_parse(&repo_path, "HEAD");
        assert_eq!(
            run_git_commit_message(&repo_path, Some(&second))
                .await
                .expect("commit message with hash"),
            "Second commit",
            "a named hash reads that commit's subject"
        );
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_clean_tree() {
        let (_dir, repo_path) = init_temp_repo();
        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(snap.stats.added, 0);
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert_eq!(snap.stats.omitted_file_count, 0);
        assert!(snap.changes.is_empty(), "clean tree has no changes");
        assert!(snap.file_statuses.is_empty(), "clean tree has no statuses");
        assert_eq!(
            snap.repo_root,
            std::fs::canonicalize(&repo_path).unwrap(),
            "the snapshot resolves the repository root"
        );
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_with_changes() {
        let (_dir, repo_path) = init_temp_repo();
        // Modify: change "line2" to "line2 modified", add "line4"
        std::fs::write(
            repo_path.join("test.txt"),
            b"line1\nline2 modified\nline3\nline4\n",
        )
        .expect("write modified file");
        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(snap.stats.added, 2, "two lines added (modified + new line)");
        assert_eq!(snap.stats.removed, 1, "one line removed (line2)");
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert_eq!(
            snap.changes,
            vec![WorktreeChange {
                path: "test.txt".into(),
                old_path: None,
                added: 2,
                removed: 1,
                untracked: None,
            }]
        );
        assert_eq!(
            snap.file_statuses.get("test.txt"),
            Some(&GitFileStatus::Modified)
        );
    }

    /// A mode-only tracked change has no hunks and `0\t0` numstat; it is still one listed
    /// change, with no line counts.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_run_git_worktree_snapshot_lists_mode_only_change_without_counts() {
        use std::os::unix::fs::PermissionsExt;

        let (_dir, repo_path) = init_temp_repo();
        let path = repo_path.join("test.txt");
        let mut permissions = std::fs::metadata(&path)
            .expect("test file metadata")
            .permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&path, permissions).expect("make test file executable");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!((snap.stats.added, snap.stats.removed), (0, 0));
        assert_eq!(
            snap.changes,
            vec![WorktreeChange {
                path: "test.txt".into(),
                old_path: None,
                added: 0,
                removed: 0,
                untracked: None,
            }]
        );
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_counts_untracked_directory_files() {
        let (_dir, repo_path) = init_temp_repo();

        // Create an untracked directory with a normal file (3 lines) and a
        // binary file. `--untracked-files=all` lists both files individually.
        std::fs::create_dir_all(repo_path.join("new_dir")).expect("create directory");
        std::fs::write(
            repo_path.join("new_dir/a.rs"),
            b"fn foo() {\n    bar();\n}\n",
        )
        .expect("write normal file");
        std::fs::write(repo_path.join("new_dir/binary.bin"), b"line1\x00\n")
            .expect("write binary file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 3,
            "should count lines from directory files"
        );
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(
            snap.stats.huge_binary_file_count, 1,
            "binary file inside the directory surfaces as huge/binary"
        );
        assert_eq!(
            snap.changes,
            vec![
                WorktreeChange {
                    path: "new_dir/a.rs".into(),
                    old_path: None,
                    added: 3,
                    removed: 0,
                    untracked: Some(UntrackedKind::Text),
                },
                WorktreeChange {
                    path: "new_dir/binary.bin".into(),
                    old_path: None,
                    added: 0,
                    removed: 0,
                    untracked: Some(UntrackedKind::Binary),
                },
            ]
        );
        assert!(
            !snap.changes.iter().any(|c| c.path == "new_dir/"),
            "the directory itself is never a change"
        );
    }

    /// Both ways an untracked file becomes "huge": a NUL byte (binary) and a file over
    /// [`MAX_UNTRACKED_SIZE`]. Neither is line-counted, and both feed
    /// `huge_binary_file_count`, which the churn measurement reads.
    #[tokio::test]
    async fn test_run_git_worktree_snapshot_marks_binary_and_oversized_untracked_files_huge() {
        let (_dir, repo_path) = init_temp_repo();
        std::fs::write(repo_path.join("binary.bin"), b"line1\nline2\x00\n")
            .expect("write binary file");
        let size = usize::try_from(MAX_UNTRACKED_SIZE).expect("cap fits usize") + 1;
        std::fs::write(repo_path.join("large.bin"), vec![b'a'; size]).expect("write large file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(snap.stats.added, 0, "neither file is line-counted");
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(
            snap.stats.huge_binary_file_count, 2,
            "both are surfaced as huge/binary"
        );
        assert_eq!(
            snap.changes,
            vec![
                WorktreeChange {
                    path: "binary.bin".into(),
                    old_path: None,
                    added: 0,
                    removed: 0,
                    untracked: Some(UntrackedKind::Binary),
                },
                WorktreeChange {
                    path: "large.bin".into(),
                    old_path: None,
                    added: 0,
                    removed: 0,
                    untracked: Some(UntrackedKind::TooLarge(
                        u64::try_from(size).expect("size fits u64")
                    )),
                },
            ]
        );
    }

    /// A subdirectory workspace still reads the whole repository and reports repo-root-relative
    /// paths.
    #[tokio::test]
    async fn test_run_git_worktree_snapshot_resolves_root_relative_paths_from_subdir() {
        let (_dir, repo_path) = init_temp_repo();
        let sub = repo_path.join("sub");
        std::fs::create_dir(&sub).expect("create subdir");
        std::fs::write(sub.join("inside.txt"), b"one\ntwo\n").expect("write inside file");
        std::fs::write(repo_path.join("at-root.txt"), b"root\n").expect("write root file");

        let snap = run_git_worktree_snapshot(&sub)
            .await
            .expect("worktree snapshot");
        let paths: Vec<&str> = snap.changes.iter().map(|c| c.path.as_str()).collect();
        assert!(
            paths.contains(&"sub/inside.txt"),
            "a subdirectory workspace still reports repo-root-relative paths: {paths:?}"
        );
        assert!(
            paths.contains(&"at-root.txt"),
            "the reading is repo-wide: {paths:?}"
        );
        assert_eq!(snap.stats.added, 3, "both files are counted");
        assert_eq!(snap.repo_root, std::fs::canonicalize(&repo_path).unwrap());
    }

    #[expect(clippy::cast_possible_wrap)] // MAX_UNTRACKED_FILES_COUNTED is a small compile-time cap
    #[tokio::test]
    async fn test_run_git_worktree_snapshot_bounded_file_count_cap() {
        let (_dir, repo_path) = init_temp_repo();

        // An untracked directory with more files than the per-refresh cap — only the first
        // `MAX_UNTRACKED_FILES_COUNTED` are counted, the rest are reported as omitted.
        std::fs::create_dir_all(repo_path.join("big_dir")).expect("create directory");
        for i in 0..(MAX_UNTRACKED_FILES_COUNTED + 50) {
            std::fs::write(
                repo_path.join("big_dir").join(format!("f{i}")),
                format!("x{i}\n"),
            )
            .expect("write counted file");
        }

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, MAX_UNTRACKED_FILES_COUNTED as i64,
            "only the first cap files are line-counted"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert_eq!(
            snap.changes.len(),
            MAX_UNTRACKED_FILES_COUNTED,
            "the manifest only carries files inside the cap"
        );
        assert_eq!(
            snap.stats.omitted_file_count,
            MAX_UNTRACKED_FILES_COUNTED + 50 - MAX_UNTRACKED_FILES_COUNTED,
            "files beyond the cap are reported as omitted"
        );
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_gitignore_respected_in_directory() {
        let (_dir, repo_path) = init_temp_repo();

        // .gitignore is committed (tracked) so it is not itself counted.
        std::fs::write(repo_path.join(".gitignore"), b"ignored.log\n").expect("write gitignore");
        run_git_command(&repo_path, &["add", ".gitignore"])
            .await
            .expect("git add .gitignore");
        run_git_command(&repo_path, &["commit", "-m", "add .gitignore"])
            .await
            .expect("git commit .gitignore");

        // An untracked directory with a kept file and a gitignored file.
        std::fs::create_dir_all(repo_path.join("new_dir")).expect("create directory");
        std::fs::write(repo_path.join("new_dir/keep.rs"), b"aa\nbb\n").expect("write kept file");
        std::fs::write(repo_path.join("new_dir/ignored.log"), b"ignored\n")
            .expect("write ignored file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 2,
            "gitignored file inside a directory is not counted"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert_eq!(snap.changes.len(), 1, "only the kept file is a change");
        assert_eq!(snap.changes[0].path, "new_dir/keep.rs");
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_unborn_head() {
        // A freshly `git init`ed repo has no HEAD; numstat against the empty tree still
        // carries staged and untracked files.
        let dir = tempfile::tempdir().expect("create temp dir");
        let repo_path = dir.path().to_path_buf();
        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .status()
            .expect("git init");
        assert!(status.success());

        std::fs::write(repo_path.join("first.rs"), b"fn main() {}\n")
            .expect("write untracked file");
        std::fs::write(repo_path.join("staged.rs"), b"a\nb\n").expect("write staged file");
        run_git_command(&repo_path, &["add", "staged.rs"])
            .await
            .expect("git add staged file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 3,
            "staged and untracked lines both counted despite unborn HEAD"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert!(snap.unborn_head, "unborn HEAD must be flagged");
        assert_eq!(
            snap.file_statuses.get("first.rs"),
            Some(&GitFileStatus::Added),
            "untracked file status flows on an unborn repo"
        );
        let staged = snap
            .changes
            .iter()
            .find(|c| c.path == "staged.rs")
            .expect("staged file is in the change set");
        assert_eq!((staged.added, staged.removed), (2, 0));
        assert!(staged.untracked.is_none(), "a staged file is tracked");
        assert_eq!(
            snap.changes
                .iter()
                .find(|c| c.path == "first.rs")
                .and_then(|c| c.untracked),
            Some(UntrackedKind::Text)
        );
    }

    #[test]
    fn parse_numstat_z_handles_normal_binary_and_rename_records() {
        let stdout = "3\t1\tfile.txt\0-\t-\timage.bin\0\
                      2\t0\t\0old.txt\0new.txt\0";
        let entries = parse_numstat_z(stdout);
        assert_eq!(
            entries.len(),
            3,
            "trailing NUL and empty fields are ignored"
        );
        assert_eq!(entries[0].path, "file.txt");
        assert_eq!((entries[0].added, entries[0].removed), (3, 1));
        assert_eq!(entries[0].old_path, None);
        assert_eq!(entries[1].path, "image.bin");
        assert_eq!((entries[1].added, entries[1].removed), (0, 0));
        assert_eq!(entries[2].path, "new.txt");
        assert_eq!(entries[2].old_path.as_deref(), Some("old.txt"));
        assert_eq!((entries[2].added, entries[2].removed), (2, 0));
    }
    /// Create a bare repository under `root` and register it as remote `name` of `repo_path`;
    /// returns the bare repo's path.
    fn add_bare_remote(root: &Path, repo_path: &Path, name: &str) -> std::path::PathBuf {
        let bare = root.join(format!("{name}.git"));
        let status = std::process::Command::new("git")
            .args(["init", "--bare"])
            .arg(&bare)
            .status()
            .expect("git init --bare");
        assert!(status.success());
        let status = std::process::Command::new("git")
            .args(["remote", "add", name])
            .arg(&bare)
            .current_dir(repo_path)
            .status()
            .expect("git remote add");
        assert!(status.success());
        bare
    }

    /// Run a plain git command in `repo_path`, asserting it succeeded.
    fn git_ok(repo_path: &Path, args: &[&str]) -> std::process::Output {
        let output = std::process::Command::new("git")
            .args(args)
            .current_dir(repo_path)
            .output()
            .expect("run git");
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
        output
    }

    fn rev_parse(repo_path: &Path, rev: &str) -> String {
        String::from_utf8_lossy(&git_ok(repo_path, &["rev-parse", rev]).stdout)
            .trim()
            .to_string()
    }

    /// Write `name` and commit it, so the checked-out branch gains a commit.
    fn commit_file(repo_path: &Path, name: &str, message: &str) {
        std::fs::write(repo_path.join(name), b"new\n").expect("write");
        git_ok(repo_path, &["add", "-A"]);
        git_ok(repo_path, &["commit", "-m", message]);
    }

    /// The remote git resolves `branch`'s upstream to, if it tracks one.
    async fn tracked(repo_path: &Path, branch: &str) -> Option<String> {
        branch_remotes(repo_path, branch)
            .await
            .expect("branch remotes")
            .upstream
    }

    /// The remote state of the branch checked out in `repo_path`.
    async fn remote_state(repo_path: &Path) -> GitRemoteState {
        run_git_remote_state(repo_path)
            .await
            .expect("remote state")
            .expect("a branch is checked out")
    }

    /// An upstream-less branch on a repo with one pushable remote publishes to it: the push
    /// carries every commit, records the upstream, and the report is a real push (never
    /// reported as nothing to do).
    #[tokio::test]
    async fn publish_untracked_branch_to_single_pushable_remote() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        let carried = count_commits(&repo_path, "HEAD").await.expect("count");

        let state = remote_state(&repo_path).await;
        assert_eq!(state.behind, 0);
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.commits, carried, "publish carries every commit");
        assert_eq!(target.publish, Some(true), "origin has no such branch yet");
        assert!(state.has_sync_work());

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert!(
            !report.output.trim().is_empty(),
            "a real push must report something"
        );
        assert!(
            report.output.contains(&branch),
            "the report names the branch: {}",
            report.output
        );
        git_ok(
            &origin,
            &["rev-parse", "--verify", &format!("refs/heads/{branch}")],
        );
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("origin"),
            "the publish records the upstream"
        );
        assert!(
            !remote_state(&repo_path).await.has_sync_work(),
            "in sync again: nothing left to offer"
        );

        // Once the branch tracks its new remote, a later commit is an ordinary
        // update-and-push to the same destination.
        commit_file(&repo_path, "after.txt", "after the publish");
        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.publish, Some(false));
        assert_eq!(target.commits, 1);
        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD")
        );
    }

    /// The count is what a press pushes: an update-and-push fast-forwards from the branch's own
    /// update source first, and the commits the fast-forward brings go to the destination too.
    #[tokio::test]
    async fn update_and_push_counts_the_commits_a_press_pushes() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "upstream", &branch]);
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        git_ok(&repo_path, &["push", "origin", &branch]);
        // The update source moves on, so a press fast-forwards the branch and then pushes what
        // it carries.
        git_ok(&repo_path, &["switch", "-c", "upstream-side"]);
        commit_file(&repo_path, "moved.txt", "upstream moved on");
        commit_file(&repo_path, "moved-again.txt", "upstream moved on again");
        git_ok(&repo_path, &["push", "upstream", &format!("HEAD:{branch}")]);
        git_ok(&repo_path, &["switch", &branch]);
        git_ok(
            &repo_path,
            &["remote", "set-url", "--push", "upstream", "no-push"],
        );
        git_ok(&repo_path, &["fetch", "upstream"]);

        let state = remote_state(&repo_path).await;
        assert_eq!(state.behind, 2);
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.publish, Some(false));
        assert_eq!(
            target.commits, 2,
            "the commits the fast-forward brings are pushed too"
        );

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD"),
            "origin received the fast-forwarded branch"
        );
    }

    /// The destination's copy is fetched when its tip is unknown here, so the count is exact
    /// even though no local ref has seen that tip.
    #[tokio::test]
    async fn destination_advanced_elsewhere_is_fetched_before_counting() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "origin", &branch]);
        // Another clone moves the destination on, so its tip is not in this repository's
        // object store.
        let elsewhere = remotes.path().join("elsewhere");
        git_ok(
            remotes.path(),
            &[
                "clone",
                "--quiet",
                origin.to_str().expect("origin path"),
                elsewhere.to_str().expect("elsewhere path"),
            ],
        );
        for (key, value) in [("user.name", "Elsewhere"), ("user.email", "e@test.com")] {
            git_ok(&elsewhere, &["config", key, value]);
        }
        git_ok(
            &elsewhere,
            &["checkout", "-B", &branch, &format!("origin/{branch}")],
        );
        commit_file(&elsewhere, "elsewhere.txt", "origin moved on");
        git_ok(&elsewhere, &["push", "origin", &format!("HEAD:{branch}")]);
        let elsewhere_head = rev_parse(&elsewhere, "HEAD");
        commit_file(&repo_path, "local.txt", "only the local branch has this");
        assert!(
            !rev_exists(&repo_path, &elsewhere_head)
                .await
                .expect("rev exists"),
            "the destination's new tip starts out unknown here"
        );

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.publish, Some(false));
        assert_eq!(target.commits, 1, "only the local commit is not on origin");
        assert_eq!(
            rev_parse(&repo_path, &format!("refs/remotes/origin/{branch}")),
            elsewhere_head,
            "the probe fetched the destination's copy"
        );
    }

    /// The destination is asked directly: a branch it already carries is never announced as a
    /// publish just because this repository has no local ref for it (a narrowed
    /// `remote.<name>.fetch` refspec never creates one).
    #[tokio::test]
    async fn destination_branch_is_detected_without_a_local_ref() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "origin", &branch]);
        git_ok(
            &repo_path,
            &["update-ref", "-d", &format!("refs/remotes/origin/{branch}")],
        );
        commit_file(&repo_path, "later.txt", "only the local branch has this");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(
            target.publish,
            Some(false),
            "origin carries the branch even though no local ref says so"
        );
        assert_eq!(target.commits, 1);

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("origin")
        );
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD")
        );
    }

    /// The probe matches the branch's own ref: a nested ref on the destination
    /// (`feature/<branch>`) is not mistaken for the branch itself.
    #[tokio::test]
    async fn nested_destination_branch_is_not_mistaken_for_ours() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(
            &repo_path,
            &[
                "push",
                "origin",
                &format!("HEAD:refs/heads/feature/{branch}"),
            ],
        );

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(
            target.publish,
            Some(true),
            "origin has no branch named {branch}"
        );
        assert_eq!(
            target.commits,
            count_commits(&repo_path, "HEAD").await.expect("count")
        );
    }

    /// A publish skips the update step: the destination has no such branch to update from, so
    /// the branch's commits go out as they are.
    #[tokio::test]
    async fn publish_skips_the_update_step() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "upstream", &branch]);
        // The upstream moves on, so a pull would change the branch.
        git_ok(&repo_path, &["switch", "-c", "upstream-side"]);
        commit_file(&repo_path, "remote.txt", "upstream moved on");
        git_ok(&repo_path, &["push", "upstream", &format!("HEAD:{branch}")]);
        git_ok(&repo_path, &["switch", &branch]);
        git_ok(
            &repo_path,
            &["remote", "set-url", "--push", "upstream", "no-push"],
        );
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        git_ok(&repo_path, &["fetch", "upstream"]);
        let published_head = rev_parse(&repo_path, "HEAD");

        let state = remote_state(&repo_path).await;
        assert_eq!(state.behind, 1);
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.publish, Some(true), "origin has no such branch yet");

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&repo_path, "HEAD"),
            published_head,
            "a publish does not update the branch"
        );
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            published_head,
            "origin received exactly what the branch carried"
        );
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("upstream"),
            "the fetch-only tracking is left alone"
        );
    }

    /// A branch tracking a push-capable remote keeps that remote as its destination, and has
    /// nothing to offer once in sync.
    #[tokio::test]
    async fn tracked_push_capable_remote_stays_the_destination() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let upstream = add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "upstream", &branch]);
        commit_file(&repo_path, "pushed.txt", "second");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "upstream");
        assert_eq!(target.publish, Some(false));
        assert_eq!(target.commits, 1);

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert!(
            report.output.contains(&branch),
            "a real push reports itself: {}",
            report.output
        );
        assert_eq!(
            rev_parse(&upstream, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD"),
            "the tracked remote received the commit"
        );
        assert!(
            !remote_state(&repo_path).await.has_sync_work(),
            "in sync: the control hides, as before"
        );
    }

    /// An unreachable destination does not hide the branch and does not claim a publish: the
    /// branch is reported with the commits it carries, its reachability is not asserted, and a
    /// press reports git's own reason.
    #[tokio::test]
    async fn unreachable_destination_still_offers_a_push() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        std::fs::remove_dir_all(&origin).expect("remove the remote");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.publish, None, "the destination was never asked");
        assert_eq!(
            target.commits,
            count_commits(&repo_path, "HEAD").await.expect("count"),
            "the branch is reported with the commits it carries"
        );
        assert!(state.has_sync_work());
    }

    /// The destination the control names is the one a plain `git push` reaches: a configured
    /// `branch.<name>.pushRemote` wins over the tracked remote.
    #[tokio::test]
    async fn configured_push_remote_is_the_named_destination() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "origin");
        let backup = add_bare_remote(remotes.path(), &repo_path, "backup");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "origin", &branch]);
        git_ok(&repo_path, &["push", "backup", &branch]);
        git_ok(
            &repo_path,
            &["config", &format!("branch.{branch}.pushRemote"), "backup"],
        );
        commit_file(&repo_path, "pushed.txt", "only the push remote lacks this");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "backup", "the control names the push remote");
        assert_eq!(target.publish, Some(false));
        assert_eq!(target.commits, 1);

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&backup, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD"),
            "the named destination received the commit"
        );
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("origin"),
            "the tracking is left alone"
        );
    }

    /// A push remote whose push destination is disabled is never used: the push goes to the
    /// tracked remote that accepts pushes.
    #[tokio::test]
    async fn fetch_only_push_remote_falls_back_to_the_tracked_remote() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let upstream = add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "origin", &branch]);
        // Git's own way of making a remote fetch-only, this time as the branch's configured
        // push remote.
        git_ok(
            &repo_path,
            &["remote", "set-url", "--push", "upstream", "no-push"],
        );
        git_ok(
            &repo_path,
            &["config", &format!("branch.{branch}.pushRemote"), "upstream"],
        );
        commit_file(
            &repo_path,
            "pushed.txt",
            "only the tracked remote lacks this",
        );

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(target.commits, 1);

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD")
        );
        let upstream_refs =
            String::from_utf8_lossy(&git_ok(&upstream, &["for-each-ref"]).stdout).to_string();
        assert!(
            upstream_refs.trim().is_empty(),
            "the fetch-only remote received nothing: {upstream_refs}"
        );
    }

    /// A branch tracking a fetch-only upstream still pushes to the push-capable remote and
    /// keeps its fetch-only tracking.
    #[tokio::test]
    async fn fetch_only_upstream_stays_tracked_while_pushing_to_origin() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "upstream", &branch]);
        // Git's own way of making a remote fetch-only.
        git_ok(
            &repo_path,
            &["remote", "set-url", "--push", "upstream", "no-push"],
        );
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        git_ok(&repo_path, &["push", "origin", &branch]);
        commit_file(&repo_path, "pushed.txt", "Only origin lacks this");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(
            target.publish,
            Some(false),
            "origin already carries the branch"
        );
        assert_eq!(target.commits, 1);

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none(), "origin accepts pushes");
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("upstream"),
            "a fetch-only tracking is left alone"
        );
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD"),
            "origin received the commit"
        );
    }

    /// A branch whose tracking ref is gone (deleted remote branch, pruned or narrowed fetch)
    /// still resolves: the destination is asked directly, and the press republishes without
    /// overwriting the branch's tracking config.
    #[tokio::test]
    async fn missing_tracking_ref_still_resolves_and_publishes() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "origin", &branch]);
        git_ok(&origin, &["config", "receive.denyDeleteCurrent", "ignore"]);
        git_ok(&repo_path, &["push", "origin", "--delete", &branch]);

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Target(target) = &state.push else {
            panic!("expected a push target, got {:?}", state.push);
        };
        assert_eq!(target.remote, "origin");
        assert_eq!(
            target.publish,
            Some(true),
            "origin no longer carries the branch"
        );

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(report.not_pushed.is_none());
        assert_eq!(
            rev_parse(&origin, &format!("refs/heads/{branch}")),
            rev_parse(&repo_path, "HEAD")
        );
        assert_eq!(
            tracked(&repo_path, &branch).await.as_deref(),
            Some("origin"),
            "the existing tracking config is left alone"
        );
    }

    /// A branch that tracks a fetch-only upstream is still updated from it when no remote can
    /// take a push: the update step is not a guess.
    #[tokio::test]
    async fn behind_branch_still_fast_forwards_when_nowhere_to_push() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "upstream");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "-u", "upstream", &branch]);
        // Two pushable remotes make the destination ambiguous.
        add_bare_remote(remotes.path(), &repo_path, "origin");
        add_bare_remote(remotes.path(), &repo_path, "backup");

        // Advance the upstream from a side branch, so the checked-out branch is behind its own
        // update source; only then make the remote fetch-only.
        git_ok(&repo_path, &["switch", "-c", "upstream-side"]);
        commit_file(&repo_path, "remote.txt", "upstream moved on");
        git_ok(&repo_path, &["push", "upstream", &format!("HEAD:{branch}")]);
        git_ok(&repo_path, &["switch", &branch]);
        git_ok(
            &repo_path,
            &["remote", "set-url", "--push", "upstream", "no-push"],
        );
        git_ok(&repo_path, &["fetch", "upstream"]);
        let behind_head = rev_parse(&repo_path, "HEAD");

        let state = remote_state(&repo_path).await;
        assert_eq!(state.behind, 1);
        assert!(matches!(state.push, GitPushDestination::Nowhere { .. }));
        assert!(state.has_sync_work());

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert!(
            report.not_pushed.is_some(),
            "nothing can take a push, and the report says so"
        );
        assert_ne!(
            rev_parse(&repo_path, "HEAD"),
            behind_head,
            "the branch was fast-forwarded from its own update source"
        );
        assert_eq!(
            rev_parse(&repo_path, "HEAD"),
            rev_parse(&repo_path, &format!("upstream/{branch}"))
        );
    }

    /// With no remote at all, nothing is guessed and the control says so.
    #[tokio::test]
    async fn no_pushable_remote_reports_nowhere() {
        let (_dir, repo_path) = init_temp_repo();
        let state = remote_state(&repo_path).await;
        let GitPushDestination::Nowhere { reason } = &state.push else {
            panic!("expected nowhere, got {:?}", state.push);
        };
        assert!(reason.contains("push"), "reason mentions pushes: {reason}");
        assert!(
            state.has_sync_work(),
            "the control says why rather than hiding"
        );

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert_eq!(report.not_pushed.as_deref(), Some(reason.as_str()));
        assert!(report.output.is_empty(), "nothing ran: {}", report.output);
    }

    /// Two pushable remotes are ambiguous — neither is picked, nothing is pushed, and the
    /// control still says why.
    #[tokio::test]
    async fn several_pushable_remotes_are_not_guessed() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        let origin = add_bare_remote(remotes.path(), &repo_path, "origin");
        let backup = add_bare_remote(remotes.path(), &repo_path, "backup");

        let state = remote_state(&repo_path).await;
        let GitPushDestination::Nowhere { reason } = &state.push else {
            panic!("expected nowhere, got {:?}", state.push);
        };
        assert!(
            reason.contains("origin") && reason.contains("backup"),
            "the reason names both remotes: {reason}"
        );
        assert!(
            state.has_sync_work(),
            "a branch with no single destination still shows the control"
        );

        let report = run_git_sync(&repo_path).await.expect("sync");
        assert_eq!(report.not_pushed.as_deref(), Some(reason.as_str()));
        assert!(report.output.is_empty(), "nothing ran: {}", report.output);
        for remote in [&origin, &backup] {
            let refs =
                String::from_utf8_lossy(&git_ok(remote, &["for-each-ref"]).stdout).to_string();
            assert!(refs.trim().is_empty(), "nothing was pushed: {refs}");
        }
    }

    /// Dummy push URLs (git's fetch-only convention) are unusable; every real transport and an
    /// existing local path are usable.
    #[test]
    fn push_destination_accepts_pushes_distinguishes_dummy_urls() {
        let (_dir, repo_path) = init_temp_repo();
        for url in ["no-push", "no_push", "DISABLED", "", "  "] {
            assert!(
                !push_destination_accepts_pushes(&repo_path, url),
                "{url:?} must not accept pushes"
            );
        }
        for url in [
            "../remote.git",
            "/abs/x.git",
            "https://example.com/x.git",
            "git@example.com:x.git",
            "ssh://example.com/x.git",
            "ssh+git://example.com/x.git",
            "git+ssh://example.com/x.git",
            "codecommit://example/repo",
            "file:///tmp/x.git",
        ] {
            assert!(
                push_destination_accepts_pushes(&repo_path, url),
                "{url} must accept pushes"
            );
        }
        // A bare word only counts when it names an existing local path.
        std::fs::create_dir(repo_path.join("local-remote.git")).expect("create dir");
        assert!(push_destination_accepts_pushes(
            &repo_path,
            "local-remote.git"
        ));
    }

    /// A refused push surfaces git's own reason, not a generic failure.
    #[tokio::test]
    async fn refused_push_reports_git_reason() {
        let (_dir, repo_path) = init_temp_repo();
        let remotes = tempfile::tempdir().expect("remote dir");
        add_bare_remote(remotes.path(), &repo_path, "origin");
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        git_ok(&repo_path, &["push", "origin", &branch]);

        // A commit only the remote gets, then a different one locally — the branches diverge
        // and a plain push is refused.
        git_ok(&repo_path, &["switch", "-c", "remote-only"]);
        commit_file(&repo_path, "remote.txt", "remote only");
        git_ok(&repo_path, &["push", "origin", &format!("HEAD:{branch}")]);
        git_ok(&repo_path, &["switch", &branch]);
        commit_file(&repo_path, "local.txt", "local only");

        let err = run_git_sync(&repo_path)
            .await
            .expect_err("a diverged push must be refused")
            .to_string();
        assert!(
            err.contains("rejected") || err.contains("non-fast-forward"),
            "git's own refusal reason must survive: {err}"
        );
    }

    /// Shared porcelain test input with a mix of untracked (`??`), staged-as-new (`A `),
    /// modified, and C-quoted special-character paths.
    const PORCELAIN_INPUT: &str = "\
?? new_file.rs
M  modified.rs
?? another_new.py
A  staged_new.js
?? dir/untracked.txt
 M working_tree_only.txt
?? temp.log
AM staged_then_modified.js
 A working_tree_new.txt
?? \"file\\tname.rs\"
A  \"staged\\\"file.js\"
?? \"file\\\\backslash.rs\"
";

    /// The two listings over one mixed reading, and the entries both must refuse.
    /// `parse_new_files_from_porcelain` takes untracked and staged-as-new records;
    /// `parse_untracked_from_porcelain` takes `??` only, so a staged file is not listed twice.
    /// Both unquote C-quoted paths and both report nothing for a record that is too short,
    /// does not unquote, or names a collapsed nested repository. The byte-level unstaged check
    /// still counts an entry no parser accepts — see `has_unstaged_changes_cases`.
    #[test]
    fn porcelain_listings_classify_and_skip_unusable_entries() {
        assert_eq!(
            parse_new_files_from_porcelain(PORCELAIN_INPUT),
            [
                "new_file.rs",
                "another_new.py",
                "staged_new.js",
                "dir/untracked.txt",
                "temp.log",
                "staged_then_modified.js",
                "file\tname.rs",
                "staged\"file.js",
                "file\\backslash.rs",
            ],
            "untracked (`??`) and staged-as-new (`A`) records, C-quotes unquoted"
        );
        assert_eq!(
            parse_untracked_from_porcelain(PORCELAIN_INPUT),
            [
                "new_file.rs",
                "another_new.py",
                "dir/untracked.txt",
                "temp.log",
                "file\tname.rs",
                "file\\backslash.rs",
            ],
            "`??` records only, so staged-as-new files are not listed twice"
        );

        // Readings that list nothing: only modified/deleted records, and lines too short to
        // carry a path.
        for porcelain in [
            "M  modified.rs\n M working_tree_only.txt\nD  deleted.rs\n A working_tree_new.txt\n",
            "A",
            "A ",
            "?? ",
            "??",
        ] {
            assert!(
                parse_new_files_from_porcelain(porcelain).is_empty(),
                "no new file in {porcelain:?}"
            );
            assert!(
                parse_untracked_from_porcelain(porcelain).is_empty(),
                "no untracked file in {porcelain:?}"
            );
        }

        // A path that does not unquote is skipped by both listings.
        let unusable = "?? \"broken\\q.rs\"\n?? good.rs\nA  \"also\\qbroken.rs\"\n";
        assert_eq!(parse_untracked_from_porcelain(unusable), ["good.rs"]);
        assert_eq!(parse_new_files_from_porcelain(unusable), ["good.rs"]);

        // A collapsed nested repository is one `dir/` entry, not a file, and must not reach the
        // manifest (or be counted as an omitted file).
        assert_eq!(
            parse_untracked_from_porcelain("?? nested/\n?? real.rs\n"),
            ["real.rs"]
        );
    }

    #[expect(clippy::too_many_lines)]
    #[test]
    fn test_parse_git_status_porcelain() {
        struct Case {
            /// Short label for failure messages.
            name: &'static str,
            /// Raw git status --porcelain output.
            input: &'static str,
            /// `(path, None)` asserts absence from the map; an empty slice asserts the whole
            /// map is empty.
            expected: &'static [(&'static str, Option<GitFileStatus>)],
        }
        let cases: &[Case] = &[
            Case {
                name: "unstaged modified file",
                input: " M src/main.rs\n",
                expected: &[("src/main.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "staged added file",
                input: "A  new_file.rs\n",
                expected: &[("new_file.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "untracked file",
                input: "?? new_file.rs\n",
                expected: &[("new_file.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "intent-to-add ( A) is added",
                input: " A intent.rs\n",
                expected: &[("intent.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "staged and unstaged modified (MM)",
                input: "MM both.rs\n",
                expected: &[("both.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "staged added + unstaged modified (AM)",
                input: "AM partial.rs\n",
                expected: &[("partial.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename (old -> new)",
                input: "R  old.rs -> new.rs\n",
                expected: &[("new.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename with arrow in old path",
                input: "R  \"old -> name.rs\" -> \"new -> name.rs\"\n",
                expected: &[("new -> name.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename from a quoted source to a plain destination",
                input: "R  \"a b.txt\" -> plain.txt\n",
                expected: &[("plain.txt", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename into a quoted destination containing the delimiter",
                input: "R  plain.txt -> \"new -> name.txt\"\n",
                expected: &[("new -> name.txt", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename carried in the worktree column",
                input: " R old.rs -> new.rs\n",
                expected: &[("new.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "copy skipped",
                input: "C  old.rs -> copy.rs\n",
                expected: &[],
            },
            Case {
                name: "unmerged add/add (AA) is added",
                input: "AA both.rs\n",
                expected: &[("both.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "added then deleted (AD) skipped",
                input: "AD gone.rs\n",
                expected: &[],
            },
            Case {
                name: "typechange and unmerged (UU) skipped",
                input: " T link\nUU conflict.rs\n",
                expected: &[],
            },
            Case {
                name: "untracked directory (trailing slash stripped)",
                input: "?? new_dir/\n",
                expected: &[("new_dir", Some(GitFileStatus::Added))],
            },
            Case {
                name: "quoted path with spaces",
                input: " M \"path with spaces.rs\"\n",
                expected: &[("path with spaces.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "deleted file (unstaged) skipped",
                input: " D gone.rs\n",
                expected: &[],
            },
            Case {
                name: "deleted file (staged) skipped",
                input: "D  gone.rs\n",
                expected: &[],
            },
            Case {
                name: "clean (unrecognized status) not present",
                input: "   clean.rs\n",
                expected: &[("clean.rs", None)],
            },
            Case {
                name: "multiple entries same file — modified wins over added",
                input: "A  dup.rs\n M dup.rs\n",
                expected: &[("dup.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "multiple entries same file — added sticks",
                input: "?? dup.rs\nA  dup.rs\n",
                expected: &[("dup.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "empty output",
                input: "",
                expected: &[],
            },
            Case {
                name: "mixed statuses",
                input: concat!(
                    " M src/main.rs\n",
                    "?? new_file.rs\n",
                    "A  staged.rs\n",
                    " D deleted.rs\n",
                ),
                expected: &[
                    ("src/main.rs", Some(GitFileStatus::Modified)),
                    ("new_file.rs", Some(GitFileStatus::Added)),
                    ("staged.rs", Some(GitFileStatus::Added)),
                    ("deleted.rs", None),
                ],
            },
        ];

        for case in cases {
            let map = parse_git_status_porcelain(case.input);

            if case.expected.is_empty() {
                assert!(
                    map.is_empty(),
                    "case '{}' (input={:?}): expected empty map, got {:#?}",
                    case.name,
                    case.input,
                    map
                );
            } else {
                let expected_count = case.expected.iter().filter(|(_, s)| s.is_some()).count();
                assert_eq!(
                    map.len(),
                    expected_count,
                    "case '{}' (input={:?}): map has unexpected entries",
                    case.name,
                    case.input,
                );
                for &(path, expected_status) in case.expected {
                    match expected_status {
                        Some(status) => {
                            assert_eq!(
                                map.get(path),
                                Some(&status),
                                "case '{}' (input={:?}): path={:?}",
                                case.name,
                                case.input,
                                path
                            );
                        }
                        None => {
                            assert!(
                                !map.contains_key(path),
                                "case '{}' (input={:?}): path={:?} should be absent, got {:?}",
                                case.name,
                                case.input,
                                path,
                                map.get(path)
                            );
                        }
                    }
                }
            }
        }
    }

    /// A rename into a name that itself contains the ` -> ` delimiter: git quotes only the
    /// destination, so splitting at the quoted side's own delimiter would key a bogus path.
    #[cfg(unix)]
    #[tokio::test]
    async fn git_status_rename_into_a_name_with_the_delimiter_keys_its_destination() {
        let (_dir, repo_path) = init_temp_repo();
        run_git_command(&repo_path, &["config", "status.renames", "true"])
            .await
            .unwrap();
        run_git_command(&repo_path, &["mv", "test.txt", "new -> name.txt"])
            .await
            .unwrap();

        let porcelain = run_git_status(&repo_path).await.unwrap();
        assert!(
            porcelain.starts_with("R  test.txt -> \"new -> name.txt\""),
            "git's quoting is what this pins, got {porcelain:?}"
        );

        let map = parse_git_status_porcelain(&porcelain);
        assert_eq!(
            map.get("new -> name.txt"),
            Some(&GitFileStatus::Modified),
            "got {map:?}"
        );
    }

    /// numstat line parsing: normal, binary, malformed-skip, and empty inputs.
    #[test]
    fn parse_numstat_lines_cases() {
        let cases: &[(&str, &str, Vec<NumstatEntry>)] = &[
            (
                "normal",
                "10\t3\tsrc/main.rs\n0\t1\tsrc/lib.rs\n42\t7\tCargo.toml\n",
                vec![
                    NumstatEntry {
                        additions: Some(10),
                        deletions: Some(3),
                        path: "src/main.rs".to_string(),
                    },
                    NumstatEntry {
                        additions: Some(0),
                        deletions: Some(1),
                        path: "src/lib.rs".to_string(),
                    },
                    NumstatEntry {
                        additions: Some(42),
                        deletions: Some(7),
                        path: "Cargo.toml".to_string(),
                    },
                ],
            ),
            (
                "binary",
                "-\t-\timage.png\n42\t7\tsrc/main.rs\n",
                vec![
                    NumstatEntry {
                        additions: None,
                        deletions: None,
                        path: "image.png".to_string(),
                    },
                    NumstatEntry {
                        additions: Some(42),
                        deletions: Some(7),
                        path: "src/main.rs".to_string(),
                    },
                ],
            ),
            (
                "skips_malformed",
                "\n\n10\t3\tsrc/main.rs\n\t\t\nnot-enough-fields\n",
                vec![NumstatEntry {
                    additions: Some(10),
                    deletions: Some(3),
                    path: "src/main.rs".to_string(),
                }],
            ),
            ("empty_string", "", vec![]),
            ("empty_lines", "\n\n\n", vec![]),
        ];
        for (name, input, expected) in cases {
            assert_eq!(parse_numstat_lines(input), *expected, "case: {name}");
        }
    }

    /// Discard changes to a modified tracked file — restores it to HEAD.
    #[tokio::test]
    async fn test_run_git_discard_modified_file() {
        let (_dir, repo_path) = init_temp_repo();

        std::fs::write(repo_path.join("test.txt"), b"modified content\n")
            .expect("write modified file");

        let status = run_git_command(&repo_path, &["status", "--porcelain", "test.txt"])
            .await
            .expect("status before discard");
        assert!(
            !status.trim().is_empty(),
            "file should be dirty before discard"
        );

        run_git_discard(&repo_path, "test.txt", DiscardTarget::File)
            .await
            .expect("run_git_discard should succeed");

        let status = run_git_command(&repo_path, &["status", "--porcelain", "test.txt"])
            .await
            .expect("status after discard");
        assert!(
            status.trim().is_empty(),
            "file should be clean after discard"
        );

        let content = std::fs::read_to_string(repo_path.join("test.txt")).expect("read file");
        assert_eq!(
            content, "line1\nline2\nline3\n",
            "content should be restored to HEAD"
        );
    }

    /// Untracked content is removed by a discard, in both target shapes: a new file, and a
    /// directory that goes recursively.
    #[tokio::test]
    async fn test_run_git_discard_untracked_file_and_directory() {
        let (_dir, repo_path) = init_temp_repo();
        let new_path = repo_path.join("new_file.rs");
        std::fs::write(&new_path, b"fn new() {}").expect("write new file");
        let sub_dir = repo_path.join("subdir");
        std::fs::create_dir(&sub_dir).expect("create subdir");
        let sub_file = sub_dir.join("nested.rs");
        std::fs::write(&sub_file, b"fn nested() {}").expect("write nested file");

        run_git_discard(&repo_path, "new_file.rs", DiscardTarget::File)
            .await
            .expect("run_git_discard should succeed");
        run_git_discard(&repo_path, "subdir", DiscardTarget::Directory)
            .await
            .expect("run_git_discard should succeed");

        assert!(
            !new_path.exists(),
            "new file should be removed after discard"
        );
        assert!(
            !sub_dir.exists(),
            "directory and its contents should be removed after discard"
        );
    }

    /// Diff-window paths are repo-root-relative. Discarding from a subdirectory workspace must
    /// target the root file, never a same-named file beneath it.
    #[tokio::test]
    async fn test_run_git_discard_from_subdirectory_targets_the_root_path() {
        let (_dir, repo_path) = init_temp_repo();
        let sub = repo_path.join("sub");
        std::fs::create_dir(&sub).expect("create subdir");
        let nested = sub.join("test.txt");
        std::fs::write(&nested, b"nested\n").expect("write nested file");
        std::fs::write(repo_path.join("test.txt"), b"modified\n").expect("modify root file");

        run_git_discard(&sub, "test.txt", DiscardTarget::File)
            .await
            .expect("run_git_discard should succeed");

        assert_eq!(
            std::fs::read_to_string(repo_path.join("test.txt")).expect("read root file"),
            "line1\nline2\nline3\n",
            "the root file is restored"
        );
        assert!(
            nested.exists(),
            "the same-named file under the workspace is untouched"
        );
    }

    /// The untracked mode is pinned on the status readers and the discard verification, so the
    /// owner's `status.showUntrackedFiles` cannot decide what the pipeline sees: with it off,
    /// untracked files stay visible to both readings and a leftover discard is still reported
    /// as a failure.
    #[tokio::test]
    async fn status_readers_pin_the_untracked_mode() {
        let (_dir, repo_path) = init_temp_repo();
        std::fs::create_dir(repo_path.join("sub")).unwrap();
        std::fs::write(repo_path.join("sub/file.txt"), b"new\n").unwrap();
        // A nested repository, which `git clean -fd` deliberately keeps (it needs `-ff`), so
        // the discard below leaves an untracked entry behind.
        let nested = repo_path.join("nested");
        std::fs::create_dir(&nested).unwrap();
        run_git_command(&nested, &["init", "-q"]).await.unwrap();
        run_git_command(&repo_path, &["config", "status.showUntrackedFiles", "no"])
            .await
            .unwrap();

        let porcelain = run_git_status(&repo_path).await.unwrap();
        assert!(
            porcelain.lines().any(|line| line == "?? sub/"),
            "untracked files must stay visible with the owner's mode off:\n{porcelain}"
        );

        assert_eq!(
            list_new_or_untracked_files(&repo_path).await.unwrap(),
            ["nested/", "sub/"],
            "the listing must keep the collapsed directory entry, not read as empty"
        );

        let err = run_git_discard(&repo_path, "nested", DiscardTarget::Directory)
            .await
            .expect_err("a leftover must be reported, not passed off as a success");
        assert!(
            err.to_string().contains("Changes remain after discard"),
            "unexpected error: {err}"
        );
    }

    /// Empty, fully-staged, unstaged, dual-status, untracked, mixed, trailing-newline, and
    /// unparseable-path porcelain inputs.
    #[test]
    fn has_unstaged_changes_cases() {
        let cases: &[(&str, &str, bool)] = &[
            ("empty_string", "", false),
            ("empty_lines", "\n\n", false),
            ("fully_staged_modified", "M  Cargo.toml\n", false),
            ("fully_staged_added", "A  src/lib.rs\n", false),
            (
                "fully_staged_mixed",
                "M  Cargo.toml\nA  src/lib.rs\nD  old.rs\n",
                false,
            ),
            ("unstaged_modified", " M src/lib.rs\n", true),
            ("unstaged_deleted", " D src/old.rs\n", true),
            ("dual_status_modified", "MM src/lib.rs\n", true),
            ("dual_status_added", "AM src/new.rs\n", true),
            ("dual_status_deleted", "MD src/old.rs\n", true),
            ("untracked_file", "?? new_file.rs\n", true),
            ("untracked_directory", "?? dir/untracked.txt\n", true),
            (
                "mixed_only_staged",
                "M  Cargo.toml\nA  src/main.rs\n",
                false,
            ),
            (
                "mixed_staged_and_unstaged",
                "M  Cargo.toml\n M src/main.rs\n?? new.rs\n",
                true,
            ),
            ("trailing_newline_unstaged", " M file.rs\n", true),
            ("trailing_newline_staged", "M  file.rs\n", false),
            // A path no parser accepts must still count: this gate runs on bytes, not records,
            // so a malformed entry can never read as clean.
            ("unparseable_quoted_path", " M \"broken\\q.rs\"\n", true),
            (
                "unparseable_path_after_staged",
                "M  file.rs\n M \"broken\\q.rs\"\n",
                true,
            ),
        ];
        for (name, input, expected) in cases {
            assert_eq!(has_unstaged_changes(input), *expected, "case: {name}");
        }
    }
}