ag-git 0.14.5

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

#[cfg(unix)]
use rustix::fs::{self as rustix_fs, Access};
use tokio::task::spawn_blocking;
use tokio::time;

use super::error::GitError;
use super::rebase::{
    GIT_INDEX_LOCK_RETRY_ATTEMPTS, GIT_INDEX_LOCK_RETRY_DELAY, is_git_index_lock_error,
    is_rebase_conflict, run_git_command_with_index_lock_retry,
};
use super::repo::{
    AsyncGitCommand, AsyncGitCommandOutput, AsyncGitCommandRunner, ProcessAsyncGitCommandRunner,
    command_output_detail, run_git_command, run_git_command_output_sync,
    run_git_command_output_with_env_sync, run_git_command_sync, run_git_command_with_runner,
};

/// Map of local branch names to their ahead/behind counts relative to their
/// tracked upstream branch. `None` indicates no upstream or a gone upstream.
pub type BranchTrackingMap = HashMap<String, Option<(u32, u32)>>;

const COMMIT_ALL_HOOK_RETRY_ATTEMPTS: usize = 5;
const MAX_WORKTREE_FILE_BYTE_COUNT: usize = 1024 * 1024;
const PRE_COMMIT_CONFIG_FILES: [&str; 2] = [".pre-commit-config.yaml", ".pre-commit-config.yml"];

/// Bounded content returned when reading a worktree file for presentation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WorktreeFileContent {
    /// The file contains valid UTF-8 text within the preview byte limit.
    Text(String),
    /// The file does not exist in the current worktree.
    Missing,
    /// The file is not valid UTF-8 text.
    Binary,
    /// The file exceeds the preview byte limit.
    TooLarge,
}

/// Controls how single-commit session branches treat the commit message when
/// amending `HEAD`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SingleCommitMessageStrategy {
    /// Replaces the existing `HEAD` message with the newly generated message.
    Replace,
    /// Keeps the current `HEAD` message while amending file content only.
    Reuse,
}

/// Result of attempting `git pull --rebase`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PullRebaseResult {
    /// Pull and rebase completed successfully.
    Completed,
    /// Pull stopped because of merge conflicts.
    Conflict {
        /// Git diagnostic describing the conflict state.
        detail: String,
    },
}

/// Stages all changes and commits them with the given message.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `commit_message` - Message for the commit
/// * `no_verify` - When `true`, skips configured git hooks such as
///   `prek`-managed `pre-commit` and `commit-msg` hooks (`--no-verify`)
///
/// # Returns
/// Ok(()) on success.
///
/// # Errors
/// Returns a [`GitError`] if staging or committing changes fails.
pub(crate) async fn commit_all(
    repo_path: PathBuf,
    commit_message: String,
    no_verify: bool,
) -> Result<(), GitError> {
    commit_all_with_retry(
        repo_path,
        commit_message,
        SingleCommitMessageStrategy::Replace,
        no_verify,
        false,
    )
    .await
}

/// Stages all changes and keeps a single commit for the provided message.
///
/// Creates a new commit when `HEAD` has no commits beyond `base_branch`.
/// Otherwise, amends `HEAD` so the branch keeps one evolving session commit.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `base_branch` - Branch used to detect whether a session commit already
///   exists on `HEAD`
/// * `commit_message` - Message that identifies the session commit
/// * `message_strategy` - Whether amends replace or reuse the existing `HEAD`
///   message
/// * `no_verify` - When `true`, skips configured git hooks such as
///   `prek`-managed `pre-commit` and `commit-msg` hooks (`--no-verify`)
///
/// # Returns
/// Ok(()) on success.
///
/// # Errors
/// Returns a [`GitError`] if staging, commit lookup, or committing changes
/// fails.
pub(crate) async fn commit_all_preserving_single_commit(
    repo_path: PathBuf,
    base_branch: String,
    commit_message: String,
    message_strategy: SingleCommitMessageStrategy,
    no_verify: bool,
) -> Result<(), GitError> {
    let amend_existing_commit = has_commits_since(repo_path.clone(), base_branch).await?;

    commit_all_with_retry(
        repo_path,
        commit_message,
        message_strategy,
        no_verify,
        amend_existing_commit,
    )
    .await
}

/// Stages all changes in the repository or worktree.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// Ok(()) on success.
///
/// # Errors
/// Returns a [`GitError`] if `git add -A` fails.
pub(crate) async fn stage_all(repo_path: PathBuf) -> Result<(), GitError> {
    spawn_blocking(move || stage_all_sync(&repo_path)).await?
}

/// Verifies that configured pre-commit validation has an executable Git hook.
///
/// # Errors
/// Returns [`GitError::PreCommitHookMissing`] when a supported configuration
/// exists without an executable hook, or a command error when the effective
/// hook path cannot be resolved.
pub(crate) async fn check_pre_commit_hook_ready(repo_path: PathBuf) -> Result<(), GitError> {
    spawn_blocking(move || ensure_pre_commit_hook_ready(&repo_path)).await?
}

/// Returns the short hash of the current `HEAD` commit.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// The short commit hash as a string.
///
/// # Errors
/// Returns a [`GitError`] if resolving `HEAD` fails.
pub(crate) async fn head_short_hash(repo_path: PathBuf) -> Result<String, GitError> {
    let hash = run_git_command(
        repo_path,
        vec![
            "rev-parse".to_string(),
            "--short".to_string(),
            "HEAD".to_string(),
        ],
        "Failed to resolve HEAD hash".to_string(),
    )
    .await?;
    let hash = hash.trim().to_string();
    if hash.is_empty() {
        return Err(GitError::OutputParse(
            "Failed to resolve HEAD hash: empty output".to_string(),
        ));
    }

    Ok(hash)
}

/// Returns the full hash of the current `HEAD` commit.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// The full commit hash as a string.
///
/// # Errors
/// Returns a [`GitError`] if resolving `HEAD` fails.
pub(crate) async fn head_hash(repo_path: PathBuf) -> Result<String, GitError> {
    let hash = run_git_command(
        repo_path,
        vec!["rev-parse".to_string(), "HEAD".to_string()],
        "Failed to resolve HEAD hash".to_string(),
    )
    .await?;
    let hash = hash.trim().to_string();
    if hash.is_empty() {
        return Err(GitError::OutputParse(
            "Failed to resolve HEAD hash: empty output".to_string(),
        ));
    }

    Ok(hash)
}

/// Returns the full commit hash for a git reference.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree.
/// * `reference` - Branch, tag, or commit-ish to resolve.
///
/// # Returns
/// The full commit hash as a string.
///
/// # Errors
/// Returns a [`GitError`] if the reference cannot be resolved to a commit.
pub(crate) async fn ref_hash(repo_path: PathBuf, reference: String) -> Result<String, GitError> {
    let hash = run_git_command(
        repo_path,
        vec![
            "rev-parse".to_string(),
            "--verify".to_string(),
            format!("{reference}^{{commit}}"),
        ],
        format!("Failed to resolve `{reference}` hash"),
    )
    .await?;
    let hash = hash.trim().to_string();
    if hash.is_empty() {
        return Err(GitError::OutputParse(format!(
            "Failed to resolve `{reference}` hash: empty output"
        )));
    }

    Ok(hash)
}

/// Returns the full `HEAD` commit message, or `None` when no commits exist.
///
/// # Errors
/// Returns a [`GitError`] if `HEAD` cannot be inspected.
pub(crate) async fn head_commit_message(repo_path: PathBuf) -> Result<Option<String>, GitError> {
    spawn_blocking(move || head_commit_message_sync(&repo_path)).await?
}

/// Deletes a git branch.
///
/// Uses -D to force deletion even if not merged.
///
/// # Arguments
/// * `repo_path` - Path to the git repository root
/// * `branch_name` - Name of the branch to delete
///
/// # Returns
/// Ok(()) on success.
///
/// # Errors
/// Returns a [`GitError`] if the branch delete command fails or exceeds its
/// runtime bound.
pub(crate) async fn delete_branch(repo_path: PathBuf, branch_name: String) -> Result<(), GitError> {
    run_git_command(
        repo_path,
        vec!["branch".to_string(), "-D".to_string(), branch_name],
        "Git branch deletion failed".to_string(),
    )
    .await?;

    Ok(())
}

/// Returns the output of `git diff` for the given repository path, showing
/// all changes (committed and uncommitted) relative to the base branch.
///
/// Copies the repository index into a temporary index and uses
/// `git add --intent-to-add` there to make untracked files visible, then
/// finds the merge-base between `HEAD` and `base_branch` to diff against the
/// fork point. To avoid re-showing squash-merged/cherry-picked session commits
/// on non-rebased branches, this also checks `git cherry` and, when applicable,
/// diffs from the last leading commit already applied to `base_branch`.
/// The real repository index is never modified.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `base_branch` - Branch to diff against (e.g., `main`)
///
/// # Returns
/// The diff output as a string.
///
/// # Errors
/// Returns a [`GitError`] if preparing the temporary index or generating the
/// diff fails.
pub(crate) async fn diff(repo_path: PathBuf, base_branch: String) -> Result<String, GitError> {
    diff_output(repo_path, base_branch, false).await
}

/// Returns repository-relative changed paths using the same isolated index and
/// fork-point semantics as [`diff`].
pub(crate) async fn diff_changed_files(
    repo_path: PathBuf,
    base_branch: String,
) -> Result<Vec<String>, GitError> {
    let output = diff_output(repo_path, base_branch, true).await?;

    Ok(output
        .lines()
        .map(str::trim)
        .filter(|path| !path.is_empty())
        .map(str::to_string)
        .collect())
}

/// Generates either a patch or name-only output without mutating the real
/// repository index.
async fn diff_output(
    repo_path: PathBuf,
    base_branch: String,
    name_only: bool,
) -> Result<String, GitError> {
    spawn_blocking(move || -> Result<String, GitError> {
        let index_path = run_git_command_sync(
            &repo_path,
            &["rev-parse", "--git-path", "index"],
            "Git index path resolution failed",
        )?;
        let index_path = PathBuf::from(index_path.trim());
        let index_path = if index_path.is_absolute() {
            index_path
        } else {
            repo_path.join(index_path)
        };
        let temporary_index = copy_git_index_to_temp(&index_path)?;

        run_git_command_with_index_sync(
            &repo_path,
            &["add", "-A", "--intent-to-add"],
            &temporary_index,
            "Git add --intent-to-add failed",
        )?;

        let merge_base_output =
            run_git_command_output_sync(&repo_path, &["merge-base", "HEAD", &base_branch])?;

        let diff_target = if merge_base_output.status.success() {
            resolve_diff_target(
                &repo_path,
                &base_branch,
                String::from_utf8_lossy(&merge_base_output.stdout).trim(),
            )?
        } else {
            base_branch
        };

        let args = if name_only {
            vec!["diff", "--name-only", diff_target.as_str()]
        } else {
            vec!["diff", diff_target.as_str()]
        };

        run_git_command_with_index_sync(&repo_path, &args, &temporary_index, "Git diff failed")
    })
    .await?
}

