mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Git diff parsing — unified diff output into structured data.
//!
//! Handles `git diff HEAD --no-color --find-renames` or `git show -m`; untracked / new file
//! content is assembled into synthetic entries. The git subprocess wrappers live in
//! [`crate::git::commands`].

use tracing::warn;

use crate::util::unquote_c_style;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffFileStatus {
    /// File exists on both sides (modified or unchanged).
    Modified,
    /// New file added to git (from `--- /dev/null`).
    Added,
    /// File deleted from git (from `+++ /dev/null`).
    Deleted,
    /// File renamed (from `rename from`/`rename to`).
    Renamed,
    /// Untracked/new file, assembled from raw content by `make_untracked_diff_file`.
    Untracked,
}

/// Whether the diff file has parseable content, or a placeholder reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffContent {
    Parseable,
    /// File is binary (detected by git).
    Binary,
    /// File is too large to diff (size in bytes).
    TooLarge(u64),
}

#[derive(Debug, Clone)]
pub struct DiffFile {
    pub path: String,
    /// Previous path when git detects a rename.
    pub old_path: Option<String>,
    pub hunks: Vec<DiffHunk>,
    pub status: DiffFileStatus,
    pub content: DiffContent,
}

impl DiffFile {
    /// Create a new `DiffFile` with the given path, hunks, and status. Defaults: `old_path: None`,
    /// `content: DiffContent::Parseable`.
    #[must_use]
    pub fn new(path: String, hunks: Vec<DiffHunk>, status: DiffFileStatus) -> Self {
        Self {
            path,
            old_path: None,
            hunks,
            status,
            content: DiffContent::Parseable,
        }
    }

    /// Create a placeholder entry for binary or too-large untracked files.
    #[must_use]
    pub const fn placeholder(path: String, content: DiffContent) -> Self {
        Self {
            path,
            old_path: None,
            hunks: Vec::new(),
            status: DiffFileStatus::Untracked,
            content,
        }
    }
    /// Binary and too-large files have no parseable content lines — headers only.
    #[must_use]
    pub(crate) fn has_parseable_content(&self) -> bool {
        matches!(self.content, DiffContent::Parseable)
    }
}

#[derive(Debug, Clone)]
pub struct DiffHunk {
    /// The hunk header line, e.g. "@@ -10,7 +10,9 @@ fn main() {
    pub header: String,
    pub lines: Vec<DiffLine>,
}

#[derive(Debug, Clone)]
pub struct DiffLine {
    pub kind: DiffLineKind,
    pub old_line_number: Option<usize>,
    pub new_line_number: Option<usize>,
    /// The code content (without the leading +/-/space prefix).
    pub content: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineKind {
    Added,
    Removed,
    Context,
}

impl DiffLineKind {
    /// The leading character used in unified diff format: '+', '-', or ' '.
    #[must_use]
    pub const fn prefix(self) -> char {
        match self {
            Self::Added => '+',
            Self::Removed => '-',
            Self::Context => ' ',
        }
    }
}

#[derive(Default)]
struct DiffParser {
    files: Vec<DiffFile>,
    current_file: Option<DiffFile>,
    current_hunk: Option<DiffHunk>,
    old_counter: usize,
    new_counter: usize,
}

impl DiffParser {
    fn flush_hunk(&mut self) {
        if let Some(hunk) = self.current_hunk.take()
            && let Some(f) = &mut self.current_file
        {
            f.hunks.push(hunk);
        }
    }

    fn flush(&mut self) {
        self.flush_hunk();
        if let Some(file) = self.current_file.take() {
            self.files.push(file);
        }
    }

    /// `diff --git`: flush the previous file, reset counters, create a new entry.
    fn handle_diff_git_header(&mut self, line: &str) {
        self.flush();
        self.old_counter = 0;
        self.new_counter = 0;

        if let Some(path) = parse_diff_git_line(line) {
            self.current_file = Some(DiffFile::new(path, Vec::new(), DiffFileStatus::Modified));
        }
    }

    /// `rename from`: parse the old path and set the status to `Renamed`; a malformed line
    /// leaves it `Modified` (the default).
    fn handle_rename_from(&mut self, line: &str) {
        let Some(f) = self.current_file.as_mut() else {
            return;
        };

        let Some(raw) = line.strip_prefix("rename from ") else {
            warn!(
                line = %line,
                "rename from: unexpected format, dropping rename info"
            );
            return;
        };
        let Some(old_path) = unquote_c_style(raw) else {
            warn!(
                line = %line,
                "rename from: malformed C-style escape, dropping rename info"
            );
            return;
        };
        f.status = DiffFileStatus::Renamed;
        f.old_path = Some(old_path);
    }

