yoyo-agent 0.1.4

A coding agent that evolves itself. Born as 200 lines of Rust, growing up in public.
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
//! Git-related functions: staging, committing, branch detection, and `/git` subcommands.

use crate::format::*;

/// Run a git command with the given args.
/// Returns `Ok(stdout_trimmed)` on success, `Err(stderr_trimmed)` on failure.
/// This is the common path for most git invocations — use raw `Command` only
/// when you need the full `Output` struct (e.g., for separate stdout+stderr handling).
pub fn run_git(args: &[&str]) -> Result<String, String> {
    match std::process::Command::new("git").args(args).output() {
        Ok(output) if output.status.success() => {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        }
        Ok(output) => Err(String::from_utf8_lossy(&output.stderr).trim().to_string()),
        Err(e) => Err(format!("git not found: {e}")),
    }
}

/// Get the current git branch name, if we're in a git repo.
pub fn git_branch() -> Option<String> {
    run_git(&["rev-parse", "--abbrev-ref", "HEAD"]).ok()
}

/// Get staged changes (git diff --cached).
/// Returns None if git fails, Some("") if nothing staged, or Some(diff) with the diff text.
pub fn get_staged_diff() -> Option<String> {
    run_git(&["diff", "--cached"]).ok()
}

/// Run `git commit -m "<message>"` and return (success, output_text).
pub fn run_git_commit(message: &str) -> (bool, String) {
    match std::process::Command::new("git")
        .args(["commit", "-m", message])
        .output()
    {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            let text = if stdout.is_empty() { stderr } else { stdout };
            (output.status.success(), text)
        }
        Err(e) => (false, format!("error: {e}")),
    }
}

/// Generate a conventional commit message from a diff using simple heuristics.
/// This is a local, token-free approach — no AI calls needed.
pub fn generate_commit_message(diff: &str) -> String {
    let mut files_changed: Vec<String> = Vec::new();
    let mut insertions = 0usize;
    let mut deletions = 0usize;

    for line in diff.lines() {
        if let Some(path) = line.strip_prefix("+++ b/") {
            files_changed.push(path.to_string());
        } else if line.starts_with('+') && !line.starts_with("+++") {
            insertions += 1;
        } else if line.starts_with('-') && !line.starts_with("---") {
            deletions += 1;
        }
    }

    // Determine type prefix based on file paths
    let prefix = if files_changed.iter().any(|f| f.contains("test")) {
        "test"
    } else if files_changed
        .iter()
        .any(|f| f.ends_with(".md") || f.starts_with("docs/"))
    {
        "docs"
    } else if files_changed
        .iter()
        .any(|f| f.starts_with(".github/") || f.starts_with("scripts/") || f == "Cargo.toml")
    {
        "chore"
    } else if deletions > insertions * 2 {
        "refactor"
    } else {
        "feat"
    };

    // Build a concise scope from changed files
    let scope = if files_changed.len() == 1 {
        let f = &files_changed[0];
        let name = f.rsplit('/').next().unwrap_or(f);
        // Strip extension for scope
        name.split('.').next().unwrap_or(name).to_string()
    } else if files_changed.len() <= 3 {
        files_changed
            .iter()
            .map(|f| {
                let name = f.rsplit('/').next().unwrap_or(f);
                name.split('.').next().unwrap_or(name).to_string()
            })
            .collect::<Vec<_>>()
            .join(", ")
    } else {
        format!("{} files", files_changed.len())
    };

    let summary = if deletions == 0 && insertions > 0 {
        "add changes"
    } else if insertions == 0 && deletions > 0 {
        "remove code"
    } else {
        "update code"
    };

    format!("{prefix}({scope}): {summary}")
}

/// Apply ANSI colors to a unified diff string, line by line.
///
/// - Lines starting with `+` (but not `+++`): green (additions)
/// - Lines starting with `-` (but not `---`): red (deletions)
/// - Lines starting with `@@`: cyan (hunk headers)
/// - Lines starting with `diff --git`, `---`, `+++`: bold (file headers)
/// - All other lines: unchanged
pub fn colorize_diff(diff: &str) -> String {
    if diff.is_empty() {
        return String::new();
    }

    let mut result = String::with_capacity(diff.len() * 2);
    for line in diff.lines() {
        if line.starts_with("diff --git") || line.starts_with("---") || line.starts_with("+++") {
            result.push_str(&format!("{BOLD}{line}{RESET}\n"));
        } else if line.starts_with("@@") {
            result.push_str(&format!("{CYAN}{line}{RESET}\n"));
        } else if line.starts_with('+') {
            result.push_str(&format!("{GREEN}{line}{RESET}\n"));
        } else if line.starts_with('-') {
            result.push_str(&format!("{RED}{line}{RESET}\n"));
        } else {
            result.push_str(line);
            result.push('\n');
        }
    }
    // Remove trailing newline if the original didn't end with one
    if !diff.ends_with('\n') && result.ends_with('\n') {
        result.pop();
    }
    result
}