/// Reads one repository-relative worktree file with a fixed memory bound.
///
/// The path must contain only normal relative components. Canonical path
/// validation also rejects symlinks that resolve outside `repo_path`.
///
/// # Errors
/// Returns a [`GitError`] when the path is unsafe, repository path resolution
/// fails, or the selected file cannot be read.
pub(crate) async fn read_worktree_file(
    repo_path: PathBuf,
    relative_path: String,
) -> Result<WorktreeFileContent, GitError> {
    spawn_blocking(move || read_worktree_file_sync(&repo_path, &relative_path)).await?
}

/// Performs the bounded worktree read on a blocking worker thread.
fn read_worktree_file_sync(
    repo_path: &Path,
    relative_path: &str,
) -> Result<WorktreeFileContent, GitError> {
    let relative_file_path = Path::new(relative_path);
    if relative_path.is_empty()
        || relative_file_path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(GitError::OutputParse(format!(
            "Unsafe worktree file path: {relative_path}"
        )));
    }

    let canonical_repo_path = std::fs::canonicalize(repo_path)?;
    let candidate_path = repo_path.join(relative_file_path);
    let canonical_file_path = match std::fs::canonicalize(candidate_path) {
        Ok(path) => path,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(WorktreeFileContent::Missing);
        }
        Err(error) => return Err(error.into()),
    };
    if !canonical_file_path.starts_with(canonical_repo_path) {
        return Err(GitError::OutputParse(format!(
            "Worktree file resolves outside repository: {relative_path}"
        )));
    }

    let file = std::fs::File::open(canonical_file_path)?;
    let mut bytes = Vec::with_capacity(MAX_WORKTREE_FILE_BYTE_COUNT.min(8192));
    file.take((MAX_WORKTREE_FILE_BYTE_COUNT as u64).saturating_add(1))
        .read_to_end(&mut bytes)?;

    Ok(worktree_file_content(bytes))
}

/// Classifies bytes read through the bounded worktree-file reader.
fn worktree_file_content(bytes: Vec<u8>) -> WorktreeFileContent {
    if bytes.len() > MAX_WORKTREE_FILE_BYTE_COUNT {
        return WorktreeFileContent::TooLarge;
    }

    match String::from_utf8(bytes) {
        Ok(content) => WorktreeFileContent::Text(content),
        Err(_) => WorktreeFileContent::Binary,
    }
}

/// Copies one repository index beside its source and returns the temporary
/// path used by isolated read-only diff commands.
fn copy_git_index_to_temp(index_path: &Path) -> Result<tempfile::TempPath, GitError> {
    let index_parent = index_path.parent().ok_or_else(|| {
        GitError::OutputParse(format!(
            "Git index path has no parent: {}",
            index_path.display()
        ))
    })?;
    let temporary_index =
        tempfile::NamedTempFile::new_in(index_parent).map_err(|error| GitError::CommandFailed {
            command: "create temporary git index".to_string(),
            stderr: error.to_string(),
        })?;
    std::fs::copy(index_path, temporary_index.path()).map_err(|error| GitError::CommandFailed {
        command: "copy git index".to_string(),
        stderr: error.to_string(),
    })?;

    Ok(temporary_index.into_temp_path())
}