    /// Hunk header (`@@ -old,count +new,count @@`): flush the previous hunk, parse the header
    /// and start a new hunk with fresh counters.
    fn handle_hunk_header(&mut self, line: &str) {
        self.flush_hunk();
        let (old_start, new_start) = parse_hunk_header(line);
        self.old_counter = old_start;
        self.new_counter = new_start;
        self.current_hunk = Some(DiffHunk {
            header: line.to_string(),
            lines: Vec::new(),
        });
    }

    /// A content line within a hunk: classify as Added/Removed/Context, track line numbers,
    /// push to the hunk. Non-content lines are filtered by the caller.
    fn handle_diff_content_line(&mut self, line: &str) {
        // No active hunk: this line falls outside any diff hunk — skip.
        let Some(hunk) = self.current_hunk.as_mut() else {
            return;
        };

        let line_kind = if line.starts_with('+') {
            DiffLineKind::Added
        } else if line.starts_with('-') {
            DiffLineKind::Removed
        } else if line.starts_with(' ') {
            DiffLineKind::Context
        } else {
            return;
        };

        let content = line[1..].trim_end_matches('\r');
        let (old_num, new_num) = match line_kind {
            DiffLineKind::Added => {
                let n = Some(self.new_counter);
                self.new_counter += 1;
                (None, n)
            }
            DiffLineKind::Removed => {
                let n = Some(self.old_counter);
                self.old_counter += 1;
                (n, None)
            }
            DiffLineKind::Context => {
                let o = Some(self.old_counter);
                let n = Some(self.new_counter);
                self.old_counter += 1;
                self.new_counter += 1;
                (o, n)
            }
        };

        hunk.lines.push(DiffLine {
            kind: line_kind,
            old_line_number: old_num,
            new_line_number: new_num,
            content: content.to_string(),
        });
    }

