mahbot 0.5.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Git subprocess wrappers — run git commands and parse porcelain/numstat output.
//!
//! Provides `run_git_*` async functions that operate on a repository path
//! and return results. For diff output parsing, see [`crate::git::diff_parse`].

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

use crate::tools::shell::apply_safe_env;
use crate::util::unquote_c_style;

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

impl CommitInfo {
    /// Return the first 7 characters of the commit hash, or the full hash
    /// if it's shorter than 7 characters.
    #[must_use]
    pub fn short_hash(&self) -> &str {
        self.hash.get(..7).unwrap_or(&self.hash)
    }
}

/// Maximum size (1 MiB) for reading untracked files in [`run_git_worktree_snapshot`]
/// and the diff page's untracked-file display.
///
/// Larger untracked files are surfaced via [`DiffStats::huge_binary_file_count`]
/// in the footer rather than line-counted; the diff page still shows a
/// placeholder instead of reading them.
pub(crate) const MAX_UNTRACKED_SIZE: u64 = 1024 * 1024;

/// Cap on the number of collapsed untracked directories enumerated per
/// [`run_git_worktree_snapshot`] refresh.
const MAX_UNTRACKED_DIRS_ENUMERATED: usize = 10;
/// Cap on the total number of untracked files classified (line-counted or
/// oversized/binary-detected) per [`run_git_worktree_snapshot`] refresh.
const MAX_UNTRACKED_FILES_COUNTED: usize = 500;
/// Cap on the total bytes read from untracked files per
/// [`run_git_worktree_snapshot`] refresh.
const MAX_UNTRACKED_BYTES_READ: u64 = 10 * 1024 * 1024;

/// Classification of an untracked file read for diff display / line counting.
///
/// Ordering is load-bearing: size is checked from metadata before reading,
/// then null-byte detection, then UTF-8 validity. Unreadable paths are skipped
/// entirely — only `TooLarge` and `Binary` produce GUI placeholders.
pub(crate) enum UntrackedFileRead {
    Text(String),
    TooLarge(u64),
    Binary,
    Skip,
}

/// Classify an in-memory untracked-file buffer (size already confirmed ≤ the
/// caller's limit). Returns `None` for binary (a null byte, or invalid UTF-8
/// without a null byte), or the UTF-8 text otherwise. Shared by
/// [`read_untracked_file`] and [`count_untracked_file`] so the
/// null-byte/UTF-8 binary rule lives in one place.
fn classify_untracked_content(content: Vec<u8>) -> Option<String> {
    if content.contains(&0) {
        return None;
    }
    String::from_utf8(content).ok()
}

pub(crate) async fn read_untracked_file(path: &Path, max_size: u64) -> UntrackedFileRead {
    if !path.is_file() {
        return UntrackedFileRead::Skip;
    }
    let Ok(meta) = tokio::fs::metadata(path).await else {
        return UntrackedFileRead::Skip;
    };
    if meta.len() > max_size {
        return UntrackedFileRead::TooLarge(meta.len());
    }
    let Ok(content) = tokio::fs::read(path).await else {
        return UntrackedFileRead::Skip;
    };
    // Invalid UTF-8 without a null byte is still binary — never Skip, or the
    // GUI would silently drop the file instead of showing a placeholder.
    classify_untracked_content(content).map_or(UntrackedFileRead::Binary, UntrackedFileRead::Text)
}

/// Whether to discard changes in a single file or an entire directory tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscardTarget {
    File,
    /// Recursively discard all changes within a directory (and its subdirectories).
    Directory,
}

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

/// Run `git diff HEAD --no-color --find-renames` (when `commit_ref` is `None`)
/// or `git show -m <commit_ref> --no-color --find-renames --format=""` (when `Some`).
///
/// `-m` splits merge commits into per-parent diffs, producing standard unified diff
/// blocks that `parse_git_diff` can handle. This may produce duplicate file paths in the
/// tree sidebar (one `diff --git` block per parent), which is expected — each parent
/// comparison is a different diff.
/// `--format=""` suppresses the commit log header.
pub async fn run_git_diff(repo_path: &Path, commit_ref: Option<&str>) -> anyhow::Result<String> {
    if let Some(hash) = commit_ref {
        run_git_command(
            repo_path,
            &[
                "show",
                "-m",
                hash,
                "--no-color",
                "--find-renames",
                "--format=",
            ],
        )
        .await
    } else {
        run_git_command(repo_path, &["diff", "HEAD", "--no-color", "--find-renames"]).await
    }
}

/// Run `git status --porcelain` and return the output.
pub async fn run_git_status(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(repo_path, &["status", "--porcelain"]).await
}

/// Run `git show HEAD:<path>` (when `commit_ref` is `None`)
/// or `git show <commit_ref>:<path>` (when `Some`) and return the file content.
///
/// Returns `None` if the file does not exist at that ref (new/untracked files,
/// or root-commit `~1` which has no parent), or if any git error occurs.
///
/// **`~1` parent refs**: The caller constructs the parent hash. To get the parent
/// version, pass `commit_ref = Some(&format!("{hash}~1"))`.
pub async fn run_git_show(
    repo_path: &Path,
    file_path: &str,
    commit_ref: Option<&str>,
) -> Option<String> {
    let show_arg = if let Some(hash) = commit_ref {
        format!("{hash}:{file_path}")
    } else {
        format!("HEAD:{file_path}")
    };
    run_git_command(repo_path, &["show", &show_arg]).await.ok()
}

/// Resolve the repository top-level directory (the `.git`-containing ancestor).
///
/// `repo_path` may be the repo root or a subdirectory of it. Walks upward to
/// the first ancestor that contains a `.git` entry — a directory for normal
/// repos, or a *file* for linked worktrees/submodules, hence [`is_git_repo`]
/// (which uses `exists()`, not `is_dir()`).
///
/// Deliberately does NOT use `git rev-parse --show-toplevel`: repo discovery
/// itself runs the dubious-ownership check this exists to satisfy, so it would
/// recurse into the same failure (circular). Canonicalizes the resolved path
/// where possible so the value matches git's own realpath-normalized discovery.
pub(crate) fn resolve_git_top_level(repo_path: &Path) -> Option<PathBuf> {
    let dir = repo_path.ancestors().find(|dir| is_git_repo(dir))?;
    Some(std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()))
}

/// Inject the repo top-level into git's per-process config as `safe.directory`.
///
/// Uses the process-scoped `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/
/// `GIT_CONFIG_VALUE_0` env form — never writes the user's global gitconfig and
/// never uses `*` (which would fully opt out of the CVE ownership guard). The
/// value is scoped to the single resolved repo top-level. On git < 2.38 the env
/// form is silently ignored by git, which is acceptable for the supported
/// target as long as the repo is owned by the running user.
fn inject_safe_directory(cmd: &mut tokio::process::Command, repo_path: &Path) {
    let Some(top_level) = resolve_git_top_level(repo_path) else {
        return;
    };
    cmd.env("GIT_CONFIG_COUNT", "1");
    cmd.env("GIT_CONFIG_KEY_0", "safe.directory");
    cmd.env("GIT_CONFIG_VALUE_0", top_level.as_path());
}