/// Format `git stash list` output with colored entries.
///
/// Each line looks like: `stash@{0}: WIP on main: abc1234 commit message`
/// We dim the date/index part and bold the description.
pub fn format_stash_list(raw: &str) -> String {
    if raw.is_empty() {
        return format!("{DIM}  (no stashes){RESET}\n");
    }

    let mut result = String::with_capacity(raw.len() * 2);
    for line in raw.lines() {
        // Lines look like: stash@{N}: <type> on <branch>: <message>
        if let Some(colon_pos) = line.find(':') {
            let stash_ref = &line[..colon_pos];
            let rest = &line[colon_pos..];
            // Second colon separates "WIP on branch" from the commit message
            if let Some(second_colon) = rest[1..].find(':') {
                let middle = &rest[..second_colon + 1];
                let message = &rest[second_colon + 1..];
                result.push_str(&format!(
                    "  {YELLOW}{stash_ref}{RESET}{DIM}{middle}{RESET}:{BOLD}{message}{RESET}\n"
                ));
            } else {
                result.push_str(&format!("  {YELLOW}{stash_ref}{RESET}{DIM}{rest}{RESET}\n"));
            }
        } else {
            result.push_str(&format!("  {DIM}{line}{RESET}\n"));
        }
    }
    result
}

/// Represents a parsed `/git` subcommand.
#[derive(Debug, PartialEq)]
pub enum GitSubcommand {
    /// `/git status` — run `git status --short`
    Status,
    /// `/git log [n]` — show last n commits (default 5)
    Log(usize),
    /// `/git add <path>` — stage files
    Add(String),
    /// `/git stash` or `/git stash push` — stash changes
    Stash,
    /// `/git stash pop` — pop stashed changes
    StashPop,
    /// `/git stash list` — list all stash entries
    StashList,
    /// `/git stash drop [n]` — drop a stash entry (default: stash@{0})
    StashDrop(Option<usize>),
    /// `/git stash show [n]` — show diff of a stash entry (default: stash@{0})
    StashShow(Option<usize>),
    /// `/git diff` — show diff (unstaged by default, `--cached` for staged)
    Diff { cached: bool },
    /// `/git branch` — list branches or create/switch to a new one
    Branch(Option<String>),
    /// Invalid or missing subcommand — show help
    Help,
}

/// Parse the argument string after `/git` into a `GitSubcommand`.
pub fn parse_git_args(arg: &str) -> GitSubcommand {
    let arg = arg.trim();
    if arg.is_empty() {
        return GitSubcommand::Help;
    }

    let parts: Vec<&str> = arg.splitn(3, char::is_whitespace).collect();
    match parts[0].to_lowercase().as_str() {
        "status" => GitSubcommand::Status,
        "log" => {
            let n = parts
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .unwrap_or(5);
            GitSubcommand::Log(n)
        }
        "add" => {
            if parts.len() < 2 || parts[1].trim().is_empty() {
                GitSubcommand::Help
            } else {
                // Rejoin remaining parts as the path (handles spaces in filenames via quoting at shell level)
                let path = parts[1..].join(" ");
                GitSubcommand::Add(path)
            }
        }
        "stash" => {
            if parts.len() >= 2 {
                match parts[1].to_lowercase().as_str() {
                    "pop" => GitSubcommand::StashPop,
                    "list" => GitSubcommand::StashList,
                    "show" => {
                        let n = parts.get(2).and_then(|s| s.parse::<usize>().ok());
                        GitSubcommand::StashShow(n)
                    }
                    "drop" => {
                        let n = parts.get(2).and_then(|s| s.parse::<usize>().ok());
                        GitSubcommand::StashDrop(n)
                    }
                    "push" => GitSubcommand::Stash,
                    _ => GitSubcommand::Stash,
                }
            } else {
                GitSubcommand::Stash
            }
        }
        "diff" => {
            let cached =
                parts.len() >= 2 && parts[1].trim_start_matches('-').to_lowercase() == "cached";
            GitSubcommand::Diff { cached }
        }
        "branch" => {
            if parts.len() >= 2 && !parts[1].trim().is_empty() {
                let name = parts[1..].join(" ");
                GitSubcommand::Branch(Some(name))
            } else {
                GitSubcommand::Branch(None)
            }
        }
        _ => GitSubcommand::Help,
    }
}