    fn process_line(&mut self, line: &str) {
        if line.starts_with("diff --git ") {
            self.handle_diff_git_header(line);
        } else if line.starts_with("index ")
            || line.starts_with("new file mode ")
            || line.starts_with("deleted file mode ")
            || line.starts_with("old mode ")
            || line.starts_with("new mode ")
            || line.starts_with("rename to ")
            || line.starts_with("\\ ")
        // e.g. "\ No newline at end of file"
        {
            // Safe to skip: `diff --git` already captured the b-path, and `rename from`
            // already set the status.
        } else if line.starts_with("--- ") || line.starts_with("+++ ") {
            if let Some(ref mut f) = self.current_file {
                if line.starts_with("--- /dev/null") {
                    f.status = DiffFileStatus::Added;
                } else if line.starts_with("+++ /dev/null") {
                    f.status = DiffFileStatus::Deleted;
                }
            }
        } else if line.starts_with("rename from ") {
            self.handle_rename_from(line);
        } else if line.starts_with("Binary files ") {
            if let Some(ref mut f) = self.current_file {
                f.content = DiffContent::Binary;
            }
        } else if line.starts_with("@@") {
            self.handle_hunk_header(line);
        } else {
            self.handle_diff_content_line(line);
        }
    }
}

/// Parse unified diff output (from `git diff HEAD` or `git show -m`).
#[must_use]
pub fn parse_git_diff(diff_output: &str) -> Vec<DiffFile> {
    let mut parser = DiffParser::default();
    for line in diff_output.lines() {
        parser.process_line(line);
    }
    parser.flush();
    parser.files
}

/// A [`DiffFile`] for an untracked file (all lines added).
#[must_use]
pub fn make_untracked_diff_file(path: &str, content: &str) -> DiffFile {
    let lines: Vec<DiffLine> = content
        .lines()
        .enumerate()
        .map(|(idx, line)| DiffLine {
            kind: DiffLineKind::Added,
            old_line_number: None,
            new_line_number: Some(idx + 1),
            content: line.trim_end_matches('\r').to_string(),
        })
        .collect();

    let hunk = DiffHunk {
        header: format!("@@ -0,0 +1,{} @@ new file", lines.len()),
        lines,
    };

    DiffFile::new(path.to_string(), vec![hunk], DiffFileStatus::Untracked)
}

/// Parse the `b/` path from a `diff --git a/… b/…` line.
///
/// Git's `core.quotepath` (on by default) C-quotes paths with trigger characters (`"`, `\`,
/// control chars <0x20, bytes ≥0x80); spaces (0x20) do NOT trigger quoting. Two formats exist:
///
/// - **Fully-quoted** (both sides trigger chars): each side gets its own quote pair,
///   `diff --git "a/file\"name.rs" "b/file\"name.rs"` — the `b/` prefix is INSIDE the
///   quotes, so a naive `find(" b/")` fails.
/// - **Asymmetrical** (possible for renames where only one path has trigger chars):
///   `diff --git "a/file\"x.rs" b/normal.rs` or `diff --git a/normal.rs "b/file\"x.rs"`.
///
/// Returns `None` if the line is malformed, an escape sequence is invalid, or the `b/` prefix
/// is missing. Deliberately not handled: `---`/`+++` lines (only checked for `/dev/null` to
/// detect added/deleted files — extracting paths from them would be a bug), `rename to` (the
/// `diff --git` b-path is authoritative), and combined diff (`diff --combined`/`--cc`), which
/// `git show -m` never produces.
fn parse_diff_git_line(line: &str) -> Option<String> {
    let rest = line.strip_prefix("diff --git ")?;
    let b_part = find_b_part(rest)?;
    extract_b_path(b_part)
}

/// Locate the b-part (second token) in the remainder of a `diff --git` line.
///
/// The a-part may be double-quoted and contain escaped quotes/spaces, so splitting on the first
/// space is unreliable; the b-part may itself be quoted. Search for the boundary marker (` b/`
/// for an unquoted b-part, ` "b/` for a quoted one).
fn find_b_part(rest: &str) -> Option<&str> {
    let bytes = rest.as_bytes();

    if bytes.first() == Some(&b'"') {
        // Quoted a-part: scan for the closing unescaped quote, then skip whitespace to reach
        // the b-part.
        let mut i: usize = 1;
        while i < bytes.len() {
            if bytes[i] == b'\\' {
                // Git's C-quoting uses single-char escapes (\t, \n, \\, \") or multi-byte
                // octal escapes; skipping 2 bytes (backslash + next byte) suffices, because the
                // remaining octal digits cannot match `\` or `"`.
                i += 2;
            } else if bytes[i] == b'"' {
                i += 1; // skip closing quote
                break;
            } else {
                i += 1;
            }
        }
        while i < bytes.len() && bytes[i] == b' ' {
            i += 1;
        }
        if i >= bytes.len() {
            return None;
        }
        Some(&rest[i..])
    } else {
        // Unquoted a-part, whose path may contain spaces (they don't trigger C-style
        // quoting). The b-part can be quoted (`"b/…"`) or not; try the quoted separator first.
        if let Some(idx) = rest.find(" \"b/") {
            Some(&rest[idx + 1..])
        } else {
            rest.find(" b/").map(|idx| &rest[idx + 1..])
        }
    }
}

/// Extract the unescaped path from the b-part token: `b/path`, or `"b/path\"with\"escapes"`
/// with the prefix inside the quotes.
fn extract_b_path(b_part: &str) -> Option<String> {
    let path = unquote_c_style(b_part)?;
    Some(path.strip_prefix("b/")?.to_string())
}

/// Parse a range token like `-10,7` or `+10` from a hunk header; `None` when malformed.
fn parse_range_token(part: &str, prefix: char) -> Option<usize> {
    let remainder = part.strip_prefix(prefix)?;
    remainder.split(',').next()?.parse::<usize>().ok()
}

/// Parse a hunk header: `@@ -old_start,old_count +new_start,new_count @@ [context]`.
///
/// Returns `(old_start, new_start)`, defaulting to `1` for malformed or missing ranges.
///
/// # Correctness
///
/// Trailing-context tokens can look like range prefixes: `->` in a Rust signature starts with
/// `-`, and `a + b` yields a `+b` token. Both appear after the closing `@@`, where the parser
/// stops on the first `@`, so they are never inspected — and [`parse_range_token`] returns
/// `None` for any non-numeric remainder anyway.
fn parse_hunk_header(header: &str) -> (usize, usize) {
    // Example inputs:
    //   @@ -10,7 +10,9 @@ fn main() {
    //   @@ -1 +2 @@ fn main()
    //   @@ -0,0 +1,3 @@
    //   @@ -10,7 +10,9 @@ fn process() -> Result<()>

    let after_open = header.trim_start_matches('@');

    let mut old_start = 1;
    let mut new_start = 1;

    for part in after_open.split_whitespace() {
        // Stop at the closing @@ delimiter — remaining tokens are context and must not
        // influence line numbers.
        if part.starts_with('@') {
            break;
        }

        if part.starts_with('-')
            && let Some(n) = parse_range_token(part, '-')
        {
            old_start = n;
        } else if part.starts_with('+')
            && let Some(n) = parse_range_token(part, '+')
        {
            new_start = n;
        }
    }

    (old_start, new_start)
}

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