/// Create a [`tokio::process::Command`] for `git` with a sanitized environment.
///
/// The subprocess environment is cleared and re-populated with only safe
/// environment variables (see [`apply_safe_env`]) to prevent credential
/// leakage (CWE-200). `LC_ALL=C` is set for consistent locale behavior
/// across all git invocations. This is the only entry point for production git
/// subprocess creation in this module — all callers must use this helper.
///
/// `repo_root` is the workspace/`current_dir` path for repo-bound invocations;
/// when present, the resolved repo top-level is injected as `safe.directory`
/// (see [`inject_safe_directory`]) so git works on repos owned by a different
/// UID. Pass `None` for repo-agnostic invocations (e.g. [`git_is_installed`]),
/// which must not receive a repo-path value.
///
/// Callers should add further configuration (args, current_dir, stdio, etc.)
/// and then spawn or execute the command.
fn git_command(repo_root: Option<&Path>) -> tokio::process::Command {
    let mut cmd = tokio::process::Command::new("git");
    apply_safe_env(&mut cmd);
    cmd.env("LC_ALL", "C");
    if let Some(path) = repo_root {
        inject_safe_directory(&mut cmd, path);
    }
    cmd
}

/// Run a git command without any interpretation of the exit code.
///
/// Shared by [`run_git_command`] and other raw-output callers to avoid
/// duplicating the spawn + output + decode pattern. Returns the raw
/// [`std::process::Output`] so each caller can interpret the exit
/// status as appropriate.
///
/// **Environment sanitization**: The subprocess environment is cleared
/// and re-populated with only a safe set of environment variables
/// (see [`apply_safe_env`] for details). This prevents leaking API keys
/// and other secrets into child processes (CWE-200), but it also means
/// variables like `SSH_AUTH_SOCK` and `GIT_SSH_COMMAND` are **not**
/// inherited. This is consistent with the shell tool's behavior — use
/// SSH config (`~/.ssh/config`) for SSH-based git remotes rather than
/// environment variables. ([`run_git_fetch`] is the one exception: it
/// restores `SSH_AUTH_SOCK` so SSH-agent remotes still work.)
pub(crate) async fn run_git_output(
    repo_path: &Path,
    args: &[&str],
) -> anyhow::Result<std::process::Output> {
    let mut cmd = git_command(Some(repo_path));
    cmd.args(args).current_dir(repo_path);
    cmd.output()
        .await
        .with_context(|| format!("Failed to run git {}", args.join(" ")))
}

/// Run a git command and return stdout as string on success.
///
/// Returns an error if git exits with a non-zero status.
pub async fn run_git_command(repo_path: &Path, args: &[&str]) -> anyhow::Result<String> {
    let output = run_git_output(repo_path, args).await?;

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

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

/// Check if `git status --porcelain` output contains any unstaged changes.
///
/// Looks for any line where the worktree status column (second character) is
/// non-space — this indicates an unstaged modification, deletion, or untracked
/// file (`??` has `?` in the worktree column, `!!` ignored lines also have `!`
/// but are excluded here since default `--porcelain` doesn't show ignored files).
/// Fully-staged-only entries (`M `, `A `) are ignored.
///
/// This is a pure parsing function with no I/O — callers run `git status`
/// themselves and pass the captured stdout here.
///
#[must_use]
pub fn has_unstaged_changes(porcelain: &str) -> bool {
    porcelain.lines().any(|line| {
        let line = line.trim_end();
        if line.is_empty() {
            return false;
        }
        // Check the worktree status column (byte index 1).
        // For `??` (untracked) lines, both columns are `?` — the second is non-space.
        // For ` M`, `MM`, ` D`, etc., the second column is non-space.
        // For `M `, `A `, etc., the second column is space (fully staged).
        line.as_bytes().get(1).is_some_and(|&b| b != b' ')
    })
}

/// Stage all changes in the working tree via `git add -A`.
///
/// This stages tracked modifications, untracked files, and file deletions.
/// Unlike [`run_git_commit`], this does NOT commit — it only stages changes
/// into the index.
///
/// Returns the stdout of the git command on success.
pub async fn run_git_add_all(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(repo_path, &["add", "-A"]).await
}

/// Run `git rev-parse HEAD` and return the trimmed commit hash.
///
/// Errors when HEAD cannot be resolved (e.g. a repository with no commits
/// yet). Callers that need unknown-as-`None` semantics should use `.ok()`.
pub async fn run_git_head(repo_path: &Path) -> anyhow::Result<String> {
    Ok(run_git_command(repo_path, &["rev-parse", "HEAD"])
        .await?
        .trim()
        .to_string())
}

/// Run `git write-tree` and return the trimmed index tree hash.
///
/// The tree hash identifies the exact staged content (index). Errors when the
/// index cannot be written (e.g. unmerged entries). Callers that need
/// unknown-as-`None` semantics should use `.ok()`.
pub async fn run_git_write_tree(repo_path: &Path) -> anyhow::Result<String> {
    Ok(run_git_command(repo_path, &["write-tree"])
        .await?
        .trim()
        .to_string())
}

/// Stage all changes and commit with the given message.
/// Runs `git add -A` followed by `git commit -m "<msg>"`,
/// then captures the full SHA via `git rev-parse HEAD` and
/// line stats via `git diff --numstat`.
pub async fn run_git_commit(repo_path: &Path, message: &str) -> anyhow::Result<CommitInfo> {
    // Stage all changes (tracked, untracked, removed) in the worktree.
    run_git_add_all(repo_path).await?;

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

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

    // Capture line stats via --numstat. Try HEAD~1..HEAD first.
    let (lines_added, lines_removed) =
        if let Ok(stats) = parse_numstat(repo_path, &["HEAD~1..HEAD"]).await {
            stats
        } else {
            // HEAD~1 doesn't exist (first commit) — fall back to the empty tree hash.
            parse_numstat(
                repo_path,
                &["4b825dc642cb6eb9a060e54bf8d69288fbee4904", "HEAD"],
            )
            .await
            .unwrap_or((0, 0))
        };
    Ok(CommitInfo {
        hash,
        lines_added,
        lines_removed,
    })
}

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

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

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

/// A single entry from `git diff --numstat` or `git show --numstat` output.
///
/// `additions` and `deletions` are `None` for binary files (where git outputs `-`
/// instead of a line count). Regular files always have `Some` values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumstatEntry {
    /// Lines added, or `None` if the file is binary.
    pub additions: Option<i64>,
    /// Lines deleted, or `None` if the file is binary.
    pub deletions: Option<i64>,
    /// File path as printed by git.
    pub path: String,
}

