ag-git 0.13.4

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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Output;

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

use super::error::GitError;
use super::rebase::{is_rebase_conflict, run_git_command_with_index_lock_retry};
use super::repo::{
    command_output_detail, run_git_command, run_git_command_cancellable,
    run_git_command_output_sync, run_git_command_output_with_env_sync, run_git_command_sync,
};

/// 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 PRE_COMMIT_CONFIG_FILES: [&str; 2] = [".pre-commit-config.yaml", ".pre-commit-config.yml"];

/// 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_cancellable(
        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> {
    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
        };

        run_git_command_with_index_sync(
            &repo_path,
            &["diff", diff_target.as_str()],
            &temporary_index,
            "Git diff failed",
        )
    })
    .await?
}

/// 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> {
    spawn_blocking(move || {
        let pull_arguments = pull_rebase_arguments(&repo_path)
            .unwrap_or_else(|_| vec!["pull".to_string(), "--rebase".to_string()]);
        let pull_argument_refs: Vec<&str> = pull_arguments.iter().map(String::as_str).collect();
        let output = run_git_command_with_index_lock_retry(
            &repo_path,
            &pull_argument_refs,
            &[("GIT_EDITOR", ":"), ("GIT_SEQUENCE_EDITOR", ":")],
        )?;

        if output.status.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,
        })
    })
    .await?
}

/// 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.
fn pull_rebase_arguments(repo_path: &Path) -> Result<Vec<String>, GitError> {
    let upstream_reference = primary_upstream_reference(repo_path)?;

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

    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.
fn primary_upstream_reference(repo_path: &Path) -> Result<String, GitError> {
    let upstream_reference = upstream_reference_name(repo_path)?;
    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`).
fn upstream_reference_name(repo_path: &Path) -> Result<String, GitError> {
    let upstream_reference = run_git_command_sync(
        repo_path,
        &["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
        "Failed to resolve upstream branch",
    )?;
    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=.`).
fn current_branch_remote_name(repo_path: &Path) -> Result<String, GitError> {
    let current_branch_name = current_branch_name(repo_path)?;
    let remote_config_key = format!("branch.{current_branch_name}.remote");
    let remote_name = run_git_command_sync(
        repo_path,
        &["config", "--get", &remote_config_key],
        &format!("Failed to resolve current branch remote `{remote_config_key}`"),
    )?;
    let remote_name = remote_name.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(remote_name)
}

/// Returns the current local branch name for `HEAD`.
fn current_branch_name(repo_path: &Path) -> Result<String, GitError> {
    let branch_name = run_git_command_sync(
        repo_path,
        &["rev-parse", "--abbrev-ref", "HEAD"],
        "Failed to resolve current branch name",
    )?;
    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)
}

/// 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> {
    spawn_blocking(move || -> Result<String, GitError> {
        let push_output = run_git_command_output_sync(&repo_path, &["push", "--force-with-lease"])?;

        if push_output.status.success() {
            return primary_upstream_reference(&repo_path);
        }

        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".to_string(),
                stderr: push_detail,
            });
        }

        run_git_command_sync(
            &repo_path,
            &[
                "push",
                "--force-with-lease",
                "--set-upstream",
                "origin",
                "HEAD",
            ],
            "Git push failed",
        )?;

        primary_upstream_reference(&repo_path)
    })
    .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> {
    spawn_blocking(move || -> Result<bool, GitError> {
        let remote_name =
            current_branch_remote_name(&repo_path).unwrap_or_else(|_| "origin".to_string());
        let output = run_git_command_output_sync(
            &repo_path,
            &["ls-remote", "--heads", &remote_name, &remote_branch_name],
        )?;

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

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

        let stdout = String::from_utf8_lossy(&output.stdout);

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

/// 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> {
    spawn_blocking(move || -> Result<String, GitError> {
        let remote_name =
            current_branch_remote_name(&repo_path).unwrap_or_else(|_| "origin".to_string());
        let push_refspec = format!("HEAD:{remote_branch_name}");

        run_git_command_sync(
            &repo_path,
            &[
                "push",
                "--force-with-lease",
                "--set-upstream",
                &remote_name,
                &push_refspec,
            ],
            "Git push failed",
        )?;

        Ok(format!("{remote_name}/{remote_branch_name}"))
    })
    .await?
}

/// 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> {
    spawn_blocking(move || primary_upstream_reference(&repo_path)).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 tempfile::tempdir;

    use super::*;

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

        // 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!(cached_diff_after, cached_diff_before);
        assert_eq!(status_after, status_before);
    }

    #[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"
        );
    }

    #[test]
    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"]);

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

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

    #[test]
    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"],
        );

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

        // Assert
        assert_eq!(upstream_reference, "origin/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!(status.is_empty());
    }
}