    /// One hunk-shape decision per case — a modified file's context/removed/added lines, a new
    /// file (all added, numbered from 1), a deleted file (all removed), a binary file (a header
    /// with no parseable content), and the synthetic untracked file.
    #[expect(clippy::too_many_lines)] // the table is the whole point: one row per hunk shape
    #[test]
    fn file_status_and_line_kinds_follow_the_diff() {
        enum Source {
            Diff(&'static str),
            Untracked(&'static str),
        }
        struct Case {
            name: &'static str,
            source: Source,
            path: &'static str,
            status: DiffFileStatus,
            content: DiffContent,
            hunks: usize,
            kinds: &'static [DiffLineKind],
            /// The first line's new-side line number, when it has one.
            first_new_line: Option<usize>,
        }
        let cases = [
            Case {
                name: "modified",
                source: Source::Diff(
                    r#"diff --git a/src/main.rs b/src/main.rs
index abc123..def456 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,4 @@
 fn main() {
-    println!("hello");
+    println!("hello world");
     println!("goodbye");
 }
"#,
                ),
                path: "src/main.rs",
                status: DiffFileStatus::Modified,
                content: DiffContent::Parseable,
                hunks: 1,
                kinds: &[
                    DiffLineKind::Context,
                    DiffLineKind::Removed,
                    DiffLineKind::Added,
                    DiffLineKind::Context,
                    DiffLineKind::Context,
                ],
                first_new_line: Some(1),
            },
            Case {
                name: "added",
                source: Source::Diff(
                    r#"diff --git a/new.rs b/new.rs
new file mode 100644
index 0000000..abc123
--- /dev/null
+++ b/new.rs
@@ -0,0 +1,2 @@
+fn hello() {
+    println!("new");
+}
"#,
                ),
                path: "new.rs",
                status: DiffFileStatus::Added,
                content: DiffContent::Parseable,
                hunks: 1,
                kinds: &[
                    DiffLineKind::Added,
                    DiffLineKind::Added,
                    DiffLineKind::Added,
                ],
                first_new_line: Some(1),
            },
            Case {
                name: "deleted",
                source: Source::Diff(
                    r#"diff --git a/old.rs b/old.rs
deleted file mode 100644
index abc123..0000000
--- a/old.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-fn hello() {
-    println!("bye");
-}
"#,
                ),
                path: "old.rs",
                status: DiffFileStatus::Deleted,
                content: DiffContent::Parseable,
                hunks: 1,
                kinds: &[
                    DiffLineKind::Removed,
                    DiffLineKind::Removed,
                    DiffLineKind::Removed,
                ],
                first_new_line: None,
            },
            Case {
                name: "binary",
                source: Source::Diff(
                    r"diff --git a/image.png b/image.png
index abc..def 100644
Binary files a/image.png and b/image.png differ
",
                ),
                path: "image.png",
                status: DiffFileStatus::Modified,
                content: DiffContent::Binary,
                hunks: 0,
                kinds: &[],
                first_new_line: None,
            },
            Case {
                name: "untracked",
                source: Source::Untracked("fn main() {}"),
                path: "src/untracked.rs",
                status: DiffFileStatus::Untracked,
                content: DiffContent::Parseable,
                hunks: 1,
                kinds: &[DiffLineKind::Added],
                first_new_line: Some(1),
            },
        ];

        for case in &cases {
            let files = match case.source {
                Source::Diff(diff) => parse_git_diff(diff),
                Source::Untracked(content) => vec![make_untracked_diff_file(case.path, content)],
            };
            assert_eq!(files.len(), 1, "case {}: one file", case.name);
            let file = &files[0];
            assert_eq!(file.path, case.path, "case {}", case.name);
            assert_eq!(file.status, case.status, "case {}", case.name);
            assert_eq!(file.content, case.content, "case {}", case.name);
            assert_eq!(file.hunks.len(), case.hunks, "case {}", case.name);
            let lines = file
                .hunks
                .first()
                .map_or(&[][..], |hunk| hunk.lines.as_slice());
            let kinds: Vec<DiffLineKind> = lines.iter().map(|line| line.kind).collect();
            assert_eq!(kinds, case.kinds, "case {}: line kinds", case.name);
            assert_eq!(
                lines.first().and_then(|line| line.new_line_number),
                case.first_new_line,
                "case {}: the first line's new-side number",
                case.name
            );
        }
    }

    #[test]
    fn test_parse_diff_git_line() {
        // Cases: (diff_line, expected_b_path). None-returning cases are not covered — all
        // existing tests exercise only Some-returning paths.
        let cases: &[(&str, Option<&str>)] = &[
            // Unquoted path.
            (
                "diff --git a/src/main.rs b/src/main.rs",
                Some("src/main.rs"),
            ),
            // Fully quoted: both sides have trigger chars.
            (
                r#"diff --git "a/file\"name.rs" "b/file\"name.rs""#,
                Some("file\"name.rs"),
            ),
            (
                r#"diff --git "a/path\\with\\backslash.rs" "b/path\\with\\backslash.rs""#,
                Some("path\\with\\backslash.rs"),
            ),
            (
                r#"diff --git "a/file\tname.rs" "b/file\tname.rs""#,
                Some("file\tname.rs"),
            ),
            // Multiple trigger chars: tab, double-quote, backslash.
            (
                r#"diff --git "a/file\t\"quote\"\\n.rs" "b/file\t\"quote\"\\n.rs""#,
                Some("file\t\"quote\"\\n.rs"),
            ),
            // Asymmetrical: only one side quoted.
            (
                r#"diff --git "a/file\"x.rs" b/normal.rs"#,
                Some("normal.rs"),
            ),
            (
                r#"diff --git a/normal.rs "b/file\"x.rs""#,
                Some("file\"x.rs"),
            ),
            // Multi-byte octal escape (git's `\377` = byte 0xFF): `find_b_part`'s 2-byte skip
            // (`i += 2`) handles 4-byte octal escapes — `\3` is skipped, the remaining `77`
            // process as ordinary non-delimiter bytes.
            (
                r#"diff --git "a/file\377name.rs" "b/file\377name.rs""#,
                Some("file\u{FFFD}name.rs"), // 0xFF → replacement character
            ),
        ];
        for (i, (input, expected)) in cases.iter().enumerate() {
            let result = parse_diff_git_line(input);
            assert_eq!(
                result.as_deref(),
                *expected,
                "case {i}: parse_diff_git_line({input:?})"
            );
        }
    }

    #[test]
    fn test_rename_from_cases() {
        // Cases: (name, diff, expected_old_path, expected_path).
        let cases: &[(&str, &str, Option<&str>, &str)] = &[
            // Unquoted rename — no special characters.
            (
                "unquoted",
                r"diff --git a/old.rs b/new.rs
similarity index 100%
rename from old.rs
rename to new.rs
",
                Some("old.rs"),
                "new.rs",
            ),
            // Quoted with escape sequences (double-quote in filename).
            (
                "quoted_with_escapes",
                r#"diff --git "a/old\"name.rs" "b/new\"name.rs"
similarity index 100%
rename from "old\"name.rs"
rename to "new\"name.rs"
"#,
                Some("old\"name.rs"),
                "new\"name.rs",
            ),
            // Tab character triggers quoting.
            (
                "quoted_tab_in_name",
                r#"diff --git "a/old\tname.rs" "b/new\tname.rs"
similarity index 100%
rename from "old\tname.rs"
rename to "new\tname.rs"
"#,
                Some("old\tname.rs"),
                "new\tname.rs",
            ),
            // Spaces without quoting — no trigger characters.
            (
                "no_trigger_chars",
                r"diff --git a/old name.rs b/new name.rs
similarity index 100%
rename from old name.rs
rename to new name.rs
",
                Some("old name.rs"),
                "new name.rs",
            ),
        ];
        for (i, (name, diff, expected_old_path, expected_path)) in cases.iter().enumerate() {
            let output = parse_git_diff(diff);
            assert_eq!(output.len(), 1, "case {i} ({name})");
            assert_eq!(
                output[0].status,
                DiffFileStatus::Renamed,
                "case {i} ({name})"
            );
            assert_eq!(
                output[0].old_path.as_deref(),
                *expected_old_path,
                "case {i} ({name}): old_path mismatch"
            );
            assert_eq!(
                output[0].path, *expected_path,
                "case {i} ({name}): path mismatch"
            );
        }
    }

    #[test]
    fn test_rename_from_malformed_c_style_escape() {
        // Malformed C-style escape (\x is unrecognized) makes unquote_c_style return None, so
        // the file keeps the default Modified status.
        let diff = r#"diff --git "a/old.rs" "b/new.rs"
similarity index 100%
rename from "old\xname.rs"
rename to "new.rs"
"#;
        let output = parse_git_diff(diff);
        assert_eq!(output.len(), 1);
        assert_eq!(output[0].status, DiffFileStatus::Modified);
        assert_eq!(output[0].old_path, None);
        assert_eq!(output[0].path, "new.rs");
    }

    #[test]
    fn test_no_newline_annotation_skipped_and_counters_correct() {
        // A trailing `\ No newline at end of file` annotation is metadata and must NOT
        // increment line counters — otherwise highlight lookups would be off-by-one for all
        // subsequent hunks.
        let diff = r"diff --git a/foo.rs b/foo.rs
index abc123..def456 100644
--- a/foo.rs
+++ b/foo.rs
@@ -1,3 +1,3 @@
 line1
 line2
 line3
\ No newline at end of file
@@ -10,2 +10,2 @@
 other1
 other2
";
        let output = parse_git_diff(diff);
        assert_eq!(output.len(), 1);
        assert_eq!(output[0].hunks.len(), 2);
        // First hunk: 3 context lines, no annotation line counted.
        assert_eq!(output[0].hunks[0].lines.len(), 3);
        assert_eq!(output[0].hunks[0].lines[0].old_line_number, Some(1));
        assert_eq!(output[0].hunks[0].lines[2].old_line_number, Some(3));
        // Second hunk: line numbers must pick up at 10, not 11.
        assert_eq!(output[0].hunks[1].lines.len(), 2);
        assert_eq!(output[0].hunks[1].lines[0].old_line_number, Some(10));
        assert_eq!(output[0].hunks[1].lines[1].old_line_number, Some(11));
    }

    #[test]
    fn test_parse_hunk_header_cases() {
        // Cases: (name, hunk_header, expected_old, expected_new).
        let cases: &[(&str, &str, usize, usize)] = &[
            // Rust signatures contain `->`, which must not corrupt old_start — it sits after
            // the closing @@ and the parser breaks on @@ first.
            (
                "hunk_context_with_arrow",
                "@@ -10,7 +10,9 @@ fn process() -> Result<()>",
                10,
                10,
            ),
            // `a + b` in context must not corrupt new_start, for the same reason.
            (
                "hunk_context_with_plus",
                "@@ -5,3 +5,4 @@ fn add(a: i32, b: i32) -> i32 { let x = a + b; }",
                5,
                5,
            ),
            // A context producing `@@` as a whitespace-delimited token must not make the parser
            // consume tokens after the real delimiter.
            ("hunk_at_at_in_context", "@@ -1,3 +1,3 @@ @@ -this", 1, 1),
            // Standard hunk header with plain context.
            (
                "hunk_plain_context",
                "@@ -100,6 +200,7 @@ fn main() {",
                100,
                200,
            ),
            // No context string after the closing @@.
            ("hunk_no_context", "@@ -0,0 +1,5 @@", 0, 1),
            // Single-line hunk without a comma count on the old range.
            ("hunk_no_count_first", "@@ -1 +1 @@ fn single_line()", 1, 1),
            // Single-line hunk, different values.
            ("hunk_no_count_second", "@@ -5 +3 @@ fn another()", 5, 3),
            // Context like `if x < -1` produces a `-1` token whose remainder `"1"` is all digits,
            // so digit validation alone would not reject it — only the @-break protects against
            // this. The header is constructed so `-1` follows the real range tokens.
            (
                "hunk_negative_number_in_context",
                "@@ -3,2 +3,2 @@ fn check() { if x < -1 { } }",
                3,
                3,
            ),
        ];
        for (i, (name, input, expected_old, expected_new)) in cases.iter().enumerate() {
            let (old, new) = parse_hunk_header(input);
            assert_eq!(
                old, *expected_old,
                "case {i} ({name}): old_start mismatch. Input: {input:?}"
            );
            assert_eq!(
                new, *expected_new,
                "case {i} ({name}): new_start mismatch. Input: {input:?}"
            );
        }
    }
}