/// Parse the output of `git diff --numstat` or `git show --numstat`.
///
/// Returns a vector of [`NumstatEntry`] values for each file.
/// Binary files (displayed as `-\t-\t<path>`) have `additions` and `deletions`
/// set to `None` so callers can distinguish them from regular entries with zero
/// changes. Lines that don't match the expected 3-field format are silently skipped.
///
/// This is a pure parsing function with no I/O — callers run git themselves
/// and pass the captured stdout here.
#[must_use]
pub fn parse_numstat_lines(stdout: &str) -> Vec<NumstatEntry> {
    let mut result = Vec::new();
    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        // Format: <additions>\t<deletions>\t<path>
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() != 3 {
            continue;
        }

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

        // Binary files are displayed as "-\t-\t<path>"
        // If either field is "-", treat the file as binary (both fields None).
        // This is defensive: git always outputs "-\t-" for both fields on binary
        // files, but we handle the mixed case conservatively.
        if additions_str == "-" || deletions_str == "-" {
            result.push(NumstatEntry {
                additions: None,
                deletions: None,
                path,
            });
            continue;
        }

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

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

/// Run `git diff --numstat <range...>` and sum the line stats across all files.
///
/// Returns `Ok((lines_added, lines_removed))` on success (even if the diff
/// is empty). Returns the git error message on failure.
async fn parse_numstat(repo_path: &Path, range: &[&str]) -> anyhow::Result<(i64, i64)> {
    let entries = run_git_diff_numstat(repo_path, range).await?;

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

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

    Ok((lines_added, lines_removed))
}

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

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

/// Get the current branch name (e.g. `main`, `feature/xyz`).
pub async fn run_git_current_branch(repo_path: &Path) -> anyhow::Result<String> {
    run_git_command(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"])
        .await
        .map(|s| s.trim().to_string())
}

/// Get behind/ahead counts against the upstream branch.
///
/// Returns `(behind, ahead)`. If there is no upstream configured, returns
/// `(0, 0)` without error.
pub async fn run_git_behind_ahead(repo_path: &Path) -> anyhow::Result<(usize, usize)> {
    match run_git_command(
        repo_path,
        &["rev-list", "--count", "--left-right", "HEAD...@{upstream}"],
    )
    .await
    {
        Ok(out) => {
            let parts: Vec<&str> = out.trim().split('\t').collect();
            if parts.len() == 2 {
                let ahead = parts[0].parse::<usize>().unwrap_or(0);
                let behind = parts[1].parse::<usize>().unwrap_or(0);
                Ok((behind, ahead))
            } else {
                Ok((0, 0))
            }
        }
        Err(e) => {
            // Only git's own "no upstream" verdicts are genuine empty results.
            // The error string embeds the command args (`@{upstream}`), so a
            // naive "contains upstream" match also swallows spawn/runtime
            // failures — anchor on git's stderr wording instead.
            let msg = e.to_string();
            if msg.contains("fatal: no upstream") || msg.contains("HEAD does not point to a branch")
            {
                Ok((0, 0))
            } else {
                Err(e)
            }
        }
    }
}

/// Hard timeout for a single `git fetch` — an unreachable/slow remote must not
/// hang the periodic remote sync indefinitely.
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);

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

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

/// Run `git fetch` so upstream refs are refreshed before behind/ahead is
/// computed (a fetch-free comparison only sees the last-fetched remote state).
///
/// The subprocess environment is sanitized (see [`git_command`]), then
/// `GIT_TERMINAL_PROMPT=0` prevents git/credential helpers from popping an
/// interactive (osxkeychain) prompt for a credential-less remote, and
/// `SSH_AUTH_SOCK` is restored (if present) so SSH-agent remotes still work —
/// the sanitized base drops it, and with it dropped behind/ahead would be
/// limited to the locally-available remote ref. The fetch is time-boxed by
/// [`FETCH_TIMEOUT`] and single-flight guarded.
///
/// On timeout the direct `git` child is killed and reaped; a remote helper it
/// spawned (e.g. `git-remote-https`) is not signalled directly but terminates
/// when its communication pipe closes, so it cannot hold the fetch open past
/// the timeout.
///
/// Returns the fetch stdout; callers most often discard it and only log a
/// failure (the subsequent behind/ahead read still works against local refs).
pub async fn run_git_fetch(repo_path: &Path) -> anyhow::Result<String> {
    // Single-flight: if a fetch is already running, skip this one rather than
    // queueing it (it would only contend on the same ref locks).
    if FETCH_IN_FLIGHT.swap(true, Ordering::AcqRel) {
        return Ok(String::new());
    }
    let _guard = FetchInFlightGuard;

    let mut cmd = git_command(Some(repo_path));
    cmd.arg("fetch").arg("--quiet").current_dir(repo_path);
    cmd.env("GIT_TERMINAL_PROMPT", "0");
    // Restore the SSH agent socket for SSH remotes (dropped by apply_safe_env).
    if let Some(sock) = std::env::var_os("SSH_AUTH_SOCK") {
        cmd.env("SSH_AUTH_SOCK", sock);
    }
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Kill the child if this task is cancelled (e.g. on shutdown) so a running
    // fetch cannot outlive the runtime and orphan.
    cmd.kill_on_drop(true);

    let mut child = cmd.spawn().context("Failed to spawn git fetch")?;
    let mut stdout = child.stdout.take();
    let mut stderr = child.stderr.take();
    let mut stdout_buf = Vec::new();
    let mut stderr_buf = Vec::new();

    // Wait for the child while draining its pipes concurrently, all inside the
    // timeout — a slow/unreachable remote (or a subprocess that outlives git
    // holding the pipes) cannot hang the periodic sync. On timeout, kill and
    // reap so the process does not linger as a zombie.
    let wait = child.wait();
    let read_stdout = async {
        if let Some(out) = &mut stdout {
            let _ = out.read_to_end(&mut stdout_buf).await;
        }
    };
    let read_stderr = async {
        if let Some(err) = &mut stderr {
            let _ = err.read_to_end(&mut stderr_buf).await;
        }
    };

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

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

    Ok(String::from_utf8_lossy(&stdout_buf).to_string())
}

/// Aggregate working-tree diff statistics for the GUI footer.
///
/// `added`/`removed` are the exact line counts used by the footer (+X / -Y)
/// and by reviewer churn calibration. `huge_binary_file_count` counts
/// oversized (> [`MAX_UNTRACKED_SIZE`]) and binary *untracked* files
/// (top-level or inside a collapsed untracked directory). It is a separate
/// indicator and is deliberately NOT folded into `added`/`removed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiffStats {
    /// Total lines added (tracked diff + line-counted untracked text files).
    pub added: i64,
    /// Total lines removed (tracked diff only).
    pub removed: i64,
    /// Count of oversized/binary untracked files surfaced as a separate
    /// "N files" indicator, not line counts.
    pub huge_binary_file_count: usize,
}

/// Git file status for coloring the file tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitFileStatus {
    /// File has uncommitted modifications (M in porcelain output).
    Modified,
    /// File is untracked (?? in porcelain output) or newly added (A).
    Added,
}

/// Accumulator for untracked-file classification during a single
/// [`run_git_worktree_snapshot`] refresh. Enforces the per-refresh work caps.
#[derive(Default)]
struct UntrackedAccumulator {
    added: i64,
    huge_binary_file_count: usize,
    files_processed: usize,
    bytes_read: u64,
}

impl UntrackedAccumulator {
    /// Whether another untracked file may still be inspected this refresh.
    fn can_process(&self) -> bool {
        self.files_processed < MAX_UNTRACKED_FILES_COUNTED
            && self.bytes_read < MAX_UNTRACKED_BYTES_READ
    }
}