/// Execute a `/git` subcommand directly (no AI, no tokens).
pub fn run_git_subcommand(subcmd: &GitSubcommand) {
    match subcmd {
        GitSubcommand::Status => match run_git(&["status", "--short"]) {
            Ok(text) if text.is_empty() => {
                println!("{DIM}  (clean working tree){RESET}\n");
            }
            Ok(text) => {
                println!("{DIM}{text}{RESET}");
            }
            Err(_) => eprintln!("{RED}  error: not in a git repository{RESET}\n"),
        },
        GitSubcommand::Log(n) => {
            let n_str = n.to_string();
            match run_git(&["log", "--oneline", "-n", &n_str]) {
                Ok(text) if text.is_empty() => {
                    println!("{DIM}  (no commits yet){RESET}\n");
                }
                Ok(text) => {
                    println!("{DIM}{text}{RESET}");
                }
                Err(_) => eprintln!("{RED}  error: not in a git repository{RESET}\n"),
            }
        }
        GitSubcommand::Add(path) => match run_git(&["add", path]) {
            Ok(_) => {
                println!("{GREEN}  ✓ staged: {path}{RESET}\n");
            }
            Err(e) => {
                if e.contains("git not found") {
                    eprintln!("{RED}  error: git not found{RESET}\n");
                } else {
                    eprintln!("{RED}  error: {e}{RESET}\n");
                }
            }
        },
        GitSubcommand::Stash => match run_git(&["stash", "push"]) {
            Ok(text) => {
                println!("{GREEN}{text}{RESET}\n");
            }
            Err(e) => {
                if e.contains("git not found") {
                    eprintln!("{RED}  error: git not found{RESET}\n");
                } else {
                    eprintln!("{RED}  error: {e}{RESET}\n");
                }
            }
        },
        GitSubcommand::StashPop => match run_git(&["stash", "pop"]) {
            Ok(text) => {
                println!("{GREEN}{text}{RESET}\n");
            }
            Err(e) => {
                if e.contains("git not found") {
                    eprintln!("{RED}  error: git not found{RESET}\n");
                } else {
                    eprintln!("{RED}  error: {e}{RESET}\n");
                }
            }
        },
        GitSubcommand::StashList => match run_git(&["stash", "list"]) {
            Ok(text) => {
                print!("{}", format_stash_list(&text));
            }
            Err(e) => {
                if e.contains("git not found") {
                    eprintln!("{RED}  error: git not found{RESET}\n");
                } else {
                    eprintln!("{RED}  error: {e}{RESET}\n");
                }
            }
        },
        GitSubcommand::StashDrop(n) => {
            let stash_ref = match n {
                Some(idx) => format!("stash@{{{idx}}}"),
                None => "stash@{0}".to_string(),
            };
            match run_git(&["stash", "drop", &stash_ref]) {
                Ok(text) => {
                    println!("{GREEN}{text}{RESET}\n");
                }
                Err(e) => {
                    if e.contains("git not found") {
                        eprintln!("{RED}  error: git not found{RESET}\n");
                    } else {
                        eprintln!("{RED}  error: {e}{RESET}\n");
                    }
                }
            }
        }
        GitSubcommand::StashShow(n) => {
            let stash_ref = match n {
                Some(idx) => format!("stash@{{{idx}}}"),
                None => "stash@{0}".to_string(),
            };
            match run_git(&["stash", "show", "-p", &stash_ref]) {
                Ok(text) if text.is_empty() => {
                    println!("{DIM}  (empty stash){RESET}\n");
                }
                Ok(text) => {
                    println!("{}", colorize_diff(&text));
                }
                Err(e) => {
                    if e.contains("git not found") {
                        eprintln!("{RED}  error: git not found{RESET}\n");
                    } else {
                        eprintln!("{RED}  error: {e}{RESET}\n");
                    }
                }
            }
        }
        GitSubcommand::Diff { cached } => {
            let args: Vec<&str> = if *cached {
                vec!["diff", "--cached"]
            } else {
                vec!["diff"]
            };
            match run_git(&args) {
                Ok(text) if text.is_empty() => {
                    let scope = if *cached { "staged" } else { "unstaged" };
                    println!("{DIM}  (no {scope} changes){RESET}\n");
                }
                Ok(text) => {
                    println!("{text}");
                }
                Err(_) => eprintln!("{RED}  error: not in a git repository{RESET}\n"),
            }
        }
        GitSubcommand::Branch(name) => match name {
            Some(branch_name) => match run_git(&["checkout", "-b", branch_name]) {
                Ok(_) => {
                    println!("{GREEN}  ✓ switched to new branch '{branch_name}'{RESET}\n");
                }
                Err(e) => {
                    if e.contains("git not found") {
                        eprintln!("{RED}  error: git not found{RESET}\n");
                    } else {
                        eprintln!("{RED}  error: {e}{RESET}\n");
                    }
                }
            },
            None => match run_git(&["branch", "--list", "-a"]) {
                Ok(text) if text.is_empty() => {
                    println!("{DIM}  (no branches yet){RESET}\n");
                }
                Ok(text) => {
                    // Current branch line starts with "* ", highlight it
                    for line in text.lines() {
                        if line.starts_with("* ") {
                            println!("{GREEN}{line}{RESET}");
                        } else {
                            println!("{DIM}{line}{RESET}");
                        }
                    }
                    println!();
                }
                Err(_) => eprintln!("{RED}  error: not in a git repository{RESET}\n"),
            },
        },
        GitSubcommand::Help => {
            println!("{DIM}  usage: /git status             Show working tree status");
            println!("         /git log [n]             Show last n commits (default: 5)");
            println!("         /git add <path>          Stage files for commit");
            println!("         /git diff [--cached]     Show diff (unstaged or staged changes)");
            println!("         /git branch [name]       List branches or create & switch");
            println!("         /git stash               Stash uncommitted changes");
            println!("         /git stash pop           Restore stashed changes");
            println!("         /git stash list          List all stash entries");
            println!("         /git stash show [n]      Show diff of stash entry n");
            println!("         /git stash drop [n]      Drop stash entry n{RESET}\n");
        }
    }
}

