mahbot 0.4.0

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
//! 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::diff_parse`].

use anyhow::Context;
use std::collections::HashSet;
use std::path::Path;
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_diff_stats`]
/// and the diff page's untracked-file display.
///
/// Files larger than this are skipped to avoid UI lag on the periodic
/// refreshes (dashboard tick every second, diff page every 5 seconds).
pub(crate) const MAX_UNTRACKED_SIZE: u64 = 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,
}

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;
    };
    if content.contains(&0) {
        return UntrackedFileRead::Binary;
    }
    // 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.
    String::from_utf8(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()
}

/// 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.
///
/// Callers should add further configuration (args, current_dir, stdio, etc.)
/// and then spawn or execute the command.
fn git_command() -> tokio::process::Command {
    let mut cmd = tokio::process::Command::new("git");
    apply_safe_env(&mut cmd);
    cmd.env("LC_ALL", "C");
    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.
pub(crate) async fn run_git_output(
    repo_path: &Path,
    args: &[&str],
) -> anyhow::Result<std::process::Output> {
    let mut cmd = git_command();
    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())
}

/// Run a git command with data piped to stdin.
///
/// Like [`run_git_output`], but pipes the given lines to the subprocess's stdin
/// before collecting output. Returns the raw [`std::process::Output`] so
/// callers can interpret exit codes as appropriate for their use case.
///
/// The `name` parameter is used to identify the subcommand in error messages
/// (e.g., `"check-ignore"`).
///
/// **Environment sanitization**: Same as [`run_git_output`] — the subprocess
/// environment is cleared and re-populated with only a safe set of variables.
async fn run_git_with_stdin(
    repo_path: &Path,
    args: &[&str],
    stdin_lines: &[String],
    name: &str,
) -> anyhow::Result<std::process::Output> {
    use std::process::Stdio;
    use tokio::io::AsyncWriteExt;

    let mut cmd = git_command();
    cmd.args(args)
        .current_dir(repo_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let mut child = cmd
        .spawn()
        .with_context(|| format!("Failed to spawn git {name}"))?;

    // Write all lines to stdin, then close it.
    let mut stdin = child
        .stdin
        .take()
        .with_context(|| format!("Failed to capture stdin for git {name}"))?;
    if !stdin_lines.is_empty() {
        let input = stdin_lines.join("\n");
        stdin
            .write_all(input.as_bytes())
            .await
            .with_context(|| format!("Failed to write to git {name} stdin"))?;
    }
    drop(stdin);

    let output = child
        .wait_with_output()
        .await
        .with_context(|| format!("Failed to wait for git {name}"))?;

    Ok(output)
}

/// Run `git check-ignore --stdin` with the given file paths.
/// Pipes paths via stdin and returns the set of paths that are ignored.
///
/// Exit code 0 means some paths matched (output lists them, one per line).
/// Exit code 1 means no paths were ignored (not a failure — returns empty set).
/// Any other exit code is treated as an error.
pub async fn run_git_check_ignore(
    repo_path: &Path,
    paths: &[String],
) -> anyhow::Result<HashSet<String>> {
    let output = run_git_with_stdin(
        repo_path,
        &["check-ignore", "--stdin"],
        paths,
        "check-ignore",
    )
    .await?;

    // Exit code 1 means "no files ignored" — not a failure, return empty set.
    if output.status.code() == Some(1) {
        return Ok(HashSet::new());
    }

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Git check-ignore failed: {stderr}");
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let ignored: HashSet<String> = stdout.lines().map(ToString::to_string).collect();
    Ok(ignored)
}

/// 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.
///
/// # Example
///
/// ```ignore
/// assert!(!has_unstaged_changes(""));
/// assert!(!has_unstaged_changes("M  Cargo.toml\nA  src/lib.rs\n"));
/// assert!(has_unstaged_changes(" M src/lib.rs"));
/// assert!(has_unstaged_changes("?? new_file.txt"));
/// assert!(has_unstaged_changes("MM src/lib.rs"));
/// ```
#[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,
    })
}

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