/// Count a single untracked file (or file enumerated inside a collapsed
/// directory) toward the diff-stats accumulation.
///
/// Oversized files are surfaced via `huge_binary_file_count` (metadata-only
/// check, no bytes read). Normal-size files are read (bounded by
/// [`MAX_UNTRACKED_BYTES_READ`]) and their line count added; binary /
/// invalid-UTF-8 files increment `huge_binary_file_count` instead.
/// Files beyond the per-refresh caps are skipped entirely (not line-counted
/// and NOT added to the file-count) — a bounded limitation for a pathological
/// very-large untracked tree.
async fn count_untracked_file(repo_path: &Path, path: &str, accum: &mut UntrackedAccumulator) {
    if !accum.can_process() {
        return;
    }
    let full_path = repo_path.join(path);
    if !full_path.is_file() {
        return;
    }
    let Ok(meta) = tokio::fs::metadata(&full_path).await else {
        return;
    };
    accum.files_processed += 1;
    if meta.len() > MAX_UNTRACKED_SIZE {
        accum.huge_binary_file_count += 1;
        return;
    }
    if accum.bytes_read + meta.len() > MAX_UNTRACKED_BYTES_READ {
        return;
    }
    let Ok(content) = tokio::fs::read(&full_path).await else {
        return;
    };
    accum.bytes_read += content.len() as u64;
    match classify_untracked_content(content) {
        Some(text) => {
            #[expect(clippy::cast_possible_wrap)]
            let line_count = text.lines().count() as i64;
            accum.added += line_count;
        }
        None => accum.huge_binary_file_count += 1,
    }
}

/// Enumerate the (untracked) files inside a collapsed `?? dir/` porcelain
/// entry with a git-scoped, gitignore-respecting listing.
///
/// Uses `git status --porcelain --untracked-files=all` scoped by a
/// `:(literal)` pathspec so the directory path is never interpreted as a glob
/// (names containing `*`/`?`/`:` match literally). `git` handles nesting,
/// ignores, and symlinks — no manual filesystem walk.
async fn enumerate_untracked_dir(repo_path: &Path, dir: &str) -> anyhow::Result<Vec<String>> {
    let pathspec = format!(":(literal){dir}");
    let out = run_git_command(
        repo_path,
        &[
            "status",
            "--porcelain",
            "--untracked-files=all",
            "--",
            &pathspec,
        ],
    )
    .await?;
    Ok(parse_untracked_from_porcelain(&out))
}

/// Whether the repository has a resolvable HEAD commit (i.e. is not unborn).
///
/// Used to distinguish an unborn HEAD (a freshly `git init`ed repo with no
/// commits) from other numstat failures — an unborn repo should still yield a
/// working-tree snapshot with empty diff stats and full per-file statuses.
async fn git_head_exists(repo_path: &Path) -> bool {
    run_git_command(repo_path, &["rev-parse", "--verify", "HEAD"])
        .await
        .is_ok()
}

/// Working-tree snapshot: aggregate diff stats plus per-file porcelain
/// statuses, from a single `git status --porcelain` + one numstat pass.
///
/// The statuses are the same map the editor's file-tree coloring uses (once
/// forwarded by `GitState`), and the stats drive the footer (+N / -M) and
/// reviewer churn calibration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitWorktreeSnapshot {
    /// Aggregate line stats (tracked diff + line-counted untracked text).
    pub stats: DiffStats,
    /// Per-file porcelain status, keyed by workspace-relative path.
    pub file_statuses: HashMap<String, GitFileStatus>,
    /// The repo has no commits (unborn HEAD): tracked stats are `(0, 0)` but
    /// per-file statuses still flow. Consumers that predate the unborn-HEAD
    /// tolerance and must keep their old error semantics (reviewer churn)
    /// check this instead of treating the snapshot as a valid diff baseline.
    pub unborn_head: bool,
}

/// Capture the working-tree snapshot for a repository path.
///
/// Runs `git status --porcelain` first — the single source for both the
/// untracked-file list and the per-file status map. A failure here is fatal:
/// broken or missing git never yields a snapshot, so callers keep their
/// last-known-good state (or default churn).
///
/// Untracked files are line-counted (since `git diff HEAD` only considers
/// tracked files). Untracked files larger than [`MAX_UNTRACKED_SIZE`] or
/// detected as binary are surfaced via `huge_binary_file_count`. Collapsed
/// `?? dir/` entries are enumerated with a scoped `git status
/// --untracked-files=all` listing (gitignore-respecting), and each file
/// inside contributes exact line counts (or the file-count if
/// oversized/binary). Per-refresh work is bounded by the `MAX_UNTRACKED_*`
/// caps. A missing HEAD (unborn repo) yields `(0, 0)` stats so per-file
/// statuses still flow; any other numstat failure is fatal.
pub async fn run_git_worktree_snapshot(repo_path: &Path) -> anyhow::Result<GitWorktreeSnapshot> {
    let porcelain = run_git_status(repo_path).await?;
    let file_statuses = parse_git_status_porcelain(&porcelain);
    let untracked = parse_untracked_from_porcelain(&porcelain);

    let (added, removed, unborn_head) = match parse_numstat(repo_path, &["HEAD"]).await {
        Ok(stats) => (stats.0, stats.1, false),
        Err(_) if !git_head_exists(repo_path).await => (0, 0, true),
        Err(e) => return Err(e.context("Failed to compute working-tree diff stats")),
    };
    let mut accum = UntrackedAccumulator {
        added,
        ..Default::default()
    };

    let mut dirs_enumerated = 0;
    for path in &untracked {
        if path.ends_with('/') {
            if dirs_enumerated >= MAX_UNTRACKED_DIRS_ENUMERATED {
                continue;
            }
            dirs_enumerated += 1;
            match enumerate_untracked_dir(repo_path, path).await {
                Ok(files) => {
                    for file in &files {
                        count_untracked_file(repo_path, file, &mut accum).await;
                    }
                }
                Err(e) => warn!(error = %e, dir = %path, "Failed to enumerate untracked directory"),
            }
        } else {
            count_untracked_file(repo_path, path, &mut accum).await;
        }
    }

    Ok(GitWorktreeSnapshot {
        stats: DiffStats {
            added: accum.added,
            removed,
            huge_binary_file_count: accum.huge_binary_file_count,
        },
        file_statuses,
        unborn_head,
    })
}

/// Sync with remote: `git pull --ff-only` then `git push`.
///
/// Returns the combined output of both commands.
pub async fn run_git_sync(repo_path: &Path) -> anyhow::Result<String> {
    let pull_out = run_git_command(repo_path, &["pull", "--ff-only"]).await?;
    let push_out = run_git_command(repo_path, &["push"]).await?;
    let combined = if pull_out.trim().is_empty() {
        push_out
    } else if push_out.trim().is_empty() {
        pull_out
    } else {
        format!("{pull_out}\n{push_out}")
    };
    Ok(combined)
}