/// Detect the base branch for PR creation (main or master).
/// Returns "main" if it exists, otherwise "master", falling back to "main".
pub fn detect_base_branch() -> String {
    if run_git(&["rev-parse", "--verify", "main"]).is_ok() {
        return "main".to_string();
    }
    if run_git(&["rev-parse", "--verify", "master"]).is_ok() {
        return "master".to_string();
    }
    "main".to_string()
}

/// Get the diff between the current branch and a base branch.
/// Returns None if git fails, Some(diff) with the diff text otherwise.
pub fn get_branch_diff(base: &str) -> Option<String> {
    let merge_base_sha = run_git(&["merge-base", base, "HEAD"]).ok()?;
    run_git(&["diff", &merge_base_sha, "HEAD"]).ok()
}

/// Get the list of commits on the current branch since diverging from the base branch.
/// Returns None if git fails, Some(commits) with one-line commit summaries otherwise.
pub fn get_branch_commits(base: &str) -> Option<String> {
    let range = format!("{base}..HEAD");
    run_git(&["log", "--oneline", &range]).ok()
}

/// Build a prompt for the AI to generate a PR title and description.
/// The AI output should be in the format:
/// ```
/// TITLE: <one-line title>
/// ---
/// <markdown description body>
/// ```
pub fn build_pr_description_prompt(branch: &str, base: &str, commits: &str, diff: &str) -> String {
    // Truncate diff if it's very large to stay within context limits
    let max_diff_chars = 15_000;
    let diff_preview = if diff.len() > max_diff_chars {
        let truncated = &diff[..max_diff_chars];
        format!(
            "{truncated}\n\n... (diff truncated, {} more chars)",
            diff.len() - max_diff_chars
        )
    } else {
        diff.to_string()
    };

    format!(
        r#"Generate a pull request title and description for the following changes.

Branch: {branch}{base}

Commits:
{commits}

Diff:
```
{diff_preview}
```

Respond in EXACTLY this format (no extra text before or after):

TITLE: <concise PR title using conventional commit style>
---
<markdown PR description body>

The description should include:
- A brief summary of what changed and why
- Key changes as bullet points
- Any notable implementation details

Keep it concise but informative."#
    )
}