/// Run `git diff --numstat HEAD` and return the total added/removed lines.
///
/// Also counts lines from untracked (new) files, since `git diff HEAD` only
/// considers tracked files. Untracked files larger than
/// [`MAX_UNTRACKED_SIZE`] or detected as binary are silently skipped to
/// avoid UI lag (this function runs on the every-second dashboard refresh
/// tick).
///
/// Delegates to `parse_numstat` for tracked file diffs and
/// `parse_untracked_from_porcelain` for untracked file enumeration.
pub async fn run_git_diff_stats(repo_path: &Path) -> anyhow::Result<(i64, i64)> {
    let (mut added, removed) = parse_numstat(repo_path, &["HEAD"]).await?;

    // Enumerate untracked files and count their lines.
    // `git diff HEAD` only considers tracked files, so new/untracked files are
    // invisible to the numstat above. We read them from disk and count their
    // lines — all lines in an untracked file are "added".
    let status_output = match run_git_status(repo_path).await {
        Ok(output) => output,
        Err(e) => {
            warn!("Failed to run git status for untracked file counting: {e}");
            return Ok((added, removed));
        }
    };

    let untracked = parse_untracked_from_porcelain(&status_output);

    for path in &untracked {
        if let UntrackedFileRead::Text(text) =
            read_untracked_file(&repo_path.join(path), MAX_UNTRACKED_SIZE).await
        {
            // All lines in an untracked file count as added lines
            #[expect(clippy::cast_possible_wrap)]
            let line_count = text.lines().count() as i64;
            added += line_count;
        }
    }

    Ok((added, removed))
}