/// Runs one git command against a temporary index without touching the real
/// index.
fn run_git_command_with_index_sync(
    repo_path: &Path,
    args: &[&str],
    index_path: &Path,
    error_context: &str,
) -> Result<String, GitError> {
    let output = run_git_command_output_with_env_sync(
        repo_path,
        args,
        &[("GIT_INDEX_FILE", index_path.as_os_str())],
    )?;
    if !output.status.success() {
        return Err(GitError::CommandFailed {
            command: format!("git {}", args.join(" ")),
            stderr: format!(
                "{error_context}: {}",
                command_output_detail(&output.stdout, &output.stderr)
            ),
        });
    }

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

/// Returns whether a repository or worktree has no uncommitted changes.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// `true` when `git status --porcelain` is empty, `false` otherwise.
///
/// # Errors
/// Returns a [`GitError`] if `git status --porcelain` cannot be executed.
pub(crate) async fn is_worktree_clean(repo_path: PathBuf) -> Result<bool, GitError> {
    let status_output = worktree_status(repo_path).await?;

    Ok(status_output.trim().is_empty())
}

/// Returns a stable porcelain status snapshot for a repository or worktree.
///
/// The snapshot includes untracked files so cleanup and review workflows can
/// detect all local filesystem changes in the worktree.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// Raw `git status --porcelain=v1 --untracked-files=all` stdout.
///
/// # Errors
/// Returns a [`GitError`] if the status command cannot be executed.
pub(crate) async fn worktree_status(repo_path: PathBuf) -> Result<String, GitError> {
    run_git_command(
        repo_path,
        vec![
            "status".to_string(),
            "--porcelain=v1".to_string(),
            "--untracked-files=all".to_string(),
        ],
        "Git status --porcelain=v1 failed".to_string(),
    )
    .await
}

/// Returns a stable porcelain status snapshot for tracked worktree files only.
///
/// This omits untracked files so session isolation checks can ignore unrelated
/// editor or build artifacts while still catching modifications, deletions, and
/// staged changes to tracked files in the main checkout.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// Raw `git status --porcelain=v1 --untracked-files=no` stdout.
///
/// # Errors
/// Returns a [`GitError`] if the status command cannot be executed.
pub(crate) async fn tracked_worktree_status(repo_path: PathBuf) -> Result<String, GitError> {
    run_git_command(
        repo_path,
        vec![
            "status".to_string(),
            "--porcelain=v1".to_string(),
            "--untracked-files=no".to_string(),
        ],
        "Git tracked status --porcelain=v1 failed".to_string(),
    )
    .await
}

/// Runs `git pull --rebase` and returns conflict outcome when applicable.
///
/// When an upstream branch can be resolved, this uses an explicit
/// `git pull --rebase <remote> <branch>` target to avoid ambiguous rebase
/// failures caused by multiple configured merge branches.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// A [`PullRebaseResult`] describing whether pull/rebase completed or stopped
/// on conflicts.
///
/// # Errors
/// Returns a [`GitError`] for non-conflict pull/rebase failures.
pub(crate) async fn pull_rebase(repo_path: PathBuf) -> Result<PullRebaseResult, GitError> {
    let command_runner = ProcessAsyncGitCommandRunner;

    pull_rebase_with_runner(repo_path, &command_runner, GIT_INDEX_LOCK_RETRY_DELAY).await
}

/// Runs pull/rebase through an injected asynchronous command boundary.
async fn pull_rebase_with_runner(
    repo_path: PathBuf,
    command_runner: &dyn AsyncGitCommandRunner,
    retry_delay: Duration,
) -> Result<PullRebaseResult, GitError> {
    let pull_arguments = pull_rebase_arguments(&repo_path, command_runner).await?;
    let command = AsyncGitCommand::new(repo_path, pull_arguments).with_environment(vec![
        ("GIT_EDITOR".to_string(), ":".to_string()),
        ("GIT_SEQUENCE_EDITOR".to_string(), ":".to_string()),
    ]);
    let output =
        run_async_git_command_with_index_lock_retry(command, command_runner, retry_delay).await?;

    if output.success() {
        return Ok(PullRebaseResult::Completed);
    }

    let detail = command_output_detail(&output.stdout, &output.stderr);
    if is_rebase_conflict(&detail) {
        return Ok(PullRebaseResult::Conflict { detail });
    }

    Err(GitError::CommandFailed {
        command: "git pull --rebase".to_string(),
        stderr: detail,
    })
}

/// Builds pull arguments that target a single upstream branch when available.
///
/// Resolves an explicit `<remote> <branch>` pull target for both remote and
/// local upstreams so git does not need to infer one from branch config.
async fn pull_rebase_arguments(
    repo_path: &Path,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<Vec<String>, GitError> {
    let upstream_reference = primary_upstream_reference(repo_path, command_runner).await?;

    if let Some((remote_name, branch_name)) = upstream_reference.split_once('/') {
        return Ok(vec![
            "pull".to_string(),
            "--rebase".to_string(),
            remote_name.to_string(),
            branch_name.to_string(),
        ]);
    }

    let remote_name = current_branch_remote_name(repo_path, command_runner)
        .await?
        .ok_or_else(|| {
            GitError::OutputParse(
                "Failed to resolve current branch remote: not configured".to_string(),
            )
        })?;

    Ok(vec![
        "pull".to_string(),
        "--rebase".to_string(),
        remote_name,
        upstream_reference,
    ])
}

/// Returns the first upstream reference reported for `HEAD`.
///
/// Git can return multiple lines when multiple merge targets are configured.
/// Pulling with rebase needs one concrete target, so this selects the first
/// non-empty line.
async fn primary_upstream_reference(
    repo_path: &Path,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<String, GitError> {
    let upstream_reference = upstream_reference_name(repo_path, command_runner).await?;
    let Some(primary_reference) = upstream_reference
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
    else {
        return Err(GitError::OutputParse(
            "Failed to resolve upstream branch: empty output".to_string(),
        ));
    };

    Ok(primary_reference.to_string())
}

/// Returns the full upstream reference for `HEAD` (for example, `origin/main`).
async fn upstream_reference_name(
    repo_path: &Path,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<String, GitError> {
    let upstream_reference = run_git_command_with_runner(
        AsyncGitCommand::new(
            repo_path.to_path_buf(),
            vec![
                "rev-parse".to_string(),
                "--abbrev-ref".to_string(),
                "--symbolic-full-name".to_string(),
                "@{u}".to_string(),
            ],
        ),
        "Failed to resolve upstream branch",
        command_runner,
    )
    .await?;
    let upstream_reference = upstream_reference.trim().to_string();
    if upstream_reference.is_empty() {
        return Err(GitError::OutputParse(
            "Failed to resolve upstream branch: empty output".to_string(),
        ));
    }

    Ok(upstream_reference)
}

/// Returns the configured remote name for the current local branch.
///
/// This is used when the upstream short name omits a remote prefix (for
/// example, `main` with `branch.<name>.remote=.`).
async fn current_branch_remote_name(
    repo_path: &Path,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<Option<String>, GitError> {
    let current_branch_name = current_branch_name(repo_path, command_runner).await?;
    let remote_config_key = format!("branch.{current_branch_name}.remote");
    let output = command_runner
        .run(AsyncGitCommand::new(
            repo_path.to_path_buf(),
            vec![
                "config".to_string(),
                "--get".to_string(),
                remote_config_key.clone(),
            ],
        ))
        .await?;

    parse_current_branch_remote_output(&output, &remote_config_key)
}

/// Parses `git config --get` output for one current-branch remote.
fn parse_current_branch_remote_output(
    output: &AsyncGitCommandOutput,
    remote_config_key: &str,
) -> Result<Option<String>, GitError> {
    if output.exit_code == Some(1) {
        return Ok(None);
    }
    if !output.success() {
        let detail = command_output_detail(&output.stdout, &output.stderr);

        return Err(GitError::CommandFailed {
            command: format!("git config --get {remote_config_key}"),
            stderr: format!(
                "Failed to resolve current branch remote `{remote_config_key}`: {detail}"
            ),
        });
    }

    let remote_name = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if remote_name.is_empty() {
        return Err(GitError::OutputParse(format!(
            "Failed to resolve current branch remote `{remote_config_key}`: empty output"
        )));
    }

    Ok(Some(remote_name))
}

/// Returns the current local branch name for `HEAD`.
async fn current_branch_name(
    repo_path: &Path,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<String, GitError> {
    let branch_name = run_git_command_with_runner(
        AsyncGitCommand::new(
            repo_path.to_path_buf(),
            vec![
                "rev-parse".to_string(),
                "--abbrev-ref".to_string(),
                "HEAD".to_string(),
            ],
        ),
        "Failed to resolve current branch name",
        command_runner,
    )
    .await?;
    let branch_name = branch_name.trim().to_string();
    if branch_name.is_empty() {
        return Err(GitError::OutputParse(
            "Failed to resolve current branch name: empty output".to_string(),
        ));
    }

    if branch_name == "HEAD" {
        return Err(GitError::OutputParse(
            "Failed to resolve current branch name: detached HEAD".to_string(),
        ));
    }

    Ok(branch_name)
}

/// Runs one asynchronous git command and retries transient index lock
/// contention without blocking a Tokio worker.
async fn run_async_git_command_with_index_lock_retry(
    command: AsyncGitCommand,
    command_runner: &dyn AsyncGitCommandRunner,
    retry_delay: Duration,
) -> Result<AsyncGitCommandOutput, GitError> {
    let mut attempt_count = 0;
    loop {
        attempt_count += 1;
        let output = command_runner.run(command.clone()).await?;
        if output.success() {
            return Ok(output);
        }

        let detail = command_output_detail(&output.stdout, &output.stderr);
        let is_last_attempt = attempt_count == GIT_INDEX_LOCK_RETRY_ATTEMPTS;
        if !is_git_index_lock_error(&detail) || is_last_attempt {
            return Ok(output);
        }

        time::sleep(retry_delay).await;
    }
}

/// Pushes the current branch to its upstream remote with
/// `--force-with-lease`.
///
/// Falls back to `git push --force-with-lease --set-upstream origin HEAD`
/// when no upstream branch is configured, then returns the resolved upstream
/// reference.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// The upstream reference on success.
///
/// # Errors
/// Returns a [`GitError`] if `git push` fails or upstream tracking cannot be
/// resolved afterwards.
pub(crate) async fn push_current_branch(repo_path: PathBuf) -> Result<String, GitError> {
    let command_runner = ProcessAsyncGitCommandRunner;

    push_current_branch_with_runner(repo_path, &command_runner).await
}

/// Pushes the current branch through an injected asynchronous command
/// boundary.
async fn push_current_branch_with_runner(
    repo_path: PathBuf,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<String, GitError> {
    let push_command = AsyncGitCommand::new(
        repo_path.clone(),
        vec!["push".to_string(), "--force-with-lease".to_string()],
    );
    let push_output = command_runner.run(push_command).await?;

    if push_output.success() {
        return primary_upstream_reference(&repo_path, command_runner).await;
    }

    let push_detail = command_output_detail(&push_output.stdout, &push_output.stderr);
    if !is_no_upstream_error(&push_detail) {
        return Err(GitError::CommandFailed {
            command: "git push --force-with-lease".to_string(),
            stderr: push_detail,
        });
    }

    let remote_name = current_branch_remote_name(&repo_path, command_runner)
        .await?
        .unwrap_or_else(|| "origin".to_string());
    run_git_command_with_runner(
        AsyncGitCommand::new(
            repo_path.clone(),
            vec![
                "push".to_string(),
                "--force-with-lease".to_string(),
                "--set-upstream".to_string(),
                remote_name,
                "HEAD".to_string(),
            ],
        ),
        "Git push failed",
        command_runner,
    )
    .await?;

    primary_upstream_reference(&repo_path, command_runner).await
}

/// Checks whether a branch already exists on the remote.
///
/// Resolves the remote name from the current branch config, falling back
/// to `origin`, then runs `git ls-remote --heads <remote> <branch>`.
/// Returns `true` when the remote reports at least one matching ref.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `remote_branch_name` - Branch name to look up on the remote
///
/// # Errors
/// Returns a [`GitError`] if the `git ls-remote` command fails.
pub(crate) async fn remote_branch_exists(
    repo_path: PathBuf,
    remote_branch_name: String,
) -> Result<bool, GitError> {
    let command_runner = ProcessAsyncGitCommandRunner;

    remote_branch_exists_with_runner(repo_path, remote_branch_name, &command_runner).await
}

/// Checks a remote branch through an injected asynchronous command boundary.
async fn remote_branch_exists_with_runner(
    repo_path: PathBuf,
    remote_branch_name: String,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<bool, GitError> {
    let remote_name = current_branch_remote_name(&repo_path, command_runner)
        .await?
        .unwrap_or_else(|| "origin".to_string());
    let arguments = vec![
        "ls-remote".to_string(),
        "--heads".to_string(),
        remote_name,
        remote_branch_name,
    ];
    let stdout = run_git_command_with_runner(
        AsyncGitCommand::new(repo_path, arguments),
        "Git ls-remote failed",
        command_runner,
    )
    .await?;

    Ok(!stdout.trim().is_empty())
}

/// Pushes the current branch to one explicit remote branch name with
/// `--force-with-lease` and returns the resulting upstream reference.
///
/// When the current branch already tracks a remote, that remote name is
/// reused. Otherwise this falls back to `origin`.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `remote_branch_name` - Target branch name to create or update on the
///   remote
///
/// # Returns
/// The upstream reference on success, for example `origin/feature/review`.
///
/// # Errors
/// Returns a [`GitError`] if `git push` fails.
pub(crate) async fn push_current_branch_to_remote_branch(
    repo_path: PathBuf,
    remote_branch_name: String,
) -> Result<String, GitError> {
    let command_runner = ProcessAsyncGitCommandRunner;

    push_current_branch_to_remote_branch_with_runner(repo_path, remote_branch_name, &command_runner)
        .await
}

/// Pushes one explicit branch through an injected asynchronous command
/// boundary.
async fn push_current_branch_to_remote_branch_with_runner(
    repo_path: PathBuf,
    remote_branch_name: String,
    command_runner: &dyn AsyncGitCommandRunner,
) -> Result<String, GitError> {
    let remote_name = current_branch_remote_name(&repo_path, command_runner)
        .await?
        .unwrap_or_else(|| "origin".to_string());
    let push_refspec = format!("HEAD:{remote_branch_name}");
    let arguments = vec![
        "push".to_string(),
        "--force-with-lease".to_string(),
        "--set-upstream".to_string(),
        remote_name.clone(),
        push_refspec,
    ];
    run_git_command_with_runner(
        AsyncGitCommand::new(repo_path, arguments),
        "Git push failed",
        command_runner,
    )
    .await?;

    Ok(format!("{remote_name}/{remote_branch_name}"))
}

/// Returns the current upstream reference for `HEAD`.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
///
/// # Returns
/// The configured upstream reference, for example `origin/main`.
///
/// # Errors
/// Returns a [`GitError`] when upstream tracking information cannot be
/// resolved.
pub(crate) async fn current_upstream_reference(repo_path: PathBuf) -> Result<String, GitError> {
    let command_runner = ProcessAsyncGitCommandRunner;

    primary_upstream_reference(&repo_path, &command_runner).await
}

/// Fetches from the configured remote.
///
/// # Arguments
/// * `repo_path` - Path to the git repository root
///
/// # Returns
/// Ok(()) on success.
///
/// # Errors
/// Returns a [`GitError`] if `git fetch` cannot be executed successfully.
pub(crate) async fn fetch_remote(repo_path: PathBuf) -> Result<(), GitError> {
    run_git_command(
        repo_path,
        vec!["fetch".to_string()],
        "Git fetch failed".to_string(),
    )
    .await?;

    Ok(())
}

/// Returns the number of commits ahead and behind the upstream branch.
///
/// # Arguments
/// * `repo_path` - Path to the git repository root
///
/// # Returns
/// Ok((ahead, behind)) on success.
///
/// # Errors
/// Returns a [`GitError`] if `git rev-list` fails or returns unexpected
/// output.
pub(crate) async fn get_ahead_behind(repo_path: PathBuf) -> Result<(u32, u32), GitError> {
    get_ref_ahead_behind(repo_path, "HEAD".to_string(), "@{u}".to_string()).await
}

/// Returns the number of commits `left_ref` is ahead of and behind `right_ref`.
///
/// The returned tuple is `(ahead, behind)`, where `ahead` counts commits
/// reachable from `left_ref` but not `right_ref`, and `behind` counts commits
/// reachable from `right_ref` but not `left_ref`.
///
/// # Errors
/// Returns a [`GitError`] if `git rev-list` fails or returns unexpected
/// output.
pub(crate) async fn get_ref_ahead_behind(
    repo_path: PathBuf,
    left_ref: String,
    right_ref: String,
) -> Result<(u32, u32), GitError> {
    let rev_list_output = run_git_command(
        repo_path,
        vec![
            "rev-list".to_string(),
            "--left-right".to_string(),
            "--count".to_string(),
            format!("{left_ref}...{right_ref}"),
        ],
        "Git rev-list failed".to_string(),
    )
    .await?;

    parse_ahead_behind_counts(&rev_list_output)
}

/// Parses one `git rev-list --left-right --count` output into `(ahead,
/// behind)`.
fn parse_ahead_behind_counts(rev_list_output: &str) -> Result<(u32, u32), GitError> {
    let parts: Vec<&str> = rev_list_output.split_whitespace().collect();
    if parts.len() >= 2 {
        let ahead = parts[0].parse().unwrap_or(0);
        let behind = parts[1].parse().unwrap_or(0);

        return Ok((ahead, behind));
    }

    Err(GitError::OutputParse(
        "Unexpected output format from git rev-list".to_string(),
    ))
}

/// Returns ahead/behind snapshots for every local branch in `repo_path`.
///
/// The returned map is keyed by local branch name. Branches without an
/// upstream, with a gone upstream, or without ahead/behind markers map to
/// `None`.
///
/// # Errors
/// Returns a [`GitError`] if `git for-each-ref` fails.
pub(crate) async fn branch_tracking_statuses(
    repo_path: PathBuf,
) -> Result<BranchTrackingMap, GitError> {
    let git_output = run_git_command(
        repo_path,
        vec![
            "for-each-ref".to_string(),
            "--format=%(refname:short)\t%(upstream:short)\t%(upstream:track,nobracket)".to_string(),
            "refs/heads".to_string(),
        ],
        "Git for-each-ref failed".to_string(),
    )
    .await?;

    Ok(parse_branch_tracking_statuses(&git_output))
}

/// Returns upstream commit subjects that are not yet in local `HEAD`.
///
/// The returned order is oldest to newest to match pull application order.
///
/// # Arguments
/// * `repo_path` - Path to the git repository root
///
/// # Errors
/// Returns a [`GitError`] when `git log` fails or upstream tracking refs are
/// unavailable.
pub(crate) async fn list_upstream_commit_titles(
    repo_path: PathBuf,
) -> Result<Vec<String>, GitError> {
    let git_output = run_git_command(
        repo_path,
        vec![
            "log".to_string(),
            "--reverse".to_string(),
            "--pretty=%s".to_string(),
            "HEAD..@{u}".to_string(),
        ],
        "Git log failed".to_string(),
    )
    .await?;

    Ok(parse_commit_titles(&git_output))
}

/// Returns local commit subjects that are not yet present in upstream.
///
/// The returned order is oldest to newest to match push application order.
///
/// # Arguments
/// * `repo_path` - Path to the git repository root
///
/// # Errors
/// Returns a [`GitError`] when `git log` fails or upstream tracking refs are
/// unavailable.
pub(crate) async fn list_local_commit_titles(repo_path: PathBuf) -> Result<Vec<String>, GitError> {
    let git_output = run_git_command(
        repo_path,
        vec![
            "log".to_string(),
            "--reverse".to_string(),
            "--pretty=%s".to_string(),
            "@{u}..HEAD".to_string(),
        ],
        "Git log failed".to_string(),
    )
    .await?;

    Ok(parse_commit_titles(&git_output))
}

/// Returns whether `HEAD` contains commits that are not reachable from
/// `base_branch`.
///
/// # Errors
/// Returns a [`GitError`] if commit ancestry cannot be queried.
pub(crate) async fn has_commits_since(
    repo_path: PathBuf,
    base_branch: String,
) -> Result<bool, GitError> {
    spawn_blocking(move || -> Result<bool, GitError> {
        let rev_list_output = run_git_command_sync(
            &repo_path,
            &["rev-list", "--count", &format!("{base_branch}..HEAD")],
            "Failed to count commits since base branch",
        )?;
        let commit_count = rev_list_output.trim().parse::<u32>().map_err(|error| {
            GitError::OutputParse(format!(
                "Failed to parse commit count since base branch `{base_branch}`: {error}"
            ))
        })?;

        Ok(commit_count > 0)
    })
    .await?
}

/// Parses newline-delimited commit subjects from `git log` output.
fn parse_commit_titles(output: &str) -> Vec<String> {
    output
        .lines()
        .map(str::trim)
        .filter(|title| !title.is_empty())
        .map(ToString::to_string)
        .collect()
}

/// Parses repo-wide branch tracking information from `git for-each-ref`.
fn parse_branch_tracking_statuses(output: &str) -> BranchTrackingMap {
    let mut branch_tracking_statuses = HashMap::new();

    for line in output
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        let mut parts = line.splitn(3, '\t');
        let Some(branch_name) = parts
            .next()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        else {
            continue;
        };
        let upstream_ref = parts.next().map(str::trim).unwrap_or_default();
        let track = parts.next().map(str::trim).unwrap_or_default();

        let status = if upstream_ref.is_empty() {
            None
        } else {
            parse_branch_tracking_counts(track)
        };
        branch_tracking_statuses.insert(branch_name.to_string(), status);
    }

    branch_tracking_statuses
}

/// Parses one `%(upstream:track,nobracket)` marker into ahead/behind counts.
fn parse_branch_tracking_counts(track: &str) -> Option<(u32, u32)> {
    let normalized_track = track.trim();
    if normalized_track.is_empty() || normalized_track == "gone" {
        return None;
    }

    let mut ahead = 0;
    let mut behind = 0;

    for part in normalized_track.split(',').map(str::trim) {
        if let Some(count) = part.strip_prefix("ahead ") {
            ahead = count.parse().ok()?;
        } else if let Some(count) = part.strip_prefix("behind ") {
            behind = count.parse().ok()?;
        }
    }

    Some((ahead, behind))
}

/// Resolves the commit/tree to use as the `git diff` "before" side.
///
/// Starts from the merge-base fallback and, when `git cherry` reports leading
/// commits already applied to `base_branch`, advances the baseline to the last
/// such commit so squash-merged session changes are not shown again.
fn resolve_diff_target(
    repo_path: &Path,
    base_branch: &str,
    merge_base: &str,
) -> Result<String, GitError> {
    let cherry_output = run_git_command_output_sync(repo_path, &["cherry", base_branch, "HEAD"])?;
    if !cherry_output.status.success() {
        return Ok(merge_base.to_string());
    }

    let cherry_stdout = String::from_utf8_lossy(&cherry_output.stdout);
    let Some(last_leading_applied_commit) = last_leading_applied_commit(&cherry_stdout) else {
        return Ok(merge_base.to_string());
    };

    Ok(last_leading_applied_commit.to_string())
}

/// Returns the last leading commit from `git cherry` marked as already applied.
///
/// `git cherry` prefixes commits with `-` when an equivalent patch exists in
/// the upstream branch and `+` when it does not. This helper only consumes the
/// initial contiguous `-` block and stops at the first `+` to avoid dropping
/// non-merged changes.
fn last_leading_applied_commit(cherry_output: &str) -> Option<&str> {
    let mut last_applied_commit = None;

    for line in cherry_output.lines() {
        let trimmed_line = line.trim();
        if trimmed_line.is_empty() {
            continue;
        }

        let mut parts = trimmed_line.split_whitespace();
        let marker = parts.next()?;
        let commit_hash = parts.next()?;

        if marker == "-" {
            last_applied_commit = Some(commit_hash);

            continue;
        }

        if marker == "+" {
            break;
        }

        break;
    }

    last_applied_commit
}

/// Stages all changes and commits or amends with retry behavior for hook
/// rewrites.
///
/// If an amend would make `HEAD` empty, the staged tree has reverted the
/// session commit back to its parent. In that case the helper drops the now
/// empty session commit and reports the standard no-changes sentinel so the
/// app can skip model-assisted commit recovery.
async fn commit_all_with_retry(
    repo_path: PathBuf,
    commit_message: String,
    message_strategy: SingleCommitMessageStrategy,
    no_verify: bool,
    amend_existing_commit: bool,
) -> Result<(), GitError> {
    spawn_blocking(move || {
        stage_all_sync(&repo_path)?;

        for _ in 0..COMMIT_ALL_HOOK_RETRY_ATTEMPTS {
            let output = run_commit_command(
                &repo_path,
                &commit_message,
                message_strategy,
                no_verify,
                amend_existing_commit,
            )?;

            if output.status.success() {
                return Ok(());
            }

            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            if is_nothing_to_commit_output(&stdout, &stderr) {
                return Err(nothing_to_commit_error());
            }

            if amend_existing_commit && is_empty_amend_output(&stdout, &stderr) {
                reset_empty_amend_sync(&repo_path)?;

                return Err(nothing_to_commit_error());
            }

            if is_hook_modified_error(&stdout, &stderr) {
                stage_all_sync(&repo_path)?;

                continue;
            }

            let detail = command_output_detail(&output.stdout, &output.stderr);

            return Err(GitError::CommandFailed {
                command: "git commit".to_string(),
                stderr: detail,
            });
        }

        Err(GitError::CommandFailed {
            command: "git commit".to_string(),
            stderr: format!(
                "Failed to commit: commit hooks kept modifying files after \
                 {COMMIT_ALL_HOOK_RETRY_ATTEMPTS} attempts"
            ),
        })
    })
    .await?
}

/// Ensures repositories declaring pre-commit validation have an executable
/// hook.
fn ensure_pre_commit_hook_ready(repo_path: &Path) -> Result<(), GitError> {
    let Some(config_file) = PRE_COMMIT_CONFIG_FILES
        .iter()
        .find(|config_file| repo_path.join(config_file).is_file())
    else {
        return Ok(());
    };
    let hook_path = resolve_pre_commit_hook_path(repo_path)?;

    if is_executable_hook(&hook_path) {
        return Ok(());
    }

    Err(GitError::PreCommitHookMissing {
        config_file: (*config_file).to_string(),
    })
}

/// Resolves the pre-commit hook using `core.hooksPath` or Git's default path.
fn resolve_pre_commit_hook_path(repo_path: &Path) -> Result<PathBuf, GitError> {
    let hooks_path_output =
        run_git_command_output_sync(repo_path, &["config", "--path", "--get", "core.hooksPath"])?;
    let hooks_path = if hooks_path_output.status.success() {
        PathBuf::from(String::from_utf8_lossy(&hooks_path_output.stdout).trim())
    } else if hooks_path_output.status.code() == Some(1) {
        let default_hook_path = run_git_command_sync(
            repo_path,
            &["rev-parse", "--git-path", "hooks/pre-commit"],
            "Failed to resolve Git pre-commit hook path",
        )?;

        return Ok(resolve_repo_path(
            repo_path,
            PathBuf::from(default_hook_path.trim()),
        ));
    } else {
        return Err(GitError::CommandFailed {
            command: "git config --path --get core.hooksPath".to_string(),
            stderr: command_output_detail(&hooks_path_output.stdout, &hooks_path_output.stderr),
        });
    };

    Ok(resolve_repo_path(repo_path, hooks_path).join("pre-commit"))
}

fn resolve_repo_path(repo_path: &Path, path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        return path;
    }

    repo_path.join(path)
}

#[cfg(unix)]
fn is_executable_hook(hook_path: &Path) -> bool {
    hook_path.is_file() && rustix_fs::access(hook_path, Access::EXEC_OK).is_ok()
}

#[cfg(not(unix))]
fn is_executable_hook(hook_path: &Path) -> bool {
    hook_path.is_file()
}

/// Returns the canonical git no-changes error used by app auto-commit flows.
fn nothing_to_commit_error() -> GitError {
    GitError::CommandFailed {
        command: "git commit".to_string(),
        stderr: "Nothing to commit: no changes detected".to_string(),
    }
}

/// Returns whether commit output reports that there was no staged work to
/// commit.
fn is_nothing_to_commit_output(stdout: &str, stderr: &str) -> bool {
    let combined = format!("{stdout}\n{stderr}").to_ascii_lowercase();

    combined.contains("nothing to commit")
}

/// Returns whether commit output reports that amending `HEAD` would remove the
/// session commit entirely.
fn is_empty_amend_output(stdout: &str, stderr: &str) -> bool {
    let combined = format!("{stdout}\n{stderr}").to_ascii_lowercase();
    let normalized = combined.split_whitespace().collect::<Vec<_>>().join(" ");

    normalized.contains("would make it empty") && normalized.contains("allow-empty")
}

/// Drops an amended session commit whose resulting tree would match its
/// parent, leaving the worktree at the reverted state.
fn reset_empty_amend_sync(repo_path: &Path) -> Result<(), GitError> {
    run_git_command_sync(
        repo_path,
        &["reset", "HEAD^"],
        "Git reset after empty amend failed",
    )?;

    Ok(())
}

/// Stages all changed files in the repository.
///
/// Uses shared git retry behavior for transient `index.lock` contention.
fn stage_all_sync(repo_path: &Path) -> Result<(), GitError> {
    let output = run_git_command_with_index_lock_retry(repo_path, &["add", "-A"], &[])?;

    if !output.status.success() {
        let detail = command_output_detail(&output.stdout, &output.stderr);

        return Err(GitError::CommandFailed {
            command: "git add -A".to_string(),
            stderr: format!("Failed to stage changes: {detail}"),
        });
    }

    Ok(())
}

/// Returns the full `HEAD` commit message, or `None` when no commits exist.
fn head_commit_message_sync(repo_path: &Path) -> Result<Option<String>, GitError> {
    if !has_head_commit_sync(repo_path)? {
        return Ok(None);
    }

    let output = run_git_command_sync(
        repo_path,
        &["log", "-1", "--pretty=%B"],
        "Failed to read HEAD commit message",
    )?;

    Ok(Some(output.trim().to_string()))
}

/// Returns whether `HEAD` resolves to an existing commit.
fn has_head_commit_sync(repo_path: &Path) -> Result<bool, GitError> {
    let output = run_git_command_output_sync(repo_path, &["rev-parse", "--verify", "HEAD"])?;

    if output.status.success() {
        return Ok(true);
    }

    let detail = command_output_detail(&output.stdout, &output.stderr);
    let normalized_detail = detail.to_ascii_lowercase();
    if normalized_detail.contains("needed a single revision")
        || normalized_detail.contains("unknown revision")
        || normalized_detail.contains("does not have any commits yet")
    {
        return Ok(false);
    }

    Err(GitError::CommandFailed {
        command: "git rev-parse --verify HEAD".to_string(),
        stderr: detail,
    })
}

/// Runs `git commit` with optional amend and hook settings.
///
/// Uses shared git retry behavior for transient `index.lock` contention.
fn run_commit_command(
    repo_path: &Path,
    commit_message: &str,
    message_strategy: SingleCommitMessageStrategy,
    no_verify: bool,
    amend_existing_commit: bool,
) -> Result<Output, GitError> {
    let mut args = vec!["commit"];
    if amend_existing_commit {
        args.push("--amend");
        match message_strategy {
            SingleCommitMessageStrategy::Replace => {
                args.push("-m");
                args.push(commit_message);
            }
            SingleCommitMessageStrategy::Reuse => {
                args.push("--no-edit");
            }
        }
    } else {
        args.push("-m");
        args.push(commit_message);
    }

    if no_verify {
        args.push("--no-verify");
    }

    run_git_command_with_index_lock_retry(repo_path, &args, &[])
}

/// Returns whether commit output indicates hooks rewrote files.
fn is_hook_modified_error(stdout: &str, stderr: &str) -> bool {
    let combined = format!(
        "{stdout}
{stderr}"
    )
    .to_ascii_lowercase();

    combined.contains("files were modified by this hook")
}

/// Returns whether git push output indicates a missing upstream branch.
pub(super) fn is_no_upstream_error(detail: &str) -> bool {
    let normalized_detail = detail.to_ascii_lowercase();

    normalized_detail.contains("has no upstream branch")
        || normalized_detail.contains("no upstream branch")
        || normalized_detail.contains("set-upstream")
}

#[cfg(test)]
mod tests {
    use std::fs;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::path::Path;
    use std::process::{Command, Output};

    use mockall::Sequence;
    use mockall::predicate::function;
    use tempfile::tempdir;

    use super::*;
    use crate::repo::MockAsyncGitCommandRunner;

    /// Builds captured asynchronous git output for command-runner tests.
    fn async_git_output(
        exit_code: i32,
        stdout: impl Into<Vec<u8>>,
        stderr: impl Into<Vec<u8>>,
    ) -> AsyncGitCommandOutput {
        AsyncGitCommandOutput {
            exit_code: Some(exit_code),
            stderr: stderr.into(),
            stdout: stdout.into(),
        }
    }

    /// Runs `git` in `repo_path` and asserts the command succeeds.
    fn run_git_command(repo_path: &Path, args: &[&str]) {
        let output = git_command_output(repo_path, args);

        assert!(
            output.status.success(),
            "git command {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// Runs `git` in `repo_path` and returns the captured command output.
    fn git_command_output(repo_path: &Path, args: &[&str]) -> Output {
        Command::new("git")
            .args(args)
            .current_dir(repo_path)
            .output()
            .expect("failed to run git command")
    }

    /// Runs `git` in `repo_path`, asserts success, and returns trimmed stdout.
    fn git_command_stdout(repo_path: &Path, args: &[&str]) -> String {
        let output = git_command_output(repo_path, args);

        assert!(
            output.status.success(),
            "git command {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );

        String::from_utf8(output.stdout)
            .expect("git stdout should be valid utf-8")
            .trim()
            .to_string()
    }

    /// Creates a committed repository rooted at `repo_path`.
    fn setup_test_git_repo(repo_path: &Path) {
        run_git_command(repo_path, &["init", "-b", "main"]);
        run_git_command(repo_path, &["config", "user.name", "Test User"]);
        run_git_command(repo_path, &["config", "user.email", "test@example.com"]);
        fs::write(repo_path.join("README.md"), "base\n").expect("failed to write base file");
        run_git_command(repo_path, &["add", "README.md"]);
        run_git_command(repo_path, &["commit", "-m", "Initial commit"]);
    }

    #[tokio::test]
    async fn delete_branch_removes_branch_from_isolated_repository() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(temp_dir.path(), &["branch", "review/topic"]);

        // Act
        delete_branch(temp_dir.path().to_path_buf(), "review/topic".to_string())
            .await
            .expect("branch deletion should succeed");

        // Assert
        let branch_lookup = git_command_output(
            temp_dir.path(),
            &["show-ref", "--verify", "--quiet", "refs/heads/review/topic"],
        );
        assert!(!branch_lookup.status.success());
    }

    #[tokio::test]
    async fn diff_preserves_staged_changes_and_includes_untracked_files() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(temp_dir.path().join("README.md"), "staged change\n")
            .expect("failed to write staged change");
        run_git_command(temp_dir.path(), &["add", "README.md"]);
        fs::write(
            temp_dir.path().join("README.md"),
            "staged change\nunstaged change\n",
        )
        .expect("failed to write unstaged change");
        fs::write(temp_dir.path().join("new.txt"), "untracked change\n")
            .expect("failed to write untracked file");
        let cached_diff_before = git_command_output(temp_dir.path(), &["diff", "--cached"]).stdout;
        let status_before = git_command_output(
            temp_dir.path(),
            &["status", "--porcelain=v1", "--untracked-files=all"],
        )
        .stdout;

        // Act
        let result = diff(temp_dir.path().to_path_buf(), "main".to_string()).await;
        let changed_files =
            diff_changed_files(temp_dir.path().to_path_buf(), "main".to_string()).await;

        // Assert
        let diff_output = result.expect("diff should succeed");
        let cached_diff_after = git_command_output(temp_dir.path(), &["diff", "--cached"]).stdout;
        let status_after = git_command_output(
            temp_dir.path(),
            &["status", "--porcelain=v1", "--untracked-files=all"],
        )
        .stdout;
        assert!(diff_output.contains("staged change"));
        assert!(diff_output.contains("unstaged change"));
        assert!(diff_output.contains("untracked change"));
        assert_eq!(
            changed_files.expect("changed files should load"),
            vec!["README.md".to_string(), "new.txt".to_string()]
        );
        assert_eq!(cached_diff_after, cached_diff_before);
        assert_eq!(status_after, status_before);
    }

    #[tokio::test]
    async fn read_worktree_file_returns_text_for_safe_nested_path() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir(&docs_dir).expect("failed to create docs directory");
        fs::write(docs_dir.join("README.md"), "# Preview\n")
            .expect("failed to write markdown file");

        // Act
        let result =
            read_worktree_file(temp_dir.path().to_path_buf(), "docs/README.md".to_string()).await;

        // Assert
        assert_eq!(
            result.expect("worktree read should succeed"),
            WorktreeFileContent::Text("# Preview\n".to_string())
        );
    }

    #[tokio::test]
    async fn read_worktree_file_classifies_missing_binary_and_oversize_files() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        fs::write(temp_dir.path().join("binary.md"), [0xff, 0xfe])
            .expect("failed to write binary file");
        fs::write(
            temp_dir.path().join("large.md"),
            vec![b'a'; MAX_WORKTREE_FILE_BYTE_COUNT + 1],
        )
        .expect("failed to write oversize file");

        // Act
        let missing =
            read_worktree_file(temp_dir.path().to_path_buf(), "missing.md".to_string()).await;
        let binary =
            read_worktree_file(temp_dir.path().to_path_buf(), "binary.md".to_string()).await;
        let too_large =
            read_worktree_file(temp_dir.path().to_path_buf(), "large.md".to_string()).await;

        // Assert
        assert_eq!(
            missing.expect("missing read should succeed"),
            WorktreeFileContent::Missing
        );
        assert_eq!(
            binary.expect("binary read should succeed"),
            WorktreeFileContent::Binary
        );
        assert_eq!(
            too_large.expect("oversize read should succeed"),
            WorktreeFileContent::TooLarge
        );
    }

    #[tokio::test]
    async fn read_worktree_file_rejects_unsafe_relative_paths() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let absolute_path = temp_dir.path().join("README.md");

        // Act
        let empty = read_worktree_file(temp_dir.path().to_path_buf(), String::new()).await;
        let parent =
            read_worktree_file(temp_dir.path().to_path_buf(), "../README.md".to_string()).await;
        let absolute = read_worktree_file(
            temp_dir.path().to_path_buf(),
            absolute_path.to_string_lossy().into_owned(),
        )
        .await;

        // Assert
        for result in [empty, parent, absolute] {
            assert!(
                matches!(result, Err(GitError::OutputParse(message)) if message.contains("Unsafe worktree file path"))
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_worktree_file_rejects_symlinks_outside_repository() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let outside_dir = tempdir().expect("failed to create outside temp dir");
        let outside_file = outside_dir.path().join("outside.md");
        fs::write(&outside_file, "outside").expect("failed to write outside file");
        std::os::unix::fs::symlink(&outside_file, temp_dir.path().join("link.md"))
            .expect("failed to create outside symlink");

        // Act
        let result = read_worktree_file(temp_dir.path().to_path_buf(), "link.md".to_string()).await;

        // Assert
        assert!(
            matches!(result, Err(GitError::OutputParse(message)) if message.contains("resolves outside repository"))
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_worktree_file_maps_non_missing_path_resolution_errors() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        std::os::unix::fs::symlink("loop.md", temp_dir.path().join("loop.md"))
            .expect("failed to create symlink loop");

        // Act
        let result = read_worktree_file(temp_dir.path().to_path_buf(), "loop.md".to_string()).await;

        // Assert
        assert!(matches!(result, Err(GitError::Io(_))));
    }

    #[test]
    fn copy_git_index_to_temp_maps_path_create_and_copy_failures() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let path_without_parent = Path::new("/");
        let missing_parent_index = temp_dir.path().join("missing-parent").join("index");
        let missing_index = temp_dir.path().join("missing-index");

        // Act
        let parent_error = copy_git_index_to_temp(path_without_parent);
        let create_error = copy_git_index_to_temp(&missing_parent_index);
        let copy_error = copy_git_index_to_temp(&missing_index);

        // Assert
        assert!(matches!(parent_error, Err(GitError::OutputParse(_))));
        assert!(matches!(
            create_error,
            Err(GitError::CommandFailed { ref command, .. })
                if command == "create temporary git index"
        ));
        assert!(matches!(
            copy_error,
            Err(GitError::CommandFailed { ref command, .. }) if command == "copy git index"
        ));
    }

    #[test]
    fn run_git_command_with_index_sync_maps_process_and_command_failures() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let index_path = temp_dir.path().join("index");
        let missing_repo_path = temp_dir.path().join("missing-repository");
        fs::write(&index_path, []).expect("failed to create temporary index");

        // Act
        let process_error = run_git_command_with_index_sync(
            &missing_repo_path,
            &["status"],
            &index_path,
            "Expected process failure",
        );
        let command_error = run_git_command_with_index_sync(
            temp_dir.path(),
            &["definitely-not-a-git-command"],
            &index_path,
            "Expected git failure",
        );

        // Assert
        assert!(matches!(
            process_error,
            Err(GitError::CommandFailed { ref command, .. }) if command == "git status"
        ));
        assert!(matches!(
            command_error,
            Err(GitError::CommandFailed {
                ref command,
                ref stderr,
            }) if command == "git definitely-not-a-git-command"
                && stderr.starts_with("Expected git failure:")
        ));
    }

    #[cfg(unix)]
    fn write_executable_pre_commit_hook(hook_path: &Path) {
        fs::create_dir_all(
            hook_path
                .parent()
                .expect("pre-commit hook should have a parent directory"),
        )
        .expect("failed to create hooks directory");
        fs::write(hook_path, "#!/bin/sh\nexit 0\n").expect("failed to write pre-commit hook");
        let mut permissions = fs::metadata(hook_path)
            .expect("failed to read pre-commit hook metadata")
            .permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(hook_path, permissions)
            .expect("failed to make pre-commit hook executable");
    }

    #[test]
    fn ensure_pre_commit_hook_ready_allows_repositories_without_configuration() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());

        // Act
        let result = ensure_pre_commit_hook_ready(temp_dir.path());

        // Assert
        assert!(result.is_ok());
    }

    #[test]
    fn ensure_pre_commit_hook_ready_rejects_missing_hook() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(
            temp_dir.path().join(".pre-commit-config.yaml"),
            "repos: []\n",
        )
        .expect("failed to write pre-commit configuration");

        // Act
        let result = ensure_pre_commit_hook_ready(temp_dir.path());

        // Assert
        assert!(matches!(
            result,
            Err(GitError::PreCommitHookMissing { ref config_file })
                if config_file == ".pre-commit-config.yaml"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn ensure_pre_commit_hook_ready_accepts_default_executable_hook() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(
            temp_dir.path().join(".pre-commit-config.yaml"),
            "repos: []\n",
        )
        .expect("failed to write pre-commit configuration");
        let hook_path = temp_dir.path().join(git_command_stdout(
            temp_dir.path(),
            &["rev-parse", "--git-path", "hooks/pre-commit"],
        ));
        write_executable_pre_commit_hook(&hook_path);

        // Act
        let result = ensure_pre_commit_hook_ready(temp_dir.path());

        // Assert
        assert!(result.is_ok());
    }

    #[cfg(unix)]
    #[test]
    fn ensure_pre_commit_hook_ready_accepts_custom_executable_hook() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(
            temp_dir.path().join(".pre-commit-config.yaml"),
            "repos: []\n",
        )
        .expect("failed to write pre-commit configuration");
        run_git_command(
            temp_dir.path(),
            &["config", "core.hooksPath", ".custom-hooks"],
        );
        write_executable_pre_commit_hook(&temp_dir.path().join(".custom-hooks").join("pre-commit"));

        // Act
        let result = ensure_pre_commit_hook_ready(temp_dir.path());

        // Assert
        assert!(result.is_ok());
    }

    #[cfg(unix)]
    #[test]
    fn ensure_pre_commit_hook_ready_rejects_hook_inaccessible_to_owner() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(
            temp_dir.path().join(".pre-commit-config.yaml"),
            "repos: []\n",
        )
        .expect("failed to write pre-commit configuration");
        let hook_path = temp_dir.path().join(git_command_stdout(
            temp_dir.path(),
            &["rev-parse", "--git-path", "hooks/pre-commit"],
        ));
        fs::write(&hook_path, "#!/bin/sh\nexit 0\n").expect("failed to write pre-commit hook");
        fs::set_permissions(&hook_path, fs::Permissions::from_mode(0o011))
            .expect("failed to set mismatched execute permissions");

        // Act
        let result = ensure_pre_commit_hook_ready(temp_dir.path());

        // Assert
        assert!(matches!(result, Err(GitError::PreCommitHookMissing { .. })));
    }

    #[tokio::test]
    async fn commit_all_allows_configured_validation_without_hook() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        fs::write(
            temp_dir.path().join(".pre-commit-config.yaml"),
            "repos: []\n",
        )
        .expect("failed to write pre-commit configuration");
        fs::write(temp_dir.path().join("README.md"), "changed\n")
            .expect("failed to write worktree change");

        // Act
        let result = commit_all(
            temp_dir.path().to_path_buf(),
            "Change README".to_string(),
            false,
        )
        .await;

        // Assert
        assert!(result.is_ok());
        assert_eq!(
            git_command_stdout(temp_dir.path(), &["log", "-1", "--pretty=%s"]),
            "Change README"
        );
    }

    #[tokio::test]
    async fn current_branch_name_returns_error_for_detached_head() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(temp_dir.path(), &["checkout", "--detach"]);
        let command_runner = ProcessAsyncGitCommandRunner;

        // Act
        let result = current_branch_name(temp_dir.path(), &command_runner).await;

        // Assert
        let error = result.expect_err("detached HEAD should fail");
        assert!(error.to_string().contains("detached HEAD"));
    }

    #[tokio::test]
    async fn current_branch_remote_name_returns_none_when_remote_is_not_configured() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        let command_runner = ProcessAsyncGitCommandRunner;

        // Act
        let remote_name = current_branch_remote_name(temp_dir.path(), &command_runner)
            .await
            .expect("missing branch remote should not be a command failure");

        // Assert
        assert_eq!(remote_name, None);
    }

    #[tokio::test]
    async fn current_branch_remote_name_returns_configured_non_origin_remote() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(
            temp_dir.path(),
            &["config", "branch.main.remote", "review-remote"],
        );
        let command_runner = ProcessAsyncGitCommandRunner;

        // Act
        let remote_name = current_branch_remote_name(temp_dir.path(), &command_runner)
            .await
            .expect("configured branch remote should resolve");

        // Assert
        assert_eq!(remote_name, Some("review-remote".to_string()));
    }

    #[test]
    fn parse_current_branch_remote_output_preserves_fatal_config_error() {
        // Arrange
        let output = AsyncGitCommandOutput {
            exit_code: Some(128),
            stderr: b"fatal: bad config line".to_vec(),
            stdout: Vec::new(),
        };

        // Act
        let error = parse_current_branch_remote_output(&output, "branch.main.remote")
            .expect_err("malformed config should remain an error");

        // Assert
        assert!(matches!(
            error,
            GitError::CommandFailed { command, stderr }
                if command == "git config --get branch.main.remote"
                    && stderr.contains("Failed to resolve current branch remote")
        ));
    }

    #[tokio::test]
    async fn primary_upstream_reference_uses_first_non_empty_line() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);
        run_git_command(
            temp_dir.path(),
            &[
                "config",
                "--replace-all",
                "branch.main.merge",
                "refs/heads/main",
            ],
        );
        run_git_command(
            temp_dir.path(),
            &["config", "--add", "branch.main.merge", "refs/heads/feature"],
        );
        let command_runner = ProcessAsyncGitCommandRunner;

        // Act
        let upstream_reference = primary_upstream_reference(temp_dir.path(), &command_runner)
            .await
            .expect("failed to resolve upstream");

        // Assert
        assert_eq!(upstream_reference, "origin/main");
    }

    #[tokio::test]
    async fn pull_rebase_retries_index_lock_through_async_runner() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| {
                Box::pin(async { Ok(async_git_output(0, "origin/main\n", Vec::new())) })
            });
        for output in [
            async_git_output(
                128,
                Vec::new(),
                "fatal: Unable to create '.git/index.lock': File exists.",
            ),
            async_git_output(0, Vec::new(), Vec::new()),
        ] {
            command_runner
                .expect_run()
                .with(function(|command: &AsyncGitCommand| {
                    command.arguments == ["pull", "--rebase", "origin", "main"]
                        && command.environment
                            == [
                                ("GIT_EDITOR".to_string(), ":".to_string()),
                                ("GIT_SEQUENCE_EDITOR".to_string(), ":".to_string()),
                            ]
                }))
                .times(1)
                .in_sequence(&mut sequence)
                .return_once(move |_| Box::pin(async move { Ok(output) }));
        }

        // Act
        let result = pull_rebase_with_runner(repo_path, &command_runner, Duration::ZERO).await;

        // Assert
        assert!(matches!(result, Ok(PullRebaseResult::Completed)));
    }

    #[tokio::test]
    async fn pull_rebase_preserves_non_conflict_command_failure() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| {
                Box::pin(async { Ok(async_git_output(0, "origin/main\n", Vec::new())) })
            });
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["pull", "--rebase", "origin", "main"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| {
                Box::pin(async { Ok(async_git_output(128, Vec::new(), "fatal: transport failed")) })
            });

        // Act
        let error = pull_rebase_with_runner(repo_path, &command_runner, Duration::ZERO)
            .await
            .expect_err("non-conflict pull failure should remain an error");

        // Assert
        assert!(matches!(
            error,
            GitError::CommandFailed { command, stderr }
                if command == "git pull --rebase" && stderr == "fatal: transport failed"
        ));
    }

    #[tokio::test]
    async fn pull_rebase_rejects_local_upstream_without_configured_remote() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        let expectations = [
            (
                vec!["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
                async_git_output(0, "main\n", Vec::new()),
            ),
            (
                vec!["rev-parse", "--abbrev-ref", "HEAD"],
                async_git_output(0, "main\n", Vec::new()),
            ),
            (
                vec!["config", "--get", "branch.main.remote"],
                async_git_output(1, Vec::new(), Vec::new()),
            ),
        ];
        for (arguments, output) in expectations {
            let arguments = arguments
                .into_iter()
                .map(str::to_string)
                .collect::<Vec<_>>();
            command_runner
                .expect_run()
                .with(function(move |command: &AsyncGitCommand| {
                    command.arguments == arguments
                }))
                .times(1)
                .in_sequence(&mut sequence)
                .return_once(move |_| Box::pin(async move { Ok(output) }));
        }

        // Act
        let error = pull_rebase_with_runner(repo_path, &command_runner, Duration::ZERO)
            .await
            .expect_err("local upstream without a remote should fail");

        // Assert
        assert!(matches!(
            error,
            GitError::OutputParse(message)
                if message == "Failed to resolve current branch remote: not configured"
        ));
    }

    #[tokio::test]
    async fn pull_rebase_returns_last_index_lock_failure_after_retry_exhaustion() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| {
                Box::pin(async { Ok(async_git_output(0, "origin/main\n", Vec::new())) })
            });
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["pull", "--rebase", "origin", "main"]
            }))
            .times(GIT_INDEX_LOCK_RETRY_ATTEMPTS)
            .in_sequence(&mut sequence)
            .returning(|_| {
                Box::pin(async {
                    Ok(async_git_output(
                        128,
                        Vec::new(),
                        "fatal: Unable to create '.git/index.lock': File exists.",
                    ))
                })
            });

        // Act
        let error = pull_rebase_with_runner(repo_path, &command_runner, Duration::ZERO)
            .await
            .expect_err("exhausted index-lock retries should return the last failure");

        // Assert
        assert!(matches!(
            error,
            GitError::CommandFailed { command, stderr }
                if command == "git pull --rebase" && stderr.contains("index.lock")
        ));
    }

    #[tokio::test]
    async fn remote_branch_lookup_uses_origin_fallback_through_async_runner() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        let expectations = [
            (
                vec!["rev-parse", "--abbrev-ref", "HEAD"],
                async_git_output(0, "main\n", Vec::new()),
            ),
            (
                vec!["config", "--get", "branch.main.remote"],
                async_git_output(1, Vec::new(), Vec::new()),
            ),
            (
                vec!["ls-remote", "--heads", "origin", "review/topic"],
                async_git_output(0, "abc123\trefs/heads/review/topic\n", Vec::new()),
            ),
        ];
        for (arguments, output) in expectations {
            let arguments = arguments
                .into_iter()
                .map(str::to_string)
                .collect::<Vec<_>>();
            command_runner
                .expect_run()
                .with(function(move |command: &AsyncGitCommand| {
                    command.arguments == arguments
                }))
                .times(1)
                .in_sequence(&mut sequence)
                .return_once(move |_| Box::pin(async move { Ok(output) }));
        }

        // Act
        let exists = remote_branch_exists_with_runner(
            repo_path,
            "review/topic".to_string(),
            &command_runner,
        )
        .await
        .expect("remote branch lookup should succeed");

        // Assert
        assert!(exists);
    }

    #[tokio::test]
    async fn remote_branch_lookup_checks_isolated_local_remote() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);

        // Act
        let exists = remote_branch_exists(temp_dir.path().to_path_buf(), "main".to_string())
            .await
            .expect("local remote branch lookup should succeed");

        // Assert
        assert!(exists);
    }

    #[tokio::test]
    async fn remote_branch_lookup_preserves_remote_config_failure() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["rev-parse", "--abbrev-ref", "HEAD"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| Box::pin(async { Ok(async_git_output(0, "main\n", Vec::new())) }));
        command_runner
            .expect_run()
            .with(function(|command: &AsyncGitCommand| {
                command.arguments == ["config", "--get", "branch.main.remote"]
            }))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| {
                Box::pin(async {
                    Ok(async_git_output(
                        128,
                        Vec::new(),
                        "fatal: malformed branch config",
                    ))
                })
            });

        // Act
        let error = remote_branch_exists_with_runner(
            repo_path,
            "review/topic".to_string(),
            &command_runner,
        )
        .await
        .expect_err("remote config failure should not fall back to origin");

        // Assert
        assert!(matches!(
            error,
            GitError::CommandFailed { command, stderr }
                if command == "git config --get branch.main.remote"
                    && stderr.contains("malformed branch config")
        ));
    }

    #[tokio::test]
    async fn push_without_upstream_reuses_configured_remote() {
        // Arrange
        let repo_path = PathBuf::from("test-repo");
        let mut command_runner = MockAsyncGitCommandRunner::new();
        let mut sequence = Sequence::new();
        let expectations = [
            (
                vec!["push", "--force-with-lease"],
                async_git_output(128, Vec::new(), "fatal: no upstream branch"),
            ),
            (
                vec!["rev-parse", "--abbrev-ref", "HEAD"],
                async_git_output(0, "main\n", Vec::new()),
            ),
            (
                vec!["config", "--get", "branch.main.remote"],
                async_git_output(0, "review-remote\n", Vec::new()),
            ),
            (
                vec![
                    "push",
                    "--force-with-lease",
                    "--set-upstream",
                    "review-remote",
                    "HEAD",
                ],
                async_git_output(0, Vec::new(), Vec::new()),
            ),
            (
                vec!["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
                async_git_output(0, "review-remote/main\n", Vec::new()),
            ),
        ];
        for (arguments, output) in expectations {
            let arguments = arguments
                .into_iter()
                .map(str::to_string)
                .collect::<Vec<_>>();
            command_runner
                .expect_run()
                .with(function(move |command: &AsyncGitCommand| {
                    command.arguments == arguments
                }))
                .times(1)
                .in_sequence(&mut sequence)
                .return_once(move |_| Box::pin(async move { Ok(output) }));
        }

        // Act
        let upstream_reference = push_current_branch_with_runner(repo_path, &command_runner)
            .await
            .expect("configured remote push should succeed");

        // Assert
        assert_eq!(upstream_reference, "review-remote/main");
    }

    #[test]
    fn parse_branch_tracking_statuses_reads_repo_wide_branch_snapshot() {
        // Arrange
        let output = "\
main\torigin/main\tbehind 2\nwt/1234abcd\torigin/wt/1234abcd\tahead 3, behind \
                      1\nfeature/local\t\t\nfeature/gone\torigin/feature/gone\tgone\n";

        // Act
        let branch_tracking_statuses = parse_branch_tracking_statuses(output);

        // Assert
        assert_eq!(branch_tracking_statuses.get("main"), Some(&Some((0, 2))));
        assert_eq!(
            branch_tracking_statuses.get("wt/1234abcd"),
            Some(&Some((3, 1)))
        );
        assert_eq!(branch_tracking_statuses.get("feature/local"), Some(&None));
        assert_eq!(branch_tracking_statuses.get("feature/gone"), Some(&None));
    }

    #[tokio::test]
    async fn pull_rebase_returns_conflict_detail_for_conflicting_remote_change() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        let contributor_dir = tempdir().expect("failed to create contributor temp dir");
        let contributor_clone_path = contributor_dir.path().join("clone");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        let contributor_clone_path_text = contributor_clone_path.to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);
        fs::write(temp_dir.path().join("README.md"), "local change\n")
            .expect("failed to write local change");
        run_git_command(temp_dir.path(), &["add", "README.md"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Local change"]);
        run_git_command(
            contributor_dir.path(),
            &["clone", &remote_path, &contributor_clone_path_text],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.name", "Contributor User"],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.email", "contributor@example.com"],
        );
        run_git_command(
            &contributor_clone_path,
            &["checkout", "-B", "main", "origin/main"],
        );
        fs::write(contributor_clone_path.join("README.md"), "remote change\n")
            .expect("failed to write remote change");
        run_git_command(&contributor_clone_path, &["add", "README.md"]);
        run_git_command(&contributor_clone_path, &["commit", "-m", "Remote change"]);
        run_git_command(&contributor_clone_path, &["push", "origin", "main"]);

        // Act
        let result = pull_rebase(temp_dir.path().to_path_buf()).await;

        // Assert
        assert!(matches!(
            result,
            Ok(PullRebaseResult::Conflict { ref detail })
                if {
                    let normalized_detail = detail.to_ascii_lowercase();

                    (normalized_detail.contains("conflict")
                        || normalized_detail.contains("could not apply"))
                        && !detail.is_empty()
                }
        ));
    }

    #[tokio::test]
    async fn push_current_branch_returns_rejected_error_for_non_fast_forward_push() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        let contributor_dir = tempdir().expect("failed to create contributor temp dir");
        let contributor_clone_path = contributor_dir.path().join("clone");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        let contributor_clone_path_text = contributor_clone_path.to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);
        run_git_command(
            contributor_dir.path(),
            &["clone", &remote_path, &contributor_clone_path_text],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.name", "Contributor User"],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.email", "contributor@example.com"],
        );
        run_git_command(
            &contributor_clone_path,
            &["checkout", "-B", "main", "origin/main"],
        );
        fs::write(contributor_clone_path.join("remote.txt"), "remote change")
            .expect("failed to write remote file");
        run_git_command(&contributor_clone_path, &["add", "remote.txt"]);
        run_git_command(&contributor_clone_path, &["commit", "-m", "Remote change"]);
        run_git_command(&contributor_clone_path, &["push", "origin", "main"]);
        fs::write(temp_dir.path().join("local.txt"), "local change")
            .expect("failed to write local file");
        run_git_command(temp_dir.path(), &["add", "local.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Local change"]);

        // Act
        let result = push_current_branch(temp_dir.path().to_path_buf()).await;

        // Assert
        let error = result
            .expect_err("non-fast-forward push should fail")
            .to_string();
        assert!(error.contains("git push"));
        assert!(
            error.contains("stale info")
                || error.contains("rejected")
                || error.contains("fetch first")
        );
    }

    #[tokio::test]
    async fn push_current_branch_force_with_lease_updates_rewritten_history() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);
        fs::write(
            temp_dir.path().join("README.md"),
            "first published version\n",
        )
        .expect("failed to write first version");
        run_git_command(temp_dir.path(), &["add", "README.md"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Publish branch change"]);
        push_current_branch(temp_dir.path().to_path_buf())
            .await
            .expect("initial push should succeed");
        fs::write(
            temp_dir.path().join("README.md"),
            "rewritten published version\n",
        )
        .expect("failed to rewrite published version");
        run_git_command(temp_dir.path(), &["add", "README.md"]);
        run_git_command(
            temp_dir.path(),
            &["commit", "--amend", "-m", "Rewrite published branch change"],
        );

        // Act
        let upstream_reference = push_current_branch(temp_dir.path().to_path_buf())
            .await
            .expect("force-with-lease push should update rewritten history");
        let local_head = git_command_stdout(temp_dir.path(), &["rev-parse", "HEAD"]);
        let remote_head = git_command_stdout(remote_dir.path(), &["rev-parse", "refs/heads/main"]);

        // Assert
        assert_eq!(upstream_reference, "origin/main");
        assert_eq!(local_head, remote_head);
    }

    #[tokio::test]
    async fn push_current_branch_to_remote_branch_returns_custom_upstream_reference() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);

        // Act
        let upstream_reference = push_current_branch_to_remote_branch(
            temp_dir.path().to_path_buf(),
            "review/custom-branch".to_string(),
        )
        .await
        .expect("failed to push current branch to custom remote branch");

        // Assert
        assert_eq!(upstream_reference, "origin/review/custom-branch");
    }

    #[tokio::test]
    async fn current_upstream_reference_returns_origin_main() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);

        // Act
        let upstream_reference = current_upstream_reference(temp_dir.path().to_path_buf())
            .await
            .expect("failed to resolve upstream reference");

        // Assert
        assert_eq!(upstream_reference, "origin/main");
    }

    #[tokio::test]
    async fn get_ref_ahead_behind_returns_counts_between_two_local_branches() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(temp_dir.path(), &["checkout", "-b", "wt/1234abcd"]);
        fs::write(temp_dir.path().join("session.txt"), "session change\n")
            .expect("failed to write session file");
        run_git_command(temp_dir.path(), &["add", "session.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Session change"]);
        run_git_command(temp_dir.path(), &["checkout", "main"]);
        fs::write(temp_dir.path().join("main.txt"), "main change\n")
            .expect("failed to write main file");
        run_git_command(temp_dir.path(), &["add", "main.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Main change"]);

        // Act
        let status = get_ref_ahead_behind(
            temp_dir.path().to_path_buf(),
            "wt/1234abcd".to_string(),
            "main".to_string(),
        )
        .await
        .expect("failed to compare branch refs");

        // Assert
        assert_eq!(status, (1, 1));
    }

    #[tokio::test]
    async fn branch_tracking_statuses_returns_repo_wide_branch_counts() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let remote_dir = tempdir().expect("failed to create remote temp dir");
        let contributor_dir = tempdir().expect("failed to create contributor temp dir");
        let contributor_clone_path = contributor_dir.path().join("clone");
        setup_test_git_repo(temp_dir.path());
        run_git_command(remote_dir.path(), &["init", "--bare"]);
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        let contributor_clone_path_text = contributor_clone_path.to_string_lossy().to_string();
        run_git_command(temp_dir.path(), &["remote", "add", "origin", &remote_path]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "main"]);
        run_git_command(
            contributor_dir.path(),
            &["clone", &remote_path, &contributor_clone_path_text],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.name", "Contributor User"],
        );
        run_git_command(
            &contributor_clone_path,
            &["config", "user.email", "contributor@example.com"],
        );
        run_git_command(
            &contributor_clone_path,
            &["checkout", "-B", "main", "origin/main"],
        );
        fs::write(contributor_clone_path.join("remote.txt"), "remote change")
            .expect("failed to write remote file");
        run_git_command(&contributor_clone_path, &["add", "remote.txt"]);
        run_git_command(&contributor_clone_path, &["commit", "-m", "Remote change"]);
        run_git_command(&contributor_clone_path, &["push", "origin", "main"]);
        run_git_command(temp_dir.path(), &["checkout", "-b", "wt/1234abcd"]);
        fs::write(temp_dir.path().join("session.txt"), "session change\n")
            .expect("failed to write session file");
        run_git_command(temp_dir.path(), &["add", "session.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Session change"]);
        run_git_command(temp_dir.path(), &["push", "-u", "origin", "wt/1234abcd"]);
        fs::write(
            temp_dir.path().join("session.txt"),
            "session change\nmore local\n",
        )
        .expect("failed to extend session file");
        run_git_command(temp_dir.path(), &["add", "session.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "More session work"]);
        run_git_command(temp_dir.path(), &["fetch"]);

        // Act
        let branch_tracking_statuses = branch_tracking_statuses(temp_dir.path().to_path_buf())
            .await
            .expect("failed to read branch tracking statuses");

        // Assert
        assert_eq!(branch_tracking_statuses.get("main"), Some(&Some((0, 1))));
        assert_eq!(
            branch_tracking_statuses.get("wt/1234abcd"),
            Some(&Some((1, 0)))
        );
    }

    #[tokio::test]
    /// Verifies that amending a session commit whose staged result is identical
    /// to the base branch (i.e., all changes were reverted) surfaces the
    /// canonical "Nothing to commit" sentinel rather than triggering the assist
    /// retry loop with the raw git "allow-empty" error.
    async fn test_empty_amend_resets_session_commit_and_returns_no_changes() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        setup_test_git_repo(temp_dir.path());
        run_git_command(temp_dir.path(), &["checkout", "-b", "session-branch"]);
        fs::write(temp_dir.path().join("session.txt"), "session work\n")
            .expect("failed to write session file");
        run_git_command(temp_dir.path(), &["add", "session.txt"]);
        run_git_command(temp_dir.path(), &["commit", "-m", "Session commit"]);
        fs::remove_file(temp_dir.path().join("session.txt"))
            .expect("failed to remove session file");

        // Act - the worktree is dirty (session.txt removed) but amending HEAD
        // would produce a tree identical to the base branch, making the amend
        // result an empty commit.
        let result = commit_all_preserving_single_commit(
            temp_dir.path().to_path_buf(),
            "main".to_string(),
            "Session commit".to_string(),
            SingleCommitMessageStrategy::Replace,
            true,
        )
        .await;

        // Assert
        let error = result.expect_err("amend-would-be-empty should fail");
        let commit_count = git_command_stdout(temp_dir.path(), &["rev-list", "--count", "HEAD"]);
        let head_message = git_command_stdout(temp_dir.path(), &["log", "-1", "--pretty=%B"]);
        let status = git_command_stdout(temp_dir.path(), &["status", "--porcelain"]);

        assert!(
            error.to_string().contains("Nothing to commit"),
            "expected 'Nothing to commit' sentinel but got: {error}"
        );
        assert_eq!(commit_count, "1");
        assert_eq!(head_message, "Initial commit");
        assert_eq!(status, "");
    }
}