/// Parse the AI's response into a PR title and body.
/// Expects format: "TITLE: ...\n---\n..."
pub fn parse_pr_description(response: &str) -> Option<(String, String)> {
    let response = response.trim();

    // Find the TITLE: line
    let title_line = response.lines().find(|l| l.starts_with("TITLE:"))?;
    let title = title_line.strip_prefix("TITLE:")?.trim().to_string();

    if title.is_empty() {
        return None;
    }

    // Find the --- separator and take everything after it
    let separator_pos = response.find("\n---\n")?;
    let body = response[separator_pos + 5..].trim().to_string();

    Some((title, body))
}

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

    #[test]
    fn test_run_git_valid_args() {
        // `git --version` should always succeed
        let result = run_git(&["--version"]);
        assert!(result.is_ok(), "git --version should succeed");
        let stdout = result.unwrap();
        assert!(
            stdout.contains("git version"),
            "Output should contain 'git version', got: {stdout}"
        );
    }

    #[test]
    fn test_run_git_invalid_args_returns_err() {
        // `git --no-such-flag-exists` should fail
        let result = run_git(&["--no-such-flag-exists"]);
        assert!(
            result.is_err(),
            "Invalid git flag should return Err, got: {:?}",
            result
        );
    }

    #[test]
    fn test_run_git_trims_output() {
        // git --version output shouldn't have trailing newlines
        let result = run_git(&["--version"]).unwrap();
        assert_eq!(result, result.trim(), "Output should be trimmed");
    }

    #[test]
    fn test_get_staged_diff_runs() {
        // Should not panic; returns None if not in git repo (e.g. cargo-mutants temp dir)
        let result = get_staged_diff();
        // We don't assert Some — outside a git repo this returns None, and that's correct
        if let Some(diff) = result {
            // If we are in a git repo, the diff is a string (possibly empty)
            assert!(diff.len() < 10_000_000, "Diff should be reasonable size");
        }
    }

    #[test]
    fn test_generate_commit_message_basic() {
        let diff = "\
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,5 @@
+// new comment
+use std::io;
 fn main() {
     println!(\"hello\");
 }
";
        let msg = generate_commit_message(diff);
        // Should produce a conventional commit format: type(scope): description
        assert!(msg.contains('('), "Should have scope: {msg}");
        assert!(msg.contains("):"), "Should have conventional format: {msg}");
        assert!(msg.contains("main"), "Scope should mention 'main': {msg}");
    }

    #[test]
    fn test_generate_commit_message_docs() {
        let diff = "\
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,2 +1,3 @@
 # Project
+New docs line
";
        let msg = generate_commit_message(diff);
        assert!(
            msg.starts_with("docs("),
            "Markdown changes should use docs prefix: {msg}"
        );
    }

    #[test]
    fn test_generate_commit_message_multiple_files() {
        let diff = "\
diff --git a/src/a.rs b/src/a.rs
--- a/src/a.rs
+++ b/src/a.rs
@@ -1 +1,2 @@
+// change a
diff --git a/src/b.rs b/src/b.rs
--- a/src/b.rs
+++ b/src/b.rs
@@ -1 +1,2 @@
+// change b
diff --git a/src/c.rs b/src/c.rs
--- a/src/c.rs
+++ b/src/c.rs
@@ -1 +1,2 @@
+// change c
diff --git a/src/d.rs b/src/d.rs
--- a/src/d.rs
+++ b/src/d.rs
@@ -1 +1,2 @@
+// change d
";
        let msg = generate_commit_message(diff);
        // More than 3 files should show "N files"
        assert!(
            msg.contains("4 files"),
            "Should show file count for many files: {msg}"
        );
    }

    #[test]
    fn test_generate_commit_message_deletions_only() {
        let diff = "\
diff --git a/src/old.rs b/src/old.rs
--- a/src/old.rs
+++ b/src/old.rs
@@ -1,5 +1,2 @@
-// removed line 1
-// removed line 2
-// removed line 3
 fn keep() {}
";
        let msg = generate_commit_message(diff);
        assert!(
            msg.contains("remove code"),
            "Pure deletion should say 'remove code': {msg}"
        );
    }

    #[test]
    fn test_git_subcommand_help() {
        assert_eq!(parse_git_args(""), GitSubcommand::Help);
        assert_eq!(parse_git_args("  "), GitSubcommand::Help);
        assert_eq!(parse_git_args("unknown"), GitSubcommand::Help);
        assert_eq!(parse_git_args("push"), GitSubcommand::Help);
    }

    #[test]
    fn test_git_subcommand_status() {
        assert_eq!(parse_git_args("status"), GitSubcommand::Status);
        assert_eq!(parse_git_args("STATUS"), GitSubcommand::Status);
        assert_eq!(parse_git_args("Status"), GitSubcommand::Status);
    }

    #[test]
    fn test_git_subcommand_log() {
        assert_eq!(parse_git_args("log"), GitSubcommand::Log(5));
        assert_eq!(parse_git_args("log 10"), GitSubcommand::Log(10));
        assert_eq!(parse_git_args("log 1"), GitSubcommand::Log(1));
        assert_eq!(parse_git_args("LOG 20"), GitSubcommand::Log(20));
        // Invalid number falls back to default 5
        assert_eq!(parse_git_args("log abc"), GitSubcommand::Log(5));
    }

    #[test]
    fn test_git_subcommand_add() {
        assert_eq!(
            parse_git_args("add src/main.rs"),
            GitSubcommand::Add("src/main.rs".to_string())
        );
        assert_eq!(parse_git_args("add ."), GitSubcommand::Add(".".to_string()));
        assert_eq!(
            parse_git_args("ADD Cargo.toml"),
            GitSubcommand::Add("Cargo.toml".to_string())
        );
        // add without path shows help
        assert_eq!(parse_git_args("add"), GitSubcommand::Help);
        assert_eq!(parse_git_args("add  "), GitSubcommand::Help);
    }

    #[test]
    fn test_git_subcommand_stash() {
        assert_eq!(parse_git_args("stash"), GitSubcommand::Stash);
        assert_eq!(parse_git_args("STASH"), GitSubcommand::Stash);
    }

    #[test]
    fn test_git_subcommand_stash_pop() {
        assert_eq!(parse_git_args("stash pop"), GitSubcommand::StashPop);
        assert_eq!(parse_git_args("STASH POP"), GitSubcommand::StashPop);
        assert_eq!(parse_git_args("stash Pop"), GitSubcommand::StashPop);
    }

    #[test]
    fn test_git_subcommand_stash_list() {
        assert_eq!(parse_git_args("stash list"), GitSubcommand::StashList);
        assert_eq!(parse_git_args("STASH LIST"), GitSubcommand::StashList);
        assert_eq!(parse_git_args("stash List"), GitSubcommand::StashList);
    }

    #[test]
    fn test_git_subcommand_stash_show() {
        assert_eq!(parse_git_args("stash show"), GitSubcommand::StashShow(None));
        assert_eq!(
            parse_git_args("stash show 2"),
            GitSubcommand::StashShow(Some(2))
        );
        assert_eq!(
            parse_git_args("STASH SHOW 0"),
            GitSubcommand::StashShow(Some(0))
        );
        // Non-numeric argument falls back to None (default stash@{0})
        assert_eq!(
            parse_git_args("stash show abc"),
            GitSubcommand::StashShow(None)
        );
    }

    #[test]
    fn test_git_subcommand_stash_drop() {
        assert_eq!(parse_git_args("stash drop"), GitSubcommand::StashDrop(None));
        assert_eq!(
            parse_git_args("stash drop 3"),
            GitSubcommand::StashDrop(Some(3))
        );
        assert_eq!(
            parse_git_args("STASH DROP 1"),
            GitSubcommand::StashDrop(Some(1))
        );
        // Non-numeric argument falls back to None
        assert_eq!(
            parse_git_args("stash drop xyz"),
            GitSubcommand::StashDrop(None)
        );
    }

    #[test]
    fn test_git_subcommand_stash_push() {
        // "stash push" is an explicit alias for "stash"
        assert_eq!(parse_git_args("stash push"), GitSubcommand::Stash);
        assert_eq!(parse_git_args("STASH PUSH"), GitSubcommand::Stash);
    }

    #[test]
    fn test_format_stash_list_empty() {
        let result = format_stash_list("");
        assert!(
            result.contains("no stashes"),
            "Empty input should show 'no stashes': {result}"
        );
    }

    #[test]
    fn test_format_stash_list_single_entry() {
        let input = "stash@{0}: WIP on main: abc1234 fix tests";
        let result = format_stash_list(input);
        // Should contain the stash ref
        assert!(
            result.contains("stash@{0}"),
            "Should contain stash ref: {result}"
        );
        // Should contain the message
        assert!(
            result.contains("fix tests"),
            "Should contain the message: {result}"
        );
    }

    #[test]
    fn test_format_stash_list_multiple_entries() {
        let input = "\
stash@{0}: WIP on main: abc1234 fix tests
stash@{1}: On feature: def5678 wip stuff";
        let result = format_stash_list(input);
        assert!(
            result.contains("stash@{0}"),
            "Should contain first stash ref: {result}"
        );
        assert!(
            result.contains("stash@{1}"),
            "Should contain second stash ref: {result}"
        );
        assert!(
            result.contains("fix tests"),
            "Should contain first message: {result}"
        );
        assert!(
            result.contains("wip stuff"),
            "Should contain second message: {result}"
        );
    }

    #[test]
    fn test_format_stash_list_uses_ansi_colors() {
        let input = "stash@{0}: WIP on main: abc1234 fix tests";
        let result = format_stash_list(input);
        // Should use YELLOW for stash ref
        assert!(
            result.contains("\x1b[33m"),
            "Should use YELLOW ANSI code: {result}"
        );
        // Should use BOLD for message
        assert!(
            result.contains("\x1b[1m"),
            "Should use BOLD ANSI code: {result}"
        );
        // Should use DIM for middle part
        assert!(
            result.contains("\x1b[2m"),
            "Should use DIM ANSI code: {result}"
        );
    }

    #[test]
    fn test_git_subcommand_diff() {
        assert_eq!(
            parse_git_args("diff"),
            GitSubcommand::Diff { cached: false }
        );
        assert_eq!(
            parse_git_args("DIFF"),
            GitSubcommand::Diff { cached: false }
        );
        assert_eq!(
            parse_git_args("diff --cached"),
            GitSubcommand::Diff { cached: true }
        );
        assert_eq!(
            parse_git_args("DIFF --CACHED"),
            GitSubcommand::Diff { cached: true }
        );
        // Non-cached flag treated as not cached
        assert_eq!(
            parse_git_args("diff --stat"),
            GitSubcommand::Diff { cached: false }
        );
    }

    #[test]
    fn test_git_subcommand_branch() {
        assert_eq!(parse_git_args("branch"), GitSubcommand::Branch(None));
        assert_eq!(parse_git_args("BRANCH"), GitSubcommand::Branch(None));
        assert_eq!(
            parse_git_args("branch feature/new"),
            GitSubcommand::Branch(Some("feature/new".to_string()))
        );
        assert_eq!(
            parse_git_args("BRANCH my-branch"),
            GitSubcommand::Branch(Some("my-branch".to_string()))
        );
        // branch with empty name is just listing
        assert_eq!(parse_git_args("branch  "), GitSubcommand::Branch(None));
    }

    #[test]
    fn test_git_branch_returns_something_in_repo() {
        let branch = git_branch();
        // Outside a git repo (e.g. cargo-mutants temp dir), branch is None — that's fine
        if let Some(name) = branch {
            assert!(!name.is_empty(), "Branch name should not be empty");
            assert!(
                !name.contains('\n'),
                "Branch name should not contain newlines"
            );
        }
    }

    #[test]
    fn test_detect_base_branch_returns_valid_name() {
        let base = detect_base_branch();
        assert!(
            base == "main" || base == "master",
            "Base branch should be 'main' or 'master', got: {base}"
        );
    }

    #[test]
    fn test_get_branch_diff_runs() {
        // Should not panic; may return None outside a git repo
        let base = detect_base_branch();
        let diff = get_branch_diff(&base);
        if let Some(d) = diff {
            assert!(d.len() < 50_000_000, "Diff should be reasonable size");
        }
    }

    #[test]
    fn test_get_branch_commits_runs() {
        // Should not panic; may return None outside a git repo
        let base = detect_base_branch();
        let commits = get_branch_commits(&base);
        if let Some(c) = commits {
            assert!(c.len() < 10_000_000, "Commits output should be reasonable");
        }
    }

    #[test]
    fn test_build_pr_description_prompt_contains_info() {
        let prompt = build_pr_description_prompt(
            "feature/test",
            "main",
            "abc1234 Add feature\ndef5678 Fix bug\n",
            "+++ b/src/main.rs\n+// new code\n",
        );
        assert!(
            prompt.contains("feature/test"),
            "Prompt should contain branch name"
        );
        assert!(prompt.contains("main"), "Prompt should contain base branch");
        assert!(prompt.contains("abc1234"), "Prompt should contain commits");
        assert!(prompt.contains("new code"), "Prompt should contain diff");
        assert!(
            prompt.contains("TITLE:"),
            "Prompt should ask for TITLE format"
        );
    }

    #[test]
    fn test_build_pr_description_prompt_truncates_large_diff() {
        let large_diff = "x".repeat(20_000);
        let prompt = build_pr_description_prompt("branch", "main", "commit1", &large_diff);
        assert!(
            prompt.contains("diff truncated"),
            "Large diffs should be truncated"
        );
        // The prompt should not be the full 20k+ length
        assert!(
            prompt.len() < 20_000,
            "Prompt should be truncated, got {} chars",
            prompt.len()
        );
    }

    #[test]
    fn test_parse_pr_description_valid() {
        let response = "TITLE: feat: add PR creation command\n---\nThis PR adds the `/pr create` command.\n\n- New command\n- AI-generated descriptions";
        let result = parse_pr_description(response);
        assert!(result.is_some(), "Should parse valid response");
        let (title, body) = result.unwrap();
        assert_eq!(title, "feat: add PR creation command");
        assert!(body.contains("This PR adds"));
        assert!(body.contains("- New command"));
    }

    #[test]
    fn test_parse_pr_description_with_extra_whitespace() {
        let response =
            "\n  TITLE: fix: resolve crash on startup\n---\n\nFixed the null pointer issue.\n  ";
        let result = parse_pr_description(response);
        assert!(result.is_some(), "Should parse with extra whitespace");
        let (title, body) = result.unwrap();
        assert_eq!(title, "fix: resolve crash on startup");
        assert!(body.contains("Fixed the null pointer"));
    }

    #[test]
    fn test_parse_pr_description_missing_title() {
        let response = "Some random text without TITLE line\n---\nbody here";
        let result = parse_pr_description(response);
        assert!(result.is_none(), "Should fail without TITLE: line");
    }

    #[test]
    fn test_parse_pr_description_missing_separator() {
        let response = "TITLE: some title\nbody without separator";
        let result = parse_pr_description(response);
        assert!(result.is_none(), "Should fail without --- separator");
    }

    #[test]
    fn test_parse_pr_description_empty_title() {
        let response = "TITLE: \n---\nbody here";
        let result = parse_pr_description(response);
        assert!(result.is_none(), "Should fail with empty title");
    }

    // ── colorize_diff tests ──────────────────────────────────────────────

    #[test]
    fn colorize_diff_green_for_additions() {
        let diff = "+added line\n context\n";
        let result = colorize_diff(diff);
        assert!(
            result.contains("\x1b[32m+added line\x1b[0m"),
            "Addition lines should be green: {result}"
        );
    }

    #[test]
    fn colorize_diff_red_for_deletions() {
        let diff = "-removed line\n context\n";
        let result = colorize_diff(diff);
        assert!(
            result.contains("\x1b[31m-removed line\x1b[0m"),
            "Deletion lines should be red: {result}"
        );
    }

    #[test]
    fn colorize_diff_cyan_for_hunk_headers() {
        let diff = "@@ -1,3 +1,4 @@\n context\n";
        let result = colorize_diff(diff);
        assert!(
            result.contains("\x1b[36m@@ -1,3 +1,4 @@\x1b[0m"),
            "Hunk headers should be cyan: {result}"
        );
    }

    #[test]
    fn colorize_diff_bold_for_file_headers() {
        let diff = "diff --git a/foo.rs b/foo.rs\n--- a/foo.rs\n+++ b/foo.rs\n";
        let result = colorize_diff(diff);
        assert!(
            result.contains("\x1b[1mdiff --git a/foo.rs b/foo.rs\x1b[0m"),
            "diff --git lines should be bold: {result}"
        );
        assert!(
            result.contains("\x1b[1m--- a/foo.rs\x1b[0m"),
            "--- lines should be bold: {result}"
        );
        assert!(
            result.contains("\x1b[1m+++ b/foo.rs\x1b[0m"),
            "+++ lines should be bold: {result}"
        );
    }

    #[test]
    fn colorize_diff_context_lines_unchanged() {
        let diff = " context line\nanother context\n";
        let result = colorize_diff(diff);
        assert!(
            result.contains(" context line\n"),
            "Context lines should be unchanged: {result}"
        );
        assert!(
            result.contains("another context\n"),
            "Context lines should be unchanged: {result}"
        );
        // Should NOT contain any ANSI codes on context lines
        assert!(
            !result.contains("\x1b[32m context line"),
            "Context lines should not be colored"
        );
    }

    #[test]
    fn colorize_diff_empty_input() {
        let result = colorize_diff("");
        assert_eq!(result, "", "Empty input should return empty output");
    }
}