eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding agents
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
use regex::Regex;
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::sync::LazyLock;

use super::unicode_tools::detect_newline_style;

const MAX_PATCH_LENGTH: usize = 200_000;
const MAX_ORIGINAL_LENGTH: usize = 200_000;

#[derive(Debug, Clone, Serialize)]
pub struct PatchHunk {
    pub old_start: usize,
    pub old_count: usize,
    pub new_start: usize,
    pub new_count: usize,
    pub header_line: String,
    pub lines: Vec<String>,
    pub raw: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct PatchFile {
    pub old_file: String,
    pub new_file: String,
    pub hunks: Vec<PatchHunk>,
    pub raw: String,
}

#[derive(Debug, Serialize)]
pub struct PatchParseResult {
    pub ok: bool,
    pub files: Vec<PatchFile>,
    pub error: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct FailedHunk {
    pub hunk_index: usize,
    pub old_start: usize,
    pub old_count: usize,
    pub expected_context: Vec<String>,
    pub actual_context: Vec<String>,
    pub reason: String,
}

#[derive(Debug, Serialize)]
pub struct PatchApplyCheckResult {
    pub patch_parse_ok: bool,
    pub applies: bool,
    pub hunks_total: usize,
    pub hunks_applied: usize,
    pub hunks_failed: usize,
    pub failed_hunks: Vec<FailedHunk>,
    pub affected_line_ranges: Vec<LineRange>,
    pub newline_style_before: String,
    pub newline_style_after: String,
    pub result_fingerprint: String,
    pub result_text: Option<String>,
    pub findings: Vec<String>,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct LineRange {
    pub start: usize,
    pub end: usize,
}

/// Build an inclusive line range for a hunk's destination span.
///
/// A deletion hunk has a zero-line destination span (for example, `+1,0`).
/// Represent that empty span by its insertion/deletion point so serialized
/// ranges remain ordered and callers can still identify the affected location.
fn line_range(start: usize, count: usize) -> LineRange {
    LineRange {
        start,
        end: if count == 0 {
            start
        } else {
            start.saturating_add(count - 1)
        },
    }
}

#[derive(Debug, PartialEq, Serialize)]
pub struct PatchSummaryResult {
    pub files_changed: usize,
    pub hunks_total: usize,
    pub additions: usize,
    pub deletions: usize,
    pub renames_detected: Vec<RenamePair>,
    pub binary_patch_detected: bool,
    pub line_ranges_by_file: BTreeMap<String, Vec<LineRange>>,
    pub findings: Vec<String>,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct RenamePair {
    pub from: String,
    pub to: String,
}

static HUNK_HEADER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@").unwrap());

fn parse_hunk_header(line: &str) -> Option<(usize, usize, usize, usize)> {
    let re = &*HUNK_HEADER_RE;
    let caps = re.captures(line)?;
    let old_start: usize = caps.get(1)?.as_str().parse().ok()?;
    let old_count: usize = caps
        .get(2)
        .map_or(Some(1), |m| m.as_str().parse().ok())
        .unwrap_or(1);
    let new_start: usize = caps.get(3)?.as_str().parse().ok()?;
    let new_count: usize = caps
        .get(4)
        .map_or(Some(1), |m| m.as_str().parse().ok())
        .unwrap_or(1);
    Some((old_start, old_count, new_start, new_count))
}

pub fn parse_unified_diff(patch_text: &str) -> PatchParseResult {
    if patch_text.trim().is_empty() {
        return PatchParseResult {
            ok: false,
            files: vec![],
            error: Some("Empty patch text".to_string()),
        };
    }

    let mut files: Vec<PatchFile> = vec![];
    let lines: Vec<&str> = patch_text.split('\n').collect();
    let mut i: usize = 0;
    let mut current_old_file = String::new();
    let mut current_new_file = String::new();
    let mut current_hunks: Vec<PatchHunk> = vec![];
    let mut current_hunk_lines: Vec<String> = vec![];
    let mut current_hunk_header = String::new();
    let mut current_hunk_info: Option<(usize, usize, usize, usize)> = None;
    let mut in_hunk = false;

    // Helper: flush any pending in-progress hunk into current_hunks.
    macro_rules! flush_hunk {
        () => {
            if in_hunk {
                if let Some((old_s, old_c, new_s, new_c)) = current_hunk_info {
                    let raw = format!("{}\n{}", current_hunk_header, current_hunk_lines.join("\n"));
                    current_hunks.push(PatchHunk {
                        old_start: old_s,
                        old_count: old_c,
                        new_start: new_s,
                        new_count: new_c,
                        header_line: current_hunk_header.clone(),
                        lines: current_hunk_lines.clone(),
                        raw,
                    });
                    in_hunk = false;
                    current_hunk_lines = vec![];
                    current_hunk_info = None;
                }
            }
        };
    }

    while i < lines.len() {
        let line = lines[i];

        if line.starts_with("--- ") {
            // Flush any in-progress hunk first.
            flush_hunk!();
            // Starting a new file — finalize the previous one (if any).
            if !current_old_file.is_empty()
                || !current_new_file.is_empty()
                || !current_hunks.is_empty()
            {
                files.push(PatchFile {
                    old_file: std::mem::take(&mut current_old_file),
                    new_file: std::mem::take(&mut current_new_file),
                    hunks: std::mem::take(&mut current_hunks),
                    raw: String::new(),
                });
            }
            current_old_file = strip_diff_path_prefix(line.strip_prefix("--- ").unwrap().trim());
        } else if line.starts_with("+++ ") {
            current_new_file = strip_diff_path_prefix(line.strip_prefix("+++ ").unwrap().trim());
        } else if line.starts_with("@@ ") {
            if in_hunk {
                if let Some((old_s, old_c, new_s, new_c)) = current_hunk_info {
                    let raw = format!("{}\n{}", current_hunk_header, current_hunk_lines.join("\n"));
                    current_hunks.push(PatchHunk {
                        old_start: old_s,
                        old_count: old_c,
                        new_start: new_s,
                        new_count: new_c,
                        header_line: current_hunk_header.clone(),
                        lines: current_hunk_lines.clone(),
                        raw,
                    });
                    current_hunk_lines = vec![];
                }
            }

            if let Some(parsed) = parse_hunk_header(line) {
                current_hunk_info = Some(parsed);
                current_hunk_header = line.to_string();
                in_hunk = true;
            } else if in_hunk {
                current_hunk_lines.push(line.to_string());
            }
        } else if in_hunk {
            current_hunk_lines.push(line.to_string());
        }

        i += 1;
    }

    if in_hunk {
        if let Some((old_s, old_c, new_s, new_c)) = current_hunk_info {
            let raw = format!("{}\n{}", current_hunk_header, current_hunk_lines.join("\n"));
            current_hunks.push(PatchHunk {
                old_start: old_s,
                old_count: old_c,
                new_start: new_s,
                new_count: new_c,
                header_line: current_hunk_header,
                lines: current_hunk_lines,
                raw,
            });
        }
    }

    if !current_old_file.is_empty() || !current_new_file.is_empty() || !current_hunks.is_empty() {
        files.push(PatchFile {
            old_file: current_old_file,
            new_file: current_new_file,
            hunks: current_hunks,
            raw: String::new(),
        });
    }

    if files.is_empty() {
        return PatchParseResult {
            ok: false,
            files: vec![],
            error: Some(
                "No unified diff headers found (-- a/... / +++ b/... or @@ ... @@)".to_string(),
            ),
        };
    }

    PatchParseResult {
        ok: true,
        files,
        error: None,
    }
}

/// Strip the unified-diff path prefix (`a/` or `b/`) and the optional
/// trailing timestamp from a diff header path. `/dev/null` becomes empty.
fn strip_diff_path_prefix(path: &str) -> String {
    let trimmed = path.trim();
    if trimmed == "/dev/null" {
        return String::new();
    }
    if let Some(stripped) = trimmed.strip_prefix("a/") {
        return stripped.to_string();
    }
    if let Some(stripped) = trimmed.strip_prefix("b/") {
        return stripped.to_string();
    }
    // Some diffs contain a tab-separated timestamp after the path; trim it.
    if let Some(idx) = trimmed.find('\t') {
        return trimmed[..idx].to_string();
    }
    trimmed.to_string()
}

fn text_to_lines(text: &str) -> Vec<&str> {
    let end = text.strip_suffix('\n').unwrap_or(text);
    let end = end.strip_suffix('\r').unwrap_or(end);
    end.split('\n').collect()
}

fn normalize_line(line: &str) -> &str {
    line.trim_end_matches('\r')
}

fn strip_line_prefix(line: &str) -> &str {
    if let Some(stripped) = line
        .strip_prefix('+')
        .or_else(|| line.strip_prefix('-'))
        .or_else(|| line.strip_prefix(' '))
    {
        stripped
    } else {
        line
    }
}

fn fingerprint(text: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(text.as_bytes());
    format!("{:x}", hasher.finalize())
}

fn expected_hunk_context(hunk: &PatchHunk) -> Vec<String> {
    hunk.lines
        .iter()
        .map(|line| normalize_line(line))
        .filter(|line| line.starts_with(' ') || line.starts_with('-'))
        .map(|line| strip_line_prefix(line).to_string())
        .collect()
}

fn validate_hunk(
    original_lines: &[&str],
    hunk: &PatchHunk,
    strict: bool,
) -> Result<(usize, usize), String> {
    let old_start = hunk.old_start.saturating_sub(1);
    let old_count = hunk.old_count;

    if old_start > original_lines.len() {
        return Err(format!("Invalid hunk start: {}", hunk.old_start));
    }

    let expected_context = expected_hunk_context(hunk);

    let actual_end = old_start.saturating_add(old_count);
    let actual_end = if actual_end > original_lines.len() {
        if strict {
            return Err(format!(
                "Hunk references lines {}-{} but original has only {} lines",
                hunk.old_start,
                hunk.old_start.saturating_add(old_count).saturating_sub(1),
                original_lines.len()
            ));
        }
        original_lines.len()
    } else {
        actual_end
    };
    let actual_context = &original_lines[old_start..actual_end];

    if strict && expected_context.len() != actual_context.len() {
        return Err(format!(
            "Context length mismatch: hunk expects {} lines, actual has {} lines",
            expected_context.len(),
            actual_context.len()
        ));
    }

    if strict {
        for (idx, (expected, actual)) in expected_context
            .iter()
            .zip(actual_context.iter())
            .enumerate()
        {
            if normalize_line(expected) != normalize_line(actual) {
                return Err(format!(
                    "Context mismatch at line {}: expected {:?}, got {:?}",
                    hunk.old_start + idx,
                    normalize_line(expected),
                    normalize_line(actual)
                ));
            }
        }
    }
    Ok((old_start, actual_end))
}

fn append_line(output: &mut String, has_line: &mut bool, line: &str, add_cr: bool) {
    if *has_line {
        output.push('\n');
    }
    output.push_str(line);
    if add_cr {
        output.push('\r');
    }
    *has_line = true;
}

pub fn patch_apply_check(
    original_text: &str,
    patch_text: &str,
    strict: bool,
    return_result_fingerprint: bool,
    return_result_text: bool,
) -> PatchApplyCheckResult {
    let mut findings: Vec<String> = vec![];
    let mut failed_hunks: Vec<FailedHunk> = vec![];
    let mut affected_line_ranges: Vec<LineRange> = vec![];

    if original_text.len() > MAX_ORIGINAL_LENGTH {
        return PatchApplyCheckResult {
            patch_parse_ok: false,
            applies: false,
            hunks_total: 0,
            hunks_applied: 0,
            hunks_failed: 0,
            failed_hunks: vec![],
            affected_line_ranges: vec![],
            newline_style_before: detect_newline_style(original_text),
            newline_style_after: detect_newline_style(original_text),
            result_fingerprint: String::new(),
            result_text: None,
            findings: vec![format!(
                "Original text exceeds maximum length of {}",
                MAX_ORIGINAL_LENGTH
            )],
        };
    }

    if patch_text.len() > MAX_PATCH_LENGTH {
        return PatchApplyCheckResult {
            patch_parse_ok: false,
            applies: false,
            hunks_total: 0,
            hunks_applied: 0,
            hunks_failed: 0,
            failed_hunks: vec![],
            affected_line_ranges: vec![],
            newline_style_before: detect_newline_style(original_text),
            newline_style_after: detect_newline_style(original_text),
            result_fingerprint: String::new(),
            result_text: None,
            findings: vec![format!(
                "Patch text exceeds maximum length of {}",
                MAX_PATCH_LENGTH
            )],
        };
    }

    let newline_before = detect_newline_style(original_text);

    let parse_result = parse_unified_diff(patch_text);
    if !parse_result.ok {
        return PatchApplyCheckResult {
            patch_parse_ok: false,
            applies: false,
            hunks_total: 0,
            hunks_applied: 0,
            hunks_failed: 0,
            failed_hunks: vec![],
            affected_line_ranges: vec![],
            newline_style_before: newline_before.clone(),
            newline_style_after: newline_before.clone(),
            result_fingerprint: String::new(),
            result_text: None,
            findings: vec![format!(
                "Failed to parse patch: {}",
                parse_result.error.unwrap_or_default()
            )],
        };
    }

    let original_lines = text_to_lines(original_text);
    let mut all_hunks: Vec<&PatchHunk> = vec![];
    for file_entry in &parse_result.files {
        for hunk in &file_entry.hunks {
            all_hunks.push(hunk);
        }
    }

    let hunks_total = all_hunks.len();
    if hunks_total == 0 {
        return PatchApplyCheckResult {
            patch_parse_ok: true,
            applies: true,
            hunks_total: 0,
            hunks_applied: 0,
            hunks_failed: 0,
            failed_hunks: vec![],
            affected_line_ranges: vec![],
            newline_style_before: newline_before.clone(),
            newline_style_after: newline_before.clone(),
            result_fingerprint: if return_result_fingerprint {
                fingerprint(original_text)
            } else {
                String::new()
            },
            result_text: if return_result_text {
                Some(original_text.to_string())
            } else {
                None
            },
            findings: vec!["No hunks found in patch".to_string()],
        };
    }

    let build_result = return_result_text || return_result_fingerprint;
    let preserve_crlf = newline_before == "CRLF";
    let mut result_text_builder = if build_result {
        Some(String::with_capacity(
            original_text.len().saturating_add(patch_text.len()),
        ))
    } else {
        None
    };
    let mut has_output_line = false;
    let mut source_cursor = 0usize;
    let mut hunks_applied = 0;
    let mut hunks_failed = 0;

    for (hunk_idx, hunk) in all_hunks.iter().enumerate() {
        let old_start = hunk.old_start.saturating_sub(1);
        let actual_end = old_start.saturating_add(hunk.old_count);
        if !strict && old_start <= original_lines.len() && actual_end > original_lines.len() {
            findings.push(format!(
                "Hunk {} context truncated at end of original text",
                hunk_idx
            ));
        }

        let result = if old_start < source_cursor {
            Err(format!(
                "Hunk starts before the previous hunk: {}",
                hunk.old_start
            ))
        } else {
            validate_hunk(&original_lines, hunk, strict)
        };
        match result {
            Ok((hunk_start, hunk_end)) => {
                if let Some(output) = result_text_builder.as_mut() {
                    for line in &original_lines[source_cursor..hunk_start] {
                        append_line(output, &mut has_output_line, line, false);
                    }
                }

                let mut source_index = hunk_start;
                for raw_line in &hunk.lines {
                    let line = normalize_line(raw_line);
                    if line.starts_with(' ') {
                        if let Some(output) = result_text_builder.as_mut() {
                            let source_line = original_lines
                                .get(source_index)
                                .copied()
                                .unwrap_or_else(|| strip_line_prefix(line));
                            append_line(output, &mut has_output_line, source_line, false);
                        }
                        source_index = source_index.saturating_add(1);
                    } else if line.starts_with('-') {
                        source_index = source_index.saturating_add(1);
                    } else if line.starts_with('+') {
                        if let Some(output) = result_text_builder.as_mut() {
                            append_line(
                                output,
                                &mut has_output_line,
                                strip_line_prefix(line),
                                preserve_crlf,
                            );
                        }
                    }
                }
                source_cursor = hunk_end;
                hunks_applied += 1;
                affected_line_ranges.push(line_range(hunk.new_start, hunk.new_count));
            }
            Err(error) => {
                hunks_failed += 1;
                let expected_ctx = expected_hunk_context(hunk);
                let actual_end = std::cmp::min(
                    hunk.old_start
                        .saturating_sub(1)
                        .saturating_add(hunk.old_count),
                    original_lines.len(),
                );
                let actual_ctx: Vec<String> =
                    if hunk.old_start.saturating_sub(1) < original_lines.len() {
                        original_lines[hunk.old_start.saturating_sub(1)..actual_end]
                            .iter()
                            .map(|line| (*line).to_string())
                            .collect()
                    } else {
                        vec![]
                    };

                failed_hunks.push(FailedHunk {
                    hunk_index: hunk_idx,
                    old_start: hunk.old_start,
                    old_count: hunk.old_count,
                    expected_context: expected_ctx,
                    actual_context: actual_ctx,
                    reason: error,
                });
            }
        }
    }

    if let Some(output) = result_text_builder.as_mut() {
        for line in &original_lines[source_cursor..] {
            append_line(output, &mut has_output_line, line, false);
        }
    }
    let applies = hunks_failed == 0;
    let built_result = result_text_builder;
    let result_text = if return_result_text {
        Some(built_result.as_deref().unwrap_or_default().to_string())
    } else {
        None
    };
    let result_text_ref = if hunks_applied == 0 && !return_result_text {
        original_text
    } else {
        built_result.as_deref().unwrap_or(original_text)
    };
    let newline_after = detect_newline_style(result_text_ref);

    if hunks_failed > 0 {
        findings.push(format!(
            "{} of {} hunks failed to apply",
            hunks_failed, hunks_total
        ));
    }

    let result_fingerprint = if return_result_fingerprint {
        fingerprint(result_text_ref)
    } else {
        String::new()
    };

    PatchApplyCheckResult {
        patch_parse_ok: true,
        applies,
        hunks_total,
        hunks_applied,
        hunks_failed,
        failed_hunks,
        affected_line_ranges,
        newline_style_before: newline_before,
        newline_style_after: newline_after,
        result_fingerprint,
        result_text,
        findings,
    }
}

pub fn patch_summary(patch_text: &str) -> PatchSummaryResult {
    let mut findings: Vec<String> = vec![];

    if patch_text.len() > MAX_PATCH_LENGTH {
        return PatchSummaryResult {
            files_changed: 0,
            hunks_total: 0,
            additions: 0,
            deletions: 0,
            renames_detected: vec![],
            binary_patch_detected: false,
            line_ranges_by_file: BTreeMap::new(),
            findings: vec![format!(
                "Patch text exceeds maximum length of {}",
                MAX_PATCH_LENGTH
            )],
        };
    }

    let parse_result = parse_unified_diff(patch_text);

    if !parse_result.ok {
        return PatchSummaryResult {
            files_changed: 0,
            hunks_total: 0,
            additions: 0,
            deletions: 0,
            renames_detected: vec![],
            binary_patch_detected: false,
            line_ranges_by_file: BTreeMap::new(),
            findings: vec![format!(
                "Failed to parse patch: {}",
                parse_result.error.unwrap_or_default()
            )],
        };
    }

    let files_changed = parse_result.files.len();
    let mut hunks_total = 0;
    let mut additions = 0;
    let mut deletions = 0;
    let mut renames_detected: Vec<RenamePair> = vec![];
    let mut binary_patch_detected = false;
    let mut line_ranges_by_file: BTreeMap<String, Vec<LineRange>> = BTreeMap::new();

    for file_entry in &parse_result.files {
        let old_file = &file_entry.old_file;
        let new_file = &file_entry.new_file;

        if !old_file.is_empty() && !new_file.is_empty() && old_file != new_file {
            renames_detected.push(RenamePair {
                from: old_file.clone(),
                to: new_file.clone(),
            });
        }

        let file_key = if new_file.is_empty() {
            old_file.clone()
        } else {
            new_file.clone()
        };
        let mut file_ranges: Vec<LineRange> = vec![];

        for hunk in &file_entry.hunks {
            hunks_total += 1;
            let mut hunk_additions = 0;
            let mut hunk_deletions = 0;

            for hline in &hunk.lines {
                let normalized = normalize_line(hline);
                if normalized.starts_with('+') {
                    hunk_additions += 1;
                } else if normalized.starts_with('-') {
                    hunk_deletions += 1;
                }
            }

            additions += hunk_additions;
            deletions += hunk_deletions;

            file_ranges.push(line_range(hunk.new_start, hunk.new_count));
        }

        if !file_key.is_empty() {
            line_ranges_by_file.insert(file_key, file_ranges);
        }
    }

    if patch_text.contains("GIT binary patch") || patch_text.contains('\0') {
        binary_patch_detected = true;
        findings.push("Binary patch content detected".to_string());
    }

    if parse_result.files.is_empty() {
        findings.push("No file headers found in patch".to_string());
    }

    PatchSummaryResult {
        files_changed,
        hunks_total,
        additions,
        deletions,
        renames_detected,
        binary_patch_detected,
        line_ranges_by_file,
        findings,
    }
}