/// Discard all changes to a path — restores tracked files from HEAD, unstages
/// staged new files, and removes untracked files. Uses a 3-step git command
/// sequence to handle ALL file states:
///
/// 1. `git checkout HEAD -- <path>`
///    — restores tracked files from HEAD (handles Modified, Deleted, Renamed).
///    For files staged in the index (Added) that don't exist in HEAD, checkout
///    removes them from both index and working tree. Untracked files fail with
///    "did not match" — absorbed below.
///
/// 2. `git reset HEAD -- <path>`
///    — unstages staged new (Added) files so that `git clean` can remove them.
///    For files already restored by checkout this is a no-op. Errors
///    (e.g. untracked files not in index) are absorbed.
///
/// 3. `git clean -f[d] -- <path>`
///    — removes untracked files. `-f` for files, `-fd` for directories (recurses
///    into subdirectories). Errors (file already tracked, already removed by
///    checkout) are absorbed.
///
/// All errors from all three steps are absorbed. After the sequence, the working
/// tree is verified via `git status --porcelain -- <path>`: if the output is
/// empty the operation succeeded; otherwise the remaining changes are reported.
///
/// Note: `git reset HEAD` also exits with non-zero status when the path is
/// outside the repository — callers should validate paths before calling this.
pub async fn run_git_discard(
    repo_path: &Path,
    path: &str,
    target: DiscardTarget,
) -> anyhow::Result<()> {
    let _ = run_git_command(repo_path, &["checkout", "HEAD", "--", path]).await;

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

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

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

/// Get the last commit's subject via `git log -1 --format=%s`.
///
/// If `commit_hash` is `Some`, get the message for that specific commit
/// instead of HEAD.
pub async fn run_git_commit_message(
    repo_path: &Path,
    commit_hash: Option<&str>,
) -> anyhow::Result<String> {
    let mut args = vec!["log", "-1", "--format=%s"];
    if let Some(hash) = commit_hash {
        args.push(hash);
    }
    let out = run_git_command(repo_path, &args).await?;
    Ok(out.trim().to_string())
}

/// List new or untracked files in the working tree.
///
/// Delegates to [`run_git_status`] to run `git status --porcelain`, then passes
/// the output to [`parse_new_files_from_porcelain`] for parsing.
///
/// Catches both `??` (untracked) and any entry starting with `A` (staged as new,
/// including `A ` clean staged and `AM` staged+modified).
pub(crate) async fn list_new_or_untracked_files(repo_path: &Path) -> anyhow::Result<Vec<String>> {
    let porcelain = run_git_status(repo_path).await?;
    Ok(parse_new_files_from_porcelain(&porcelain))
}

/// Shared helper for parsing file paths from `git status --porcelain` output.
///
/// Iterates over lines, applies `predicate` to select relevant entries, then
/// extracts the path portion (starting at index 3 after the 2-char status
/// prefix and space). Guarded with `get(3..)` to avoid panics on malformed
/// input (empty lines, truncated porcelain entries).
fn parse_porcelain_paths(porcelain: &str, predicate: impl FnMut(&&str) -> bool) -> Vec<String> {
    porcelain
        .lines()
        .filter(predicate)
        // Note: porcelain lines are at minimum 4 chars (<XY><space><path>), but
        // we guard with `get()` to prevent panics on malformed input.
        .filter_map(|line| {
            let path = line.get(3..)?;
            if path.is_empty() {
                None
            } else {
                Some(unquote_c_style(path).unwrap_or_else(|| path.to_string()))
            }
        })
        .collect()
}

/// Parse new/added file paths from `git status --porcelain` output.
///
/// Returns file paths for entries where the index status indicates a new file:
/// - `??` — untracked file
/// - `A ` at position 0 — staged as new (first char is `A`)
///
/// This correctly catches `A ` (staged, clean) and `AM` (staged as new, then
/// modified in working tree) because both start with `A`. The porcelain format
/// is `<XY><space><path>` where X = index status, Y = working tree status.
/// Path always starts at index 3.
///
/// Excludes ` A` (not tracked, added only to working tree — this is a file
/// that exists but is not tracked by git; it falls under `??` instead).
///
/// To parse only truly untracked files (those prefixed with `?? `), use
/// [`parse_untracked_from_porcelain`] instead.
#[must_use]
pub(crate) fn parse_new_files_from_porcelain(porcelain: &str) -> Vec<String> {
    parse_porcelain_paths(porcelain, |line| {
        line.starts_with("?? ") || line.starts_with('A')
    })
}

/// Parse only truly untracked file paths from `git status --porcelain` output.
///
/// Returns file paths for entries where the porcelain status is `?? ` (untracked
/// file not in the index). Unlike [`parse_new_files_from_porcelain`], this does
/// *not* include staged-as-new (`A `) files — it only catches entries starting
/// with `?? `.
///
/// Use this when you only want files that are truly untracked and do not want
/// overlap with staged-as-new files that might already be present from a
/// `git diff HEAD` parse.
#[must_use]
pub(crate) fn parse_untracked_from_porcelain(porcelain: &str) -> Vec<String> {
    parse_porcelain_paths(porcelain, |line| line.starts_with("?? "))
}

/// Parse `git status --porcelain` output into a map of file path → `GitFileStatus`.
///
/// The porcelain format uses a two-column status (index + worktree).
/// Precedence: modified > added > untracked. Rename entries (`R`) extract
/// the new path after ` -> `. Deleted files (`D`) are ignored. Handles
/// git's C-style quoting for paths with special characters.
///
/// Keys are the paths as emitted by `git status --porcelain`. When the
/// command runs with cwd = the workspace root, these are workspace-relative
/// paths (the same key space as the editor's file tree).
#[must_use]
pub fn parse_git_status_porcelain(output: &str) -> HashMap<String, GitFileStatus> {
    let mut map: HashMap<String, GitFileStatus> = HashMap::new();

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

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

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

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

        // Rename entries: "R  old_path -> new_path"
        // Both paths may be individually C-quoted by git. The separator
        // ` -> ` appears at the boundary between the two paths.
        if ix == 'R' {
            let rest = &trimmed[2..];
            let rest = rest.trim_start();
            let new_path: String = if rest.starts_with('"') {
                // Both paths are quoted. The boundary is `" -> "`.
                // rsplit_once on `" -> "` strips the opening quote of the
                // new path — add it back so `unquote_c_style` can strip both.
                if let Some((_, tail)) = rest.rsplit_once("\" -> \"") {
                    format!("\"{tail}")
                } else {
                    // Malformed — skip.
                    continue;
                }
            } else {
                // Unquoted paths: split on ` -> `.
                if let Some((_, tail)) = rest.rsplit_once(" -> ") {
                    tail.to_string()
                } else {
                    continue;
                }
            };
            if let Some(unquoted) = unquote_c_style(&new_path) {
                map.insert(unquoted, GitFileStatus::Modified);
            }
            continue;
        }

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

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

        let Some(path) = unquote_c_style(path) else {
            continue;
        };
        // Strip trailing slash — git appends '/' for untracked directories
        // (e.g., `?? new_dir/`), but tree node full_path has no trailing slash.
        let path = path.strip_suffix('/').unwrap_or(&path).to_string();

        // For entries with multiple lines referencing the same file (e.g., staged +
        // unstaged), keep the most "interesting" status: Modified > Added.
        let entry = map.entry(path).or_insert(status);
        if status == GitFileStatus::Modified && *entry == GitFileStatus::Added {
            *entry = GitFileStatus::Modified;
        }
    }

    map
}

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

    // ── Unit tests for CommitInfo::short_hash ────────────────────

    #[test]
    fn short_hash_cases() {
        let cases = [
            (
                "long hash truncated to 7 chars",
                "abc1234def5678",
                "abc1234",
            ),
            ("short hash returned as-is", "abc12", "abc12"),
            ("exactly 7 chars returned as-is", "abc1234", "abc1234"),
        ];
        for (name, hash, expected) in &cases {
            let info = CommitInfo {
                hash: hash.to_string(),
                lines_added: 0,
                lines_removed: 0,
            };
            assert_eq!(info.short_hash(), *expected, "{name}");
        }
    }

    // ── safe.directory resolver (CVE-2022-24765 ancestor walk) ───

    #[test]
    fn resolve_git_top_level_repo_root() {
        let (_dir, repo_path) = init_temp_repo();
        let expected = std::fs::canonicalize(&repo_path).expect("canonicalize repo");
        assert_eq!(resolve_git_top_level(&repo_path), Some(expected));
    }

    #[test]
    fn resolve_git_top_level_from_subdir() {
        let (_dir, repo_path) = init_temp_repo();
        let subdir = repo_path.join("src");
        std::fs::create_dir(&subdir).expect("create subdir");
        let expected = std::fs::canonicalize(&repo_path).expect("canonicalize repo");
        assert_eq!(resolve_git_top_level(&subdir), Some(expected));
    }

    #[test]
    fn resolve_git_top_level_non_repo_is_none() {
        let dir = tempfile::tempdir().expect("create temp dir");
        assert_eq!(
            resolve_git_top_level(dir.path()),
            None,
            "non-repo dir must resolve to None"
        );
    }

    #[test]
    fn resolve_git_top_level_accepts_git_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        // A `.git` *file* (linked worktree / submodule marker) is sufficient —
        // the walk uses `exists()`, not `is_dir()`.
        std::fs::write(dir.path().join(".git"), b"gitdir: /elsewhere").expect("write .git file");
        let expected = std::fs::canonicalize(dir.path()).expect("canonicalize dir");
        assert_eq!(resolve_git_top_level(dir.path()), Some(expected));
    }

    // ── Safe.directory injection (dubious-ownership fix) ──────────

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

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

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

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

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

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

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

    // ── Integration tests for run_git_* functions ────────────────

    #[tokio::test]
    async fn test_git_has_commits_true() {
        let (_dir, repo_path) = init_temp_repo();
        let has = git_has_commits(&repo_path).await;
        assert!(has, "repo with initial commit should have commits");
    }

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

        // `git init` without any commit — empty repo
        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .status()
            .expect("git init");
        assert!(status.success());

        let has = git_has_commits(&repo_path).await;
        assert!(!has, "empty repo should not have commits");
    }

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

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

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

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

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

    #[tokio::test]
    async fn test_run_git_current_branch_default() {
        let (_dir, repo_path) = init_temp_repo();
        let branch = run_git_current_branch(&repo_path).await.expect("branch");
        assert!(!branch.is_empty(), "branch name should not be empty");
    }

    #[tokio::test]
    async fn test_run_git_behind_ahead_no_upstream() {
        let (_dir, repo_path) = init_temp_repo();
        let (behind, ahead) = run_git_behind_ahead(&repo_path)
            .await
            .expect("behind/ahead");
        assert_eq!(behind, 0);
        assert_eq!(ahead, 0);
    }

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

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

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

        // Create an untracked file — not staged, not tracked by git.
        std::fs::write(
            repo_path.join("new_file.rs"),
            b"fn foo() {\n    bar();\n}\n",
        )
        .expect("write untracked file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        // The untracked file has 3 lines; unmodified tracked file contributes 0.
        assert_eq!(
            snap.stats.added, 3,
            "should count lines from untracked file"
        );
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert_eq!(
            snap.file_statuses.get("new_file.rs"),
            Some(&GitFileStatus::Added)
        );
    }

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

        // Create an untracked file containing a null byte (binary).
        std::fs::write(repo_path.join("binary.bin"), b"line1\nline2\x00\n")
            .expect("write binary file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 0,
            "binary untracked file should not be counted as added"
        );
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(
            snap.stats.huge_binary_file_count, 1,
            "binary untracked file should be surfaced as huge/binary"
        );
    }

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

        // Create an untracked file larger than MAX_UNTRACKED_SIZE (1 MiB).
        let size = usize::try_from(MAX_UNTRACKED_SIZE).unwrap() + 1;
        let mut content = Vec::with_capacity(size);
        content.resize(size, b'a');
        std::fs::write(repo_path.join("large.bin"), &content).expect("write large file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 0,
            "large untracked file should not be counted as added"
        );
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(
            snap.stats.huge_binary_file_count, 1,
            "large untracked file should be surfaced as huge/binary"
        );
    }

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

        // Create an untracked directory with a normal file (3 lines) and a
        // binary file. The collapsed `?? new_dir/` entry is enumerated and both
        // files contribute (the binary one via the huge/binary count).
        std::fs::create_dir_all(repo_path.join("new_dir")).expect("create directory");
        std::fs::write(
            repo_path.join("new_dir/a.rs"),
            b"fn foo() {\n    bar();\n}\n",
        )
        .expect("write normal file");
        std::fs::write(repo_path.join("new_dir/binary.bin"), b"line1\x00\n")
            .expect("write binary file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 3,
            "should count lines from directory files"
        );
        assert_eq!(snap.stats.removed, 0, "no removed lines");
        assert_eq!(
            snap.stats.huge_binary_file_count, 1,
            "binary file inside the directory surfaces as huge/binary"
        );
    }

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

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

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, MAX_UNTRACKED_FILES_COUNTED as i64,
            "only the first cap files are line-counted"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
    }

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

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

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

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 2,
            "gitignored file inside a directory is not counted"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
    }

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

        // A directory whose name contains glob metacharacters — the
        // `:(literal)` pathspec must match it literally.
        std::fs::create_dir_all(repo_path.join("we*ird?dir")).expect("create directory");
        std::fs::write(repo_path.join("we*ird?dir/x.rs"), b"xx\n").expect("write glob-dir file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 1,
            "glob chars in the directory path are literal"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
    }

    #[tokio::test]
    async fn test_run_git_worktree_snapshot_unborn_head() {
        // A freshly `git init`ed repo with no commits has no HEAD; numstat
        // fails, but the per-file statuses must still flow with (0, 0) stats.
        let dir = tempfile::tempdir().expect("create temp dir");
        let repo_path = dir.path().to_path_buf();
        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .status()
            .expect("git init");
        assert!(status.success());

        std::fs::write(repo_path.join("first.rs"), b"fn main() {}\n")
            .expect("write untracked file");

        let snap = run_git_worktree_snapshot(&repo_path)
            .await
            .expect("worktree snapshot");
        assert_eq!(
            snap.stats.added, 1,
            "untracked line counted despite unborn HEAD"
        );
        assert_eq!(snap.stats.removed, 0);
        assert_eq!(snap.stats.huge_binary_file_count, 0);
        assert!(snap.unborn_head, "unborn HEAD must be flagged");
        assert_eq!(
            snap.file_statuses.get("first.rs"),
            Some(&GitFileStatus::Added),
            "untracked file status flows on an unborn repo"
        );
    }

    #[tokio::test]
    async fn test_run_git_list_branches_single() {
        let (_dir, repo_path) = init_temp_repo();
        let out = run_git_command(&repo_path, &["branch", "--format=%(refname:short)"])
            .await
            .expect("list branches");
        let branches: Vec<String> = out.lines().map(ToString::to_string).collect();
        assert_eq!(branches.len(), 1, "single branch in new repo");
    }

    #[tokio::test]
    async fn test_run_git_switch_and_create_branch() {
        let (_dir, repo_path) = init_temp_repo();
        // Note the default branch name before creating a new one
        let default_branch = run_git_current_branch(&repo_path)
            .await
            .expect("current branch");

        // Create and switch to a new branch
        run_git_command(&repo_path, &["switch", "-c", "feature/test"])
            .await
            .expect("create branch");
        // Verify we're on the new branch
        let current = run_git_current_branch(&repo_path)
            .await
            .expect("current branch");
        assert_eq!(current, "feature/test");
        // Verify it appears in the branch list
        let out = run_git_command(&repo_path, &["branch", "--format=%(refname:short)"])
            .await
            .expect("list branches");
        let branches: Vec<String> = out.lines().map(ToString::to_string).collect();
        assert!(branches.contains(&"feature/test".to_string()));
        // Switch back to the default branch
        run_git_command(&repo_path, &["switch", default_branch.as_str()])
            .await
            .expect("switch back");
        let switched = run_git_current_branch(&repo_path)
            .await
            .expect("current branch");
        assert_eq!(switched, default_branch, "should be back on default branch");
    }

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

        // Without hash — should return HEAD's message
        let msg = run_git_commit_message(&repo_path, None)
            .await
            .expect("commit message without hash");
        assert_eq!(msg, "Initial commit");

        // Create a second commit
        std::fs::write(repo_path.join("test.txt"), b"line1\nline2\n").expect("write test file");
        let status = std::process::Command::new("git")
            .args(["add", "-A"])
            .current_dir(&repo_path)
            .status()
            .expect("git add");
        assert!(status.success());
        let status = std::process::Command::new("git")
            .args(["commit", "-m", "Second commit"])
            .current_dir(&repo_path)
            .status()
            .expect("git commit");
        assert!(status.success());

        // Get the second commit's hash
        let output = std::process::Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .expect("git rev-parse");
        let second_hash = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // With hash — should return that commit's message
        let msg = run_git_commit_message(&repo_path, Some(&second_hash))
            .await
            .expect("commit message with hash");
        assert_eq!(msg, "Second commit");

        // Without hash should now return HEAD (second commit)
        let msg = run_git_commit_message(&repo_path, None)
            .await
            .expect("commit message without hash");
        assert_eq!(msg, "Second commit");
    }

    #[tokio::test]
    async fn test_run_git_sync_no_remote() {
        let (_dir, repo_path) = init_temp_repo();
        // No remote configured — run_git_sync should return an error
        // from git pull --ff-only (no remote) rather than panicking.
        let result = run_git_sync(&repo_path).await;
        assert!(result.is_err(), "sync without remote should fail");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("remote")
                || err.to_string().contains("push")
                || err.to_string().contains("pull"),
            "error should mention remote/push/pull: {err}"
        );
    }

    // ── parse_new_files_from_porcelain — combined untracked + staged-as-new ──

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

    /// Verify that `parse_new_files_from_porcelain` correctly extracts untracked
    /// and staged-as-new file paths from git porcelain output, including C-quoted
    /// paths with special characters (tab, double-quote, non-ASCII).
    #[test]
    fn parse_new_files_from_porcelain_extracts_new_files() {
        let porcelain = PORCELAIN_INPUT;

        let files = parse_new_files_from_porcelain(porcelain);

        assert_eq!(files.len(), 9);
        assert!(files.contains(&"new_file.rs".to_string()));
        assert!(files.contains(&"another_new.py".to_string()));
        assert!(files.contains(&"staged_new.js".to_string()));
        assert!(files.contains(&"dir/untracked.txt".to_string()));
        assert!(files.contains(&"temp.log".to_string()));
        assert!(files.contains(&"staged_then_modified.js".to_string()));
        // C-quoted paths should be properly unquoted:
        assert!(files.contains(&"file\tname.rs".to_string()));
        assert!(files.contains(&"staged\"file.js".to_string()));
        // Backslash in filename (\\) unquotes to single backslash:
        assert!(files.contains(&"file\\backslash.rs".to_string()));
        // These should be excluded:
        assert!(!files.contains(&"modified.rs".to_string()));
        assert!(!files.contains(&"working_tree_only.txt".to_string()));
        assert!(!files.contains(&"working_tree_new.txt".to_string()));
    }

    /// Verify that porcelain parsing returns empty for both clean output
    /// (no new/untracked files) and malformed/truncated lines.
    #[test]
    fn parse_new_files_from_porcelain_returns_empty() {
        let porcelain = "\
M  modified.rs
 M working_tree_only.txt
D  deleted.rs
 A working_tree_new.txt
";

        let files = parse_new_files_from_porcelain(porcelain);
        assert!(
            files.is_empty(),
            "Should be empty when no new/untracked files"
        );

        // Malformed/truncated lines that match the filter but are too short
        // for path extraction should also produce empty results without panicking.
        let short_lines = ["A", "A ", "?? ", "??"];
        for &bad_line in &short_lines {
            let files = parse_new_files_from_porcelain(bad_line);
            assert!(
                files.is_empty(),
                "Malformed line {bad_line:?} should produce empty result, got {files:?}"
            );
        }

        // Also test the ??-only variant with the same short lines.
        for &bad_line in &short_lines {
            let files = parse_untracked_from_porcelain(bad_line);
            assert!(
                files.is_empty(),
                "Malformed line {bad_line:?} should produce empty result from ??-only parser, got {files:?}"
            );
        }
    }

    // ── parse_untracked_from_porcelain — ??-only untracked parsing ──

    /// Verify that `parse_untracked_from_porcelain` catches only `?? ` (truly
    /// untracked) entries and excludes `A ` (staged-as-new) files.
    #[test]
    fn parse_untracked_from_porcelain_returns_only_untracked() {
        let porcelain = PORCELAIN_INPUT;

        let files = parse_untracked_from_porcelain(porcelain);

        // Should include only ??-prefixed entries (6 total)
        assert_eq!(files.len(), 6);
        assert!(files.contains(&"new_file.rs".to_string()));
        assert!(files.contains(&"another_new.py".to_string()));
        assert!(files.contains(&"dir/untracked.txt".to_string()));
        assert!(files.contains(&"temp.log".to_string()));
        // C-quoted paths should be properly unquoted:
        assert!(files.contains(&"file\tname.rs".to_string()));
        assert!(files.contains(&"file\\backslash.rs".to_string()));
        // These should be excluded:
        assert!(!files.contains(&"staged_new.js".to_string()));
        assert!(!files.contains(&"staged_then_modified.js".to_string()));
        assert!(!files.contains(&"modified.rs".to_string()));
        assert!(!files.contains(&"working_tree_only.txt".to_string()));
        assert!(!files.contains(&"working_tree_new.txt".to_string()));
        assert!(!files.contains(&"staged\"file.js".to_string()));
    }

    /// Verify that `parse_untracked_from_porcelain` returns empty for output
    /// containing only staged-as-new or modified files (no ?? entries).
    #[test]
    fn parse_untracked_from_porcelain_no_untracked() {
        let porcelain = "\
M  modified.rs
A  staged_new.js
 M working_tree_only.txt
AM staged_then_modified.js
 A working_tree_new.txt
";

        let files = parse_untracked_from_porcelain(porcelain);
        assert!(
            files.is_empty(),
            "Should be empty when no `?? ` entries present"
        );
    }

    // ── parse_git_status_porcelain — per-file status map ─────────

    #[expect(clippy::too_many_lines)]
    #[test]
    fn test_parse_git_status_porcelain() {
        struct Case {
            /// Short label for failure messages.
            name: &'static str,
            /// Raw git status --porcelain output.
            input: &'static str,
            /// Expected entries: (path, Some(status)) asserts the file has that
            /// status; (path, None) asserts the file is absent from the map.
            /// An empty slice asserts the entire map is empty.
            expected: &'static [(&'static str, Option<GitFileStatus>)],
        }
        let cases: &[Case] = &[
            Case {
                name: "unstaged modified file",
                input: " M src/main.rs\n",
                expected: &[("src/main.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "staged added file",
                input: "A  new_file.rs\n",
                expected: &[("new_file.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "untracked file",
                input: "?? new_file.rs\n",
                expected: &[("new_file.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "staged and unstaged modified (MM)",
                input: "MM both.rs\n",
                expected: &[("both.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "staged added + unstaged modified (AM)",
                input: "AM partial.rs\n",
                expected: &[("partial.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename (old -> new)",
                input: "R  old.rs -> new.rs\n",
                expected: &[("new.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "rename with arrow in old path",
                input: "R  \"old -> name.rs\" -> \"new -> name.rs\"\n",
                expected: &[("new -> name.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "untracked directory (trailing slash stripped)",
                input: "?? new_dir/\n",
                expected: &[("new_dir", Some(GitFileStatus::Added))],
            },
            Case {
                name: "quoted path with spaces",
                input: " M \"path with spaces.rs\"\n",
                expected: &[("path with spaces.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "deleted file (unstaged) skipped",
                input: " D gone.rs\n",
                expected: &[],
            },
            Case {
                name: "deleted file (staged) skipped",
                input: "D  gone.rs\n",
                expected: &[],
            },
            Case {
                name: "clean (unrecognized status) not present",
                input: "   clean.rs\n",
                expected: &[("clean.rs", None)],
            },
            Case {
                name: "multiple entries same file — modified wins over added",
                input: "A  dup.rs\n M dup.rs\n",
                expected: &[("dup.rs", Some(GitFileStatus::Modified))],
            },
            Case {
                name: "multiple entries same file — added sticks",
                input: "?? dup.rs\nA  dup.rs\n",
                expected: &[("dup.rs", Some(GitFileStatus::Added))],
            },
            Case {
                name: "empty output",
                input: "",
                expected: &[],
            },
            Case {
                name: "mixed statuses",
                input: concat!(
                    " M src/main.rs\n",
                    "?? new_file.rs\n",
                    "A  staged.rs\n",
                    " D deleted.rs\n",
                ),
                expected: &[
                    ("src/main.rs", Some(GitFileStatus::Modified)),
                    ("new_file.rs", Some(GitFileStatus::Added)),
                    ("staged.rs", Some(GitFileStatus::Added)),
                    ("deleted.rs", None),
                ],
            },
        ];

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

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

    // ── parse_numstat_lines — numstat line parsing ──

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

    // ── run_git_discard — discard modifications ──

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

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

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

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

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

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

    /// Discard a new untracked file — removes it from the working tree.
    #[tokio::test]
    async fn test_run_git_discard_new_file() {
        let (_dir, repo_path) = init_temp_repo();

        // Create a new untracked file.
        let new_path = repo_path.join("new_file.rs");
        std::fs::write(&new_path, b"fn new() {}").expect("write new file");
        assert!(new_path.exists(), "new file should exist before discard");

        // Discard the untracked file.
        run_git_discard(&repo_path, "new_file.rs", DiscardTarget::File)
            .await
            .expect("run_git_discard should succeed");

        // File should be removed.
        assert!(
            !new_path.exists(),
            "new file should be removed after discard"
        );
    }

    /// Discard a directory with untracked content — recursively removes it.
    #[tokio::test]
    async fn test_run_git_discard_directory() {
        let (_dir, repo_path) = init_temp_repo();

        // Create a directory with an untracked file inside.
        let sub_dir = repo_path.join("subdir");
        std::fs::create_dir(&sub_dir).expect("create subdir");
        let sub_file = sub_dir.join("nested.rs");
        std::fs::write(&sub_file, b"fn nested() {}").expect("write nested file");
        assert!(sub_file.exists(), "nested file should exist before discard");

        // Discard the directory.
        run_git_discard(&repo_path, "subdir", DiscardTarget::Directory)
            .await
            .expect("run_git_discard should succeed");

        // Directory and its contents should be gone.
        assert!(
            !sub_dir.exists(),
            "directory should be removed after discard"
        );
    }

    /// Discard a clean file — succeeds as a no-op.
    #[tokio::test]
    async fn test_run_git_discard_clean_file() {
        let (_dir, repo_path) = init_temp_repo();

        let result = run_git_discard(&repo_path, "test.txt", DiscardTarget::File).await;
        assert!(result.is_ok(), "discarding a clean file should succeed");
    }

    // ── has_unstaged_changes ─────────────────────────────────────────

    /// Empty, fully-staged, unstaged, dual-status, untracked, mixed, and
    /// trailing-newline porcelain inputs.
    #[test]
    fn has_unstaged_changes_cases() {
        let cases: &[(&str, &str, bool)] = &[
            ("empty_string", "", false),
            ("empty_lines", "\n\n", false),
            ("fully_staged_modified", "M  Cargo.toml\n", false),
            ("fully_staged_added", "A  src/lib.rs\n", false),
            (
                "fully_staged_mixed",
                "M  Cargo.toml\nA  src/lib.rs\nD  old.rs\n",
                false,
            ),
            ("unstaged_modified", " M src/lib.rs\n", true),
            ("unstaged_deleted", " D src/old.rs\n", true),
            ("dual_status_modified", "MM src/lib.rs\n", true),
            ("dual_status_added", "AM src/new.rs\n", true),
            ("dual_status_deleted", "MD src/old.rs\n", true),
            ("untracked_file", "?? new_file.rs\n", true),
            ("untracked_directory", "?? dir/untracked.txt\n", true),
            (
                "mixed_only_staged",
                "M  Cargo.toml\nA  src/main.rs\n",
                false,
            ),
            (
                "mixed_staged_and_unstaged",
                "M  Cargo.toml\n M src/main.rs\n?? new.rs\n",
                true,
            ),
            ("trailing_newline_unstaged", " M file.rs\n", true),
            ("trailing_newline_staged", "M  file.rs\n", false),
        ];
        for (name, input, expected) in cases {
            assert_eq!(has_unstaged_changes(input), *expected, "case: {name}");
        }
    }
}