sashiko 0.2.4

Agentic code review system for Linux kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// Copyright 2026 The Sashiko Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::{Result, anyhow};
use mail_parser::{HeaderValue, MessageParser};
use regex::Regex;
use std::sync::OnceLock;

#[derive(Debug)]
#[allow(dead_code)]
pub struct PatchsetMetadata {
    pub message_id: String,
    pub subject: String,
    pub author: String,
    pub date: i64,
    pub received_date: Option<i64>,
    pub in_reply_to: Option<String>,
    pub references: Vec<String>,
    pub index: u32,
    pub total: u32,
    pub to: String,
    pub cc: String,
    pub is_patch_or_cover: bool,
    pub version: Option<u32>,
    pub body: String,
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct Patch {
    pub message_id: String,
    pub body: String,
    pub diff: String,
    pub part_index: u32,
}

pub fn extract_received_date(raw_email: &[u8]) -> Option<i64> {
    let header_end = raw_email
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .unwrap_or(raw_email.len());
    let headers_bytes = &raw_email[..header_end];
    let headers_str = String::from_utf8_lossy(headers_bytes);

    let mut current_header = String::new();
    let mut in_received = false;

    for line in headers_str.lines() {
        if line.starts_with("Received:") {
            if in_received {
                break;
            }
            in_received = true;
            current_header.push_str(line);
        } else if in_received && (line.starts_with(' ') || line.starts_with('\t')) {
            current_header.push_str(line);
        } else if in_received {
            break;
        }
    }

    if current_header.is_empty() {
        return None;
    }

    if let Some(semi_idx) = current_header.rfind(';') {
        let date_str = current_header[semi_idx + 1..].trim();
        if let Ok(dt) = chrono::DateTime::parse_from_rfc2822(date_str) {
            return Some(dt.timestamp());
        }
    }

    None
}

pub fn parse_email(raw_email: &[u8]) -> Result<(PatchsetMetadata, Option<Patch>)> {
    let received_date = extract_received_date(raw_email);

    let message = MessageParser::default()
        .with_address_headers()
        .with_message_ids()
        .header_text(mail_parser::HeaderName::Subject)
        .header_date(mail_parser::HeaderName::Date)
        .header_address("X-Original-From")
        .parse(raw_email)
        .ok_or_else(|| anyhow!("Failed to parse email"))?;

    let message_id = message
        .message_id()
        .ok_or_else(|| anyhow!("No Message-ID header"))?
        .to_string();

    let subject = message.subject().unwrap_or("(no subject)").to_string();

    let mut author = message
        .from()
        .and_then(|addr| addr.first())
        .map(|a| {
            let name = a.name().unwrap_or_default().trim();
            let address = a.address().unwrap_or("unknown@localhost").trim();
            let addr = if address.is_empty() || !address.contains('@') {
                "unknown@localhost"
            } else {
                address
            };
            if name.is_empty() || name.to_lowercase() == "unknown" {
                addr.to_string()
            } else {
                format!("{} <{}>", name, addr)
            }
        })
        .unwrap_or_else(|| "unknown@localhost".to_string());

    if let Some(first_addr) = message.header("X-Original-From").and_then(|h| match h {
        mail_parser::HeaderValue::Address(x_orig_addr) => x_orig_addr.first(),
        _ => None,
    }) {
        let name = first_addr.name().unwrap_or_default().trim();
        let address = first_addr.address().unwrap_or("").trim();
        let author_email = extract_email(&author);
        if !address.is_empty() && address.contains('@') {
            if is_b4_alias(&author_email, address) {
                author = if name.is_empty() || name.to_lowercase() == "unknown" {
                    address.to_string()
                } else {
                    format!("{} <{}>", name, address)
                };
            } else if author_email.to_lowercase().starts_with("devnull+") {
                tracing::warn!(
                    "Ignoring unverified X-Original-From header due to alias mismatch with From header"
                );
            }
        }
    }

    let date = message.date().map(|d| d.to_timestamp()).unwrap_or(0);

    let to = message
        .to()
        .map(|addr| {
            addr.iter()
                .filter_map(|a| {
                    let address = a.address().unwrap_or("").trim();
                    if address.is_empty() || !address.contains('@') {
                        None
                    } else {
                        let name = a.name().unwrap_or_default().trim();
                        if name.is_empty() {
                            Some(address.to_string())
                        } else {
                            Some(format!("\"{}\" <{}>", name.replace("\"", "\\\""), address))
                        }
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        })
        .unwrap_or_default();

    let cc = message
        .cc()
        .map(|addr| {
            addr.iter()
                .filter_map(|a| {
                    let address = a.address().unwrap_or("").trim();
                    if address.is_empty() || !address.contains('@') {
                        None
                    } else {
                        let name = a.name().unwrap_or_default().trim();
                        if name.is_empty() {
                            Some(address.to_string())
                        } else {
                            Some(format!("\"{}\" <{}>", name.replace("\"", "\\\""), address))
                        }
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        })
        .unwrap_or_default();

    let in_reply_to = match message.in_reply_to() {
        HeaderValue::Text(t) => Some(t.to_string()),
        HeaderValue::TextList(l) => l.first().map(|s| s.to_string()),
        _ => None,
    };

    let references = match message.references() {
        HeaderValue::Text(t) => vec![t.to_string()],
        HeaderValue::TextList(l) => l.iter().map(|s| s.to_string()).collect(),
        _ => vec![],
    };

    let (index, total) = parse_subject_index(&subject);
    let version = parse_subject_version(&subject);

    let mut body = String::new();
    for i in 0..message.text_body_count() {
        if let Some(text) = message.body_text(i) {
            if !body.is_empty() {
                body.push('\n');
            }
            body.push_str(&text);
        }
    }

    let diff = if body.contains("diff --git")
        || (body.contains("--- ") && body.contains("+++ ") && body.contains("@@ -"))
    {
        body.clone()
    } else {
        String::new()
    };

    // Detection logic
    let subject_lower = subject.to_lowercase();
    let subject_clean = subject_lower.trim();
    let is_reply = subject_clean.starts_with("re:")
        || subject_clean.starts_with("fwd:")
        || subject_clean.starts_with("forwarded:")
        || subject_clean.starts_with("aw:") // German 'Antwort'
        || subject_clean.starts_with("wg:") // German 'Weitergeleitet'
        || subject_clean.starts_with("回复:") // Chinese 'Re'
        || subject_clean.starts_with("回复:") // Chinese 'Re' with full-width colon
        || subject_clean.starts_with("答复:") // Chinese 'Reply'
        || subject_clean.starts_with("答复:") // Chinese 'Reply'
        || subject_clean.starts_with("[reproducer]") // Reproducers
        || subject_lower.contains("(was ")
        || subject_lower.contains("(was:");
    let has_patch_tag = subject_clean.contains("patch") || subject_clean.contains("rfc");
    let has_diff = !diff.is_empty();

    // A message is part of a series if it's a cover letter (index 0) or has multiple parts (total > 1)
    let is_series_metadata = total > 1 || index == 0;

    // It is a patch or cover letter if:
    // 1. It is NOT a reply (Re: ...)
    // 2. AND (It has [PATCH]/[RFC] tag OR it has a diff OR it looks like a series cover letter/part)
    let is_patch_or_cover = !is_reply && (has_patch_tag || has_diff || is_series_metadata);

    let metadata = PatchsetMetadata {
        message_id: message_id.clone(),
        subject,
        author,
        date,
        received_date,
        in_reply_to,
        references,
        index,
        total,
        to,
        cc,
        is_patch_or_cover,
        version,
        body: body.clone(),
    };

    let patch = if has_diff && index != 0 {
        Some(Patch {
            message_id,
            body,
            diff,
            part_index: index,
        })
    } else {
        None
    };

    Ok((metadata, patch))
}

fn parse_subject_index(subject: &str) -> (u32, u32) {
    static RE_BRACKETS: OnceLock<Regex> = OnceLock::new();
    // Match [ ... M/N ... ] but strictly require PATCH, RFC, RESEND or vN before the M/N
    let re_brackets = RE_BRACKETS.get_or_init(|| {
        Regex::new(r"(?i)\[.*?\b(?:PATCH|RFC|RESEND|v\d+)\b.*?(\d+)/(\d+).*?\]").unwrap()
    });

    if let Some(caps) = re_brackets.captures(subject)
        && let (Some(i), Some(t)) = (caps.get(1), caps.get(2))
    {
        let index = i.as_str().parse().unwrap_or(1);
        let total = t.as_str().parse().unwrap_or(1);
        return (index, total);
    }

    static RE_LOOSE: OnceLock<Regex> = OnceLock::new();
    // Match PATCH M/N or RFC M/N (case insensitive)
    let re_loose =
        RE_LOOSE.get_or_init(|| Regex::new(r"(?i)\b(?:PATCH|RFC|RESEND)\s+(\d+)/(\d+)\b").unwrap());

    if let Some(caps) = re_loose.captures(subject)
        && let (Some(i), Some(t)) = (caps.get(1), caps.get(2))
    {
        let index = i.as_str().parse().unwrap_or(1);
        let total = t.as_str().parse().unwrap_or(1);
        return (index, total);
    }

    // Check cleaned subject for "1/2" at start (Handles "[PATCH] 1/2")
    let cleaned = clean_subject(subject);
    static RE_START: OnceLock<Regex> = OnceLock::new();
    let re_start = RE_START.get_or_init(|| Regex::new(r"^\s*(\d+)/(\d+)\b").unwrap());
    if let Some(caps) = re_start.captures(&cleaned)
        && let (Some(i), Some(t)) = (caps.get(1), caps.get(2))
    {
        let index = i.as_str().parse().unwrap_or(1);
        let total = t.as_str().parse().unwrap_or(1);
        return (index, total);
    }

    (1, 1)
}

pub fn parse_subject_version(subject: &str) -> Option<u32> {
    static RE_VER: OnceLock<Regex> = OnceLock::new();
    // Strategy:
    // 1. Inside [...] blocks: find vN preceded by word boundary (e.g. [PATCH v2], [v2])
    // 2. Start of string: ^vN followed by word boundary
    // 3. Following PATCH: PATCH followed by non-word chars and vN (e.g. PATCHv2, [PATCH] v2)
    let re = RE_VER.get_or_init(|| {
        Regex::new(r"(?i)(?:\[[^\]]*?\bv(\d+)\b[^\]]*?\]|^\s*v(\d+)\b|PATCH\W*v(\d+)\b)").unwrap()
    });

    if let Some(caps) = re.captures(subject) {
        if let Some(m) = caps.get(1) {
            return m.as_str().parse().ok();
        }
        if let Some(m) = caps.get(2) {
            return m.as_str().parse().ok();
        }
        if let Some(m) = caps.get(3) {
            return m.as_str().parse().ok();
        }
    }
    None
}

pub fn get_subject_prefixes(subject: &str) -> Vec<String> {
    static RE_BRACKETS: OnceLock<Regex> = OnceLock::new();
    let re = RE_BRACKETS.get_or_init(|| Regex::new(r"\[(.*?)\]").unwrap());

    let mut prefixes = Vec::new();

    for cap in re.captures_iter(subject) {
        if let Some(content) = cap.get(1) {
            // Split by whitespace or non-word characters.
            // "PATCH net-next 1/2" -> "PATCH", "net-next", "1/2"
            // "PATCH,net-next,1/2" -> "PATCH", "net-next", "1/2"
            let tokens: Vec<&str> = content
                .as_str()
                .split(|c: char| !c.is_alphanumeric() && c != '-' && c != '.' && c != '_')
                .filter(|s| !s.is_empty())
                .collect();

            for token in tokens {
                let lower = token.to_lowercase();
                // Ignore standard tags
                if lower == "patch" || lower == "rfc" || lower == "resend" {
                    continue;
                }
                // Ignore versions (v2, v10)
                if lower.starts_with('v') && lower[1..].chars().all(|c| c.is_ascii_digit()) {
                    continue;
                }
                // Ignore pure numbers (often part of 1/2 or just garbage)
                if token.chars().all(|c| c.is_ascii_digit()) {
                    continue;
                }

                prefixes.push(token.to_string());
            }
        }
    }
    prefixes.sort();
    prefixes.dedup();
    prefixes
}

pub fn clean_subject(subject: &str) -> String {
    static RE_BRACKETS: OnceLock<Regex> = OnceLock::new();
    let re = RE_BRACKETS.get_or_init(|| Regex::new(r"\[.*?\]").unwrap());

    // 1. Remove [...] blocks
    let no_brackets = re.replace_all(subject, "");

    // 2. Remove Re:, Fwd: prefixes (case insensitive)
    let mut cleaned = no_brackets.trim().to_string();
    let prefixes = ["re:", "fwd:", "aw:", "forwarded:", "回复:", "回复:"];

    let mut changed = true;
    while changed {
        changed = false;
        let lower = cleaned.to_lowercase();
        for prefix in &prefixes {
            if lower.starts_with(prefix)
                && let Some(rest) = cleaned.get(prefix.len()..)
            {
                cleaned = rest.trim().to_string();
                changed = true;
                break;
            }
        }
    }

    cleaned
}

pub fn extract_email(author: &str) -> String {
    if let Some(start) = author.find('<')
        && let Some(end) = author.find('>')
        && end > start
    {
        return author[start + 1..end].trim().to_string();
    }
    author.trim().to_string()
}

pub fn authors_match(a: &str, b: &str) -> bool {
    let email_a = extract_email(a);
    let email_b = extract_email(b);

    if email_a == email_b {
        return true;
    }

    is_b4_alias(&email_a, &email_b) || is_b4_alias(&email_b, &email_a)
}

fn is_b4_alias(alias: &str, real: &str) -> bool {
    let alias_lower = alias.to_lowercase();
    if !alias_lower.starts_with("devnull+") {
        return false;
    }
    let Some(at_idx) = alias_lower.rfind('@') else {
        return false;
    };
    if at_idx <= 8 {
        return false;
    }

    let encoded_part = &alias_lower[8..at_idx];
    let alias_domain = &alias_lower[at_idx + 1..];

    if alias_domain != "kernel.org" && alias_domain != "linux.dev" {
        return false;
    }

    let real_lower = real.to_lowercase();
    encoded_part == real_lower.replace('@', ".")
}

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

    #[test]
    fn test_authors_match() {
        assert!(authors_match(
            "Real Author <author@example.com>",
            "Real Author <author@example.com>"
        ));
        assert!(authors_match(
            "devnull+author.example.com@kernel.org",
            "author@example.com"
        ));
        assert!(authors_match(
            "Real Author <author@example.com>",
            "Real Author via B4 Relay <devnull+author.example.com@kernel.org>"
        ));
        assert!(!authors_match("other@example.com", "author@example.com"));
        assert!(!authors_match(
            "devnull+author.example.com@spam.org",
            "author@example.com"
        ));
    }

    #[test]
    fn test_extract_email() {
        assert_eq!(
            extract_email("Name <email@example.com>"),
            "email@example.com"
        );
        assert_eq!(extract_email("email@example.com"), "email@example.com");
        assert_eq!(extract_email(" <email@example.com> "), "email@example.com");
        assert_eq!(
            extract_email("Name < email@example.com >"),
            "email@example.com"
        );
        assert_eq!(extract_email("Invalid < Format"), "Invalid < Format");
    }

    #[test]
    fn test_extract_received_date() {
        let email = b"Received: from mail.example.com ([192.0.2.1])\r\n \
by mail.example.org with ESMTPS ;\r\n \
Tue, 12 May 2026 00:12:30 +0000\r\n\
\r\n\
Body";
        let expected = chrono::DateTime::parse_from_rfc2822("Tue, 12 May 2026 00:12:30 +0000")
            .unwrap()
            .timestamp();
        assert_eq!(extract_received_date(email), Some(expected));

        let email_no_received = b"Subject: Test\r\n\
            \r\n\
            Body";
        assert_eq!(extract_received_date(email_no_received), None);

        let email_malformed_date = b"Received: from ... ; Invalid Date\r\n\
            \r\n\
            Body";
        assert_eq!(extract_received_date(email_malformed_date), None);
    }

    #[test]
    fn test_clean_subject() {
        assert_eq!(clean_subject("[PATCH] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("[PATCH v2] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("[PATCH 1/2] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("Re: [PATCH] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("[PATCH] Re: Fix bug"), "Fix bug"); // "[PATCH] " removed, then "Re: Fix bug" -> "Fix bug"
        assert_eq!(clean_subject("Subject only"), "Subject only");
        assert_eq!(
            clean_subject("[RFC] [PATCH v3] Complex subject"),
            "Complex subject"
        );
    }

    #[test]
    fn test_clean_subject_chinese() {
        assert_eq!(clean_subject("回复: [PATCH] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("回复:[PATCH] Fix bug"), "Fix bug");
        assert_eq!(clean_subject("回复:回复:[PATCH] Fix bug"), "Fix bug");
    }

    #[test]
    fn test_chinese_reply() {
        let raw =
            b"Message-ID: <reply>\r\nSubject: \xE5\x9B\x9E\xE5\xA4\x8D: [PATCH] fix\r\n\r\nBody";
        // \xE5\x9B\x9E\xE5\xA4\x8D is "回复" in UTF-8.
        let (meta, _) = parse_email(raw).unwrap();
        assert!(
            !meta.is_patch_or_cover,
            "Chinese reply should not be a patchset"
        );
    }

    #[test]
    fn test_author_parsing() {
        let raw =
            b"Message-ID: <123>\r\nFrom: Test User <test@example.com>\r\nSubject: Test\r\n\r\nBody";
        let (meta, _) = parse_email(raw).unwrap();
        assert_eq!(meta.author, "Test User <test@example.com>");

        let raw_no_name =
            b"Message-ID: <456>\r\nFrom: test2@example.com\r\nSubject: Test\r\n\r\nBody";
        let (meta2, _) = parse_email(raw_no_name).unwrap();
        assert_eq!(meta2.author, "test2@example.com");

        let raw_malformed =
            b"Message-ID: <789>\r\nFrom: \"fqr\" <user.email>\r\nSubject: Test\r\n\r\nBody";
        let (meta3, _) = parse_email(raw_malformed).unwrap();
        assert_eq!(meta3.author, "fqr <unknown@localhost>");
    }

    #[test]
    fn test_b4_relay_author_parsing() {
        let raw = b"Message-ID: <b4-relay-test>\r\n\
                    From: Real Author via B4 Relay <devnull+author.example.com@kernel.org>\r\n\
                    X-Original-From: Real Author <author@example.com>\r\n\
                    Subject: Test B4 Relay\r\n\r\nBody";
        let (meta, _) = parse_email(raw).unwrap();
        assert_eq!(meta.author, "Real Author <author@example.com>");
    }

    #[test]
    fn test_b4_relay_mismatch_fallback() {
        // Verification: If From is a B4 Relay alias, but X-Original-From is a completely
        // different address, Sashiko ignores the override and falls back to the From alias.
        let raw_mismatch = b"Message-ID: <mismatch-test-2>\r\n\
                             From: Real Author via B4 Relay <devnull+author.example.com@kernel.org>\r\n\
                             X-Original-From: Author Two <author2@example.com>\r\n\
                             Subject: Normal Patch\r\n\r\nBody";
        let (meta_mismatch, _) = parse_email(raw_mismatch).unwrap();
        assert_eq!(
            meta_mismatch.author,
            "Real Author via B4 Relay <devnull+author.example.com@kernel.org>"
        );
    }

    #[test]
    fn test_recipient_parsing() {
        let raw = b"Message-ID: <1>\r\nFrom: a@b.com\r\nTo: \"Valid User\" <valid@example.com>, invalid_no_at, <another@test.com>\r\nCc: Bad <bad>, \"Good\" <good@example.com>\r\nSubject: Test\r\n\r\nBody";
        let (meta, _) = parse_email(raw).unwrap();
        assert_eq!(
            meta.to,
            "\"Valid User\" <valid@example.com>, another@test.com"
        );
        assert_eq!(meta.cc, "\"Good\" <good@example.com>");
    }

    #[test]
    fn test_reply_with_diff_is_not_patchset() {
        // A message that starts with Re: but contains diff --git
        // This simulates a reply quoting a patch or sending an inline fixup
        let raw = b"Message-ID: <123>\r\nSubject: Re: [PATCH] fix bug\r\n\r\n> diff --git a/file b/file\n> index...";
        let (meta, _) = parse_email(raw).unwrap();

        // This fails with current logic because has_diff is true
        assert!(
            !meta.is_patch_or_cover,
            "Reply with diff should NOT be a patchset"
        );
    }

    #[test]
    fn test_diff_without_patch_tag_ignored() {
        let raw = b"Message-ID: <diffnopatch>\r\nSubject: Random fix\r\n\r\ndiff --git a/file b/file\nindex...";
        let (meta, _) = parse_email(raw).unwrap();
        assert!(
            meta.is_patch_or_cover,
            "Diff without [PATCH] tag should still be parsed as patch"
        );
    }

    #[test]
    fn test_normal_patch() {
        let raw = b"Message-ID: <456>\r\nSubject: [PATCH] fix bug\r\n\r\ndiff --git a/file b/file\nindex...";
        let (meta, _) = parse_email(raw).unwrap();
        assert!(meta.is_patch_or_cover);
    }

    #[test]
    fn test_single_patch_no_diff_ignored() {
        let raw =
            b"Message-ID: <nonpatch>\r\nSubject: [PATCH] discussion\r\n\r\nThis is not a patch";
        let (meta, _) = parse_email(raw).unwrap();
        assert!(
            meta.is_patch_or_cover,
            "Single patch without diff should still be parsed due to [PATCH] tag"
        );
    }

    #[test]
    fn test_cover_letter() {
        let raw = b"Message-ID: <789>\r\nSubject: [PATCH 0/5] fix bug\r\n\r\nCover letter body";
        let (meta, patch) = parse_email(raw).unwrap();
        assert!(meta.is_patch_or_cover);
        assert!(patch.is_none());
    }

    #[test]
    fn test_cover_letter_with_diff() {
        let raw = b"Message-ID: <cover_with_diff>\r\nSubject: [PATCH 0/5] fix bug\r\n\r\nExplanation:\ndiff --git a/file b/file\nindex...";
        let (meta, patch) = parse_email(raw).unwrap();
        assert!(meta.is_patch_or_cover);
        assert!(
            patch.is_none(),
            "Cover letter (index 0) with diff should NOT be a patch"
        );
    }

    #[test]
    fn test_pure_reply() {
        let raw = b"Message-ID: <abc>\r\nSubject: Re: [PATCH] fix bug\r\n\r\nLGTM";
        let (meta, _) = parse_email(raw).unwrap();
        assert!(!meta.is_patch_or_cover);
    }

    #[test]
    fn test_rfc_patch_parsing() {
        let subject = "[RFC PATCH 1/3] My RFC";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 3);
    }

    #[test]
    fn test_version_parsing() {
        assert_eq!(parse_subject_version("[PATCH v2] subject"), Some(2));
        assert_eq!(parse_subject_version("[PATCH v3 1/2] subject"), Some(3));
        assert_eq!(parse_subject_version("[PATCH] subject"), None); // v1 implicit
        assert_eq!(parse_subject_version("[RFC v4] subject"), Some(4));
        assert_eq!(parse_subject_version("[PATCH -v2] subject"), Some(2));
        assert_eq!(parse_subject_version("Subject with v2 inside"), None); // v2 ignored
        assert_eq!(parse_subject_version("Subject with devicetree"), None); // 'dev' should not match
        assert_eq!(parse_subject_version("[PATCH 0/10]"), None); // 0/10 is not version
        assert_eq!(parse_subject_version("[PATCH v12]"), Some(12));

        // New cases from analysis
        assert_eq!(parse_subject_version("[PATCH V2 13/13]"), Some(2)); // Uppercase V
        assert_eq!(parse_subject_version("[PATCH bpf-next v5 10/10]"), Some(5)); // Subsystem prefix
        assert_eq!(parse_subject_version("[PATCH RFC v2 8/8]"), Some(2)); // RFC + Version
        assert_eq!(parse_subject_version("[PATCHv5 2/2]"), Some(5)); // Attached version
        assert_eq!(parse_subject_version("[PATCH 00/33 v6]"), Some(6)); // Version at end
        assert_eq!(parse_subject_version("[v3 PATCH 1/1]"), Some(3)); // Version at start

        // Edge case: [PATCH] v3: ...
        assert_eq!(parse_subject_version("[PATCH] v3: subject"), Some(3));
    }

    #[test]
    fn test_complex_prefix_parsing() {
        let subject = "[PATCH v2 net-next 02/14] Something";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 2);
        assert_eq!(total, 14);
    }

    #[test]
    fn test_no_patch_prefix_parsing() {
        // Some lists might just use [RFC 1/2]
        let subject = "[RFC 1/2] Just RFC";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 2);
    }

    #[test]
    fn test_missed_cover_letter_parsing() {
        let subject = "[PATCH 6.18 000/430] 6.18.3-rc1 review";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 0);
        assert_eq!(total, 430);

        let raw = format!("Message-ID: <123>\r\nSubject: {}\r\n\r\nBody", subject);
        let (meta, _) = parse_email(raw.as_bytes()).unwrap();
        assert!(meta.is_patch_or_cover, "Should be detected as patch/cover");
    }

    #[test]
    fn test_forwarded_reply_is_not_patch() {
        // "Forwarded: Re: ..." should be treated as reply/skip if it has no diff,
        // or if it has diff but looks like a forwarded reply.
        // If it has diff, it might be a forwarded patch.
        // But if it starts with "Re:", it's usually a reply.
        // "Forwarded: Re:" -> effectively a reply.
        let subject = "Forwarded: Re: [syzbot] WARNING in cm109_urb_irq_callback";
        let raw = format!(
            "Message-ID: <456>\r\nSubject: {}\r\n\r\nDiff:\n--- a\n+++ b\n@@ -1 +1 @@",
            subject
        );
        let (meta, _) = parse_email(raw.as_bytes()).unwrap();

        // Current logic might think this is a patch because it has diff and doesn't start with "Re:" (starts with "Forwarded:")
        // We want to ensure it is handled correctly (either as patch if it IS a patch, or ignored if it's just a reply).
        // If it's "Forwarded: Re:", it's likely a discussion.
        // Let's assert what we expect. I expect it NOT to be a patchset root.
        assert!(
            !meta.is_patch_or_cover,
            "Forwarded Re: should not be a patchset"
        );
    }

    #[test]
    fn test_loose_patch_parsing() {
        // Case 1: PATCH prefix
        let subject = "PATCH 1/2: Subject";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 2);

        // Case 2: Start of string
        let subject = "1/2: Subject";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 2);

        // Case 3: Leading zeros
        let subject = "[PATCH 01/02] Subject";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 2);

        // Case 4: Regression test for false positive (508/512)
        let subject = "[PATCH v3] serial: 8250_pci: Fix broken RS485 for F81504/508/512";
        let (index, total) = parse_subject_index(subject);
        assert_eq!(index, 1);
        assert_eq!(total, 1); // Should be 1/1, NOT 508/512
    }

    #[test]
    fn test_get_subject_prefixes() {
        assert_eq!(
            get_subject_prefixes("[PATCH net-next 1/2]"),
            vec!["net-next"]
        );
        assert_eq!(
            get_subject_prefixes("[PATCH v2 bpf-next]"),
            vec!["bpf-next"]
        );
        assert_eq!(get_subject_prefixes("[PATCH RFC]"), Vec::<String>::new());
        assert_eq!(get_subject_prefixes("[PATCH 00/10]"), Vec::<String>::new()); // numbers ignored
        assert_eq!(get_subject_prefixes("[PATCH 6.18]"), vec!["6.18"]);
        assert_eq!(
            get_subject_prefixes("[PATCH net-next v3 0/1]"),
            vec!["net-next"]
        );
        assert_eq!(
            get_subject_prefixes("[PATCH net-next,bpf 1/2]"),
            vec!["bpf", "net-next"]
        ); // sorted
        assert_eq!(get_subject_prefixes("[PATCH]"), Vec::<String>::new());
    }
}