/// 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("?? "))
}

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

    // ── 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_diff_stats_clean_tree() {
        let (_dir, repo_path) = init_temp_repo();
        let (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        assert_eq!(added, 0);
        assert_eq!(removed, 0);
    }

    #[tokio::test]
    async fn test_run_git_diff_stats_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 (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        assert_eq!(added, 2, "two lines added (modified + new line)");
        assert_eq!(removed, 1, "one line removed (line2)");
    }

    #[tokio::test]
    async fn test_run_git_diff_stats_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 (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        // The untracked file has 3 lines; unmodified tracked file contributes 0.
        assert_eq!(added, 3, "should count lines from untracked file");
        assert_eq!(removed, 0, "no removed lines");
    }

    #[tokio::test]
    async fn test_run_git_diff_stats_skips_binary_untracked() {
        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 (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        assert_eq!(
            added, 0,
            "binary untracked file should not be counted as added"
        );
        assert_eq!(removed, 0, "no removed lines");
    }

    #[tokio::test]
    async fn test_run_git_diff_stats_skips_large_untracked() {
        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 (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        assert_eq!(
            added, 0,
            "large untracked file should not be counted as added"
        );
        assert_eq!(removed, 0, "no removed lines");
    }

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

        // Create an untracked directory (not a regular file).
        std::fs::create_dir(repo_path.join("new_dir")).expect("create directory");

        let (added, removed) = run_git_diff_stats(&repo_path).await.expect("diff stats");
        assert_eq!(
            added, 0,
            "untracked directory should not be counted as added"
        );
        assert_eq!(removed, 0, "no removed lines");
    }

    #[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_numstat_lines — numstat line parsing ──

    /// Normal file modifications.
    #[test]
    fn parse_numstat_lines_normal() {
        let output = "10\t3\tsrc/main.rs\n0\t1\tsrc/lib.rs\n42\t7\tCargo.toml\n";
        let entries = parse_numstat_lines(output);
        assert_eq!(entries.len(), 3);
        assert_eq!(
            entries[0],
            NumstatEntry {
                additions: Some(10),
                deletions: Some(3),
                path: "src/main.rs".to_string()
            }
        );
        assert_eq!(
            entries[1],
            NumstatEntry {
                additions: Some(0),
                deletions: Some(1),
                path: "src/lib.rs".to_string()
            }
        );
        assert_eq!(
            entries[2],
            NumstatEntry {
                additions: Some(42),
                deletions: Some(7),
                path: "Cargo.toml".to_string()
            }
        );
    }

    /// Binary files are represented as (None, None).
    #[test]
    fn parse_numstat_lines_binary() {
        let output = "-\t-\timage.png\n42\t7\tsrc/main.rs\n";
        let entries = parse_numstat_lines(output);
        assert_eq!(entries.len(), 2);
        assert_eq!(
            entries[0],
            NumstatEntry {
                additions: None,
                deletions: None,
                path: "image.png".to_string()
            }
        );
        assert_eq!(
            entries[1],
            NumstatEntry {
                additions: Some(42),
                deletions: Some(7),
                path: "src/main.rs".to_string()
            }
        );
    }

    /// Empty lines and malformed lines are silently skipped.
    #[test]
    fn parse_numstat_lines_skips_malformed() {
        let output = "\n\n10\t3\tsrc/main.rs\n\t\t\nnot-enough-fields\n";
        let entries = parse_numstat_lines(output);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0],
            NumstatEntry {
                additions: Some(10),
                deletions: Some(3),
                path: "src/main.rs".to_string()
            }
        );
    }

    /// Empty output produces an empty vector.
    #[test]
    fn parse_numstat_lines_empty() {
        assert!(parse_numstat_lines("").is_empty());
        assert!(parse_numstat_lines("\n\n\n").is_empty());
    }

    // ── run_git_with_stdin — stdin-piping helper ──

    /// Verify that stdin piping works by hashing content via stdin.
    #[tokio::test]
    async fn test_run_git_with_stdin_pipes_stdin() {
        let (_dir, repo_path) = init_temp_repo();

        let output = run_git_with_stdin(
            &repo_path,
            &["hash-object", "--stdin"],
            &["hello world".to_string()],
            "hash-object",
        )
        .await
        .unwrap();

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // git hash-object --stdin outputs the SHA-1 hash followed by a newline
        assert!(!stdout.trim().is_empty(), "Expected a non-empty hash");
    }

    /// Verify empty stdin lines produce a valid (empty) output.
    #[tokio::test]
    async fn test_run_git_with_stdin_empty_lines() {
        let (_dir, repo_path) = init_temp_repo();

        let output = run_git_with_stdin(
            &repo_path,
            &["hash-object", "--stdin"],
            &[] as &[String],
            "hash-object",
        )
        .await
        .unwrap();

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // hash-object with empty/absent stdin still outputs a hash (empty blob hash)
        assert!(
            !stdout.trim().is_empty(),
            "Expected a non-empty hash for empty input"
        );
    }

    // ── run_git_check_ignore — .gitignore matching ──

    /// A path matching .gitignore should be reported as ignored.
    #[tokio::test]
    async fn test_run_git_check_ignore_matches_ignored_path() {
        let (_dir, repo_path) = init_temp_repo();

        std::fs::write(repo_path.join(".gitignore"), "*.log\n").unwrap();

        let ignored = run_git_check_ignore(&repo_path, &["test.log".to_string()])
            .await
            .unwrap();
        assert!(
            ignored.contains("test.log"),
            "test.log should be ignored by *.log pattern"
        );
    }

    /// A path not matching .gitignore should return an empty set.
    #[tokio::test]
    async fn test_run_git_check_ignore_non_ignored_path() {
        let (_dir, repo_path) = init_temp_repo();

        std::fs::write(repo_path.join(".gitignore"), "*.log\n").unwrap();

        let ignored = run_git_check_ignore(&repo_path, &["test.txt".to_string()])
            .await
            .unwrap();
        assert!(
            ignored.is_empty(),
            "test.txt should not be ignored by *.log pattern"
        );
    }

    /// Empty path list should return an empty set.
    #[tokio::test]
    async fn test_run_git_check_ignore_empty_paths() {
        let (_dir, repo_path) = init_temp_repo();

        let ignored = run_git_check_ignore(&repo_path, &[]).await.unwrap();
        assert!(
            ignored.is_empty(),
            "Empty path list should produce empty result"
        );
    }

    // ── 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 porcelain has no unstaged changes.
    #[test]
    fn has_unstaged_changes_empty() {
        assert!(!has_unstaged_changes(""));
        assert!(!has_unstaged_changes("\n\n"));
    }

    /// Fully-staged-only entries are not unstaged.
    #[test]
    fn has_unstaged_changes_fully_staged() {
        assert!(!has_unstaged_changes("M  Cargo.toml\n"));
        assert!(!has_unstaged_changes("A  src/lib.rs\n"));
        assert!(!has_unstaged_changes(
            "M  Cargo.toml\nA  src/lib.rs\nD  old.rs\n"
        ));
    }

    /// Unstaged modifications (space in index column) are detected.
    #[test]
    fn has_unstaged_changes_unstaged_modifications() {
        assert!(has_unstaged_changes(" M src/lib.rs\n"));
        assert!(has_unstaged_changes(" D src/old.rs\n"));
    }

    /// Dual-status entries (staged + unstaged) are detected.
    #[test]
    fn has_unstaged_changes_dual_status() {
        assert!(has_unstaged_changes("MM src/lib.rs\n"));
        assert!(has_unstaged_changes("AM src/new.rs\n"));
        assert!(has_unstaged_changes("MD src/old.rs\n"));
    }

    /// Untracked files (??) are detected.
    #[test]
    fn has_unstaged_changes_untracked() {
        assert!(has_unstaged_changes("?? new_file.rs\n"));
        assert!(has_unstaged_changes("?? dir/untracked.txt\n"));
    }

    /// Mixed porcelain output is parsed correctly.
    #[test]
    fn has_unstaged_changes_mixed() {
        // Only staged — no unstaged.
        assert!(!has_unstaged_changes("M  Cargo.toml\nA  src/main.rs\n"));

        // Staged + unstaged — has unstaged.
        assert!(has_unstaged_changes(
            "M  Cargo.toml\n M src/main.rs\n?? new.rs\n"
        ));
    }

    /// Whitespace trimming — trailing newline handled.
    #[test]
    fn has_unstaged_changes_trailing_newline() {
        assert!(has_unstaged_changes(" M file.rs\n"));
        assert!(!has_unstaged_changes("M  file.rs\n"));
    }
}