provenant-cli 1.0.9

Fast Rust scanner for licenses, copyrights, package metadata, SBOMs, and provenance data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashSet;
use std::sync::LazyLock;

use regex::Regex;

use super::super::token_utils::normalize_whitespace;
use crate::copyright::line_tracking::PreparedLines;
use crate::copyright::prepare::prepare_text_line;
use crate::copyright::refiner::{
    contains_xml_markup_declaration_token, looks_like_name_with_parenthesized_url, refine_author,
};
use crate::copyright::types::{AuthorDetection, CopyrightDetection};
use crate::models::LineNumber;

pub(in super::super) fn drop_merged_dash_bullet_attribution_authors(
    authors: &mut Vec<AuthorDetection>,
) {
    authors.retain(|author| {
        let lower = author.author.to_ascii_lowercase();
        !(lower.contains(" - updated by ")
            || lower.contains(" - added to by ")
            || lower.contains(" - ported to ")
            || lower.contains(" - adapted to ")
            || lower.contains(" - modified by ")
            || lower.contains(" - valuable contributions by ")
            || lower.starts_with("mainline integration by ")
            || lower.starts_with("updated by ")
            || lower.starts_with("added to by ")
            || lower.starts_with("ported to ")
            || lower.starts_with("adapted to ")
            || lower.starts_with("modified by ")
            || lower.starts_with("valuable contributions by "))
    });
}

pub(in super::super) fn refine_author_with_optional_handle_suffix(
    candidate: &str,
) -> Option<String> {
    static TRAILING_HANDLE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\s*\(@[A-Za-z0-9_.-]+\)\s*$").unwrap());
    static TRAILING_BARE_HANDLE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?x)^(?P<base>.+?)\s+@[A-Za-z0-9_.-]+\s*$").unwrap());
    static TRAILING_COMMA_HANDLE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?x)
                ^(?P<base>.+?),
                \s*
                (?P<handle>@?[A-Za-z0-9_.-]+)
                \s*$
            ",
        )
        .unwrap()
    });

    let trimmed = candidate.trim();
    if trimmed.is_empty() {
        return None;
    }

    let without_handle = TRAILING_HANDLE_RE.replace(trimmed, "").trim().to_string();
    if without_handle != trimmed {
        return refine_author(&without_handle);
    }

    if let Some(captures) = TRAILING_BARE_HANDLE_RE.captures(trimmed) {
        let base = captures
            .name("base")
            .map(|m| m.as_str())
            .unwrap_or("")
            .trim();
        if !base.is_empty() {
            return refine_author(base);
        }
    }

    if let Some(captures) = TRAILING_COMMA_HANDLE_RE.captures(trimmed) {
        let base = captures
            .name("base")
            .map(|m| m.as_str())
            .unwrap_or("")
            .trim();
        let handle = captures
            .name("handle")
            .map(|m| m.as_str())
            .unwrap_or("")
            .trim();
        let bare_handle = handle.trim_start_matches('@');
        let looks_like_handle = !bare_handle.is_empty()
            && (handle.starts_with('@')
                || bare_handle.chars().any(|ch| ch.is_ascii_digit())
                || (bare_handle.len() >= 3
                    && bare_handle
                        .chars()
                        .all(|ch| !ch.is_ascii_alphabetic() || ch.is_ascii_lowercase())));
        if looks_like_handle {
            return refine_author(base);
        }
    }

    refine_author(trimmed)
}

pub(in super::super) fn refine_particle_name(candidate: &str) -> Option<String> {
    const NAME_PARTICLES: &[&str] = &[
        "al", "bin", "da", "de", "del", "della", "der", "di", "dos", "du", "la", "le", "the",
        "van", "von", "y",
    ];

    let candidate = candidate.trim().trim_end_matches('.').trim();
    let words: Vec<&str> = candidate.split_whitespace().collect();
    if words.len() < 3 || words.len() > 6 {
        return None;
    }
    let mut uppercase_words = 0;
    for word in words {
        let normalized = word.trim_matches(|ch: char| !ch.is_alphanumeric());
        let first = normalized.chars().find(|ch| ch.is_alphabetic())?;
        if first.is_uppercase() {
            uppercase_words += 1;
        } else if !NAME_PARTICLES.contains(&normalized.to_ascii_lowercase().as_str()) {
            return None;
        }
    }
    (uppercase_words >= 2).then(|| candidate.to_string())
}

pub(in super::super) fn drop_authors_embedded_in_copyrights(
    copyrights: &[CopyrightDetection],
    authors: &mut Vec<AuthorDetection>,
) {
    if copyrights.is_empty() || authors.is_empty() {
        return;
    }

    authors.retain(|a| {
        let a_lower = a.author.to_lowercase();
        !copyrights.iter().any(|c| {
            if a.start_line < c.start_line || a.end_line > c.end_line {
                return false;
            }
            let c_lower = c.copyright.to_lowercase();
            if a.author.contains('@')
                && c_lower.starts_with("copyright")
                && c_lower.contains(&a_lower)
            {
                return true;
            }
            if c_lower.contains("authors") {
                if a.author.contains('@') {
                    return false;
                }
                return c_lower.contains(&a_lower);
            }
            if c_lower.contains("author") {
                return c_lower.contains(&a_lower);
            }
            false
        })
    });
}

pub(in super::super) fn drop_authors_from_copyright_by_lines(
    prepared_cache: &PreparedLines<'_>,
    authors: &mut Vec<AuthorDetection>,
) {
    if authors.is_empty() || prepared_cache.is_empty() {
        return;
    }

    static YEAR_PREFIX_BY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?i)^\s*(?:[/#*;!-]+\s*)?(?:\d{4}(?:[-–/]\d{1,4})*|\d{4}\s*[-–]\s*\d{4})\s+by\s+",
        )
        .unwrap()
    });
    static INLINE_ATTRIBUTION_PARENS_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)\((?:written|authored|created|developed)\s+by\s+[^)]+\)").unwrap()
    });

    authors.retain(|author| {
        let author_lower = author.author.to_ascii_lowercase();
        let mut line_number = author.start_line;

        loop {
            let Some(raw) = prepared_cache.line(line_number).map(|line| line.raw) else {
                return true;
            };
            let lower = raw.to_ascii_lowercase();
            if INLINE_ATTRIBUTION_PARENS_RE.is_match(raw) {
                if line_number == author.end_line {
                    return true;
                }
                line_number = line_number.next();
                continue;
            }
            if lower.trim_start().starts_with("copyright")
                && lower.contains(" by ")
                && lower.contains(&author_lower)
            {
                return false;
            }

            if let Some(prev_line_number) = line_number.prev()
                && let Some(prev) = prepared_cache.line(prev_line_number).map(|line| line.raw)
            {
                let prev_lower = prev.to_ascii_lowercase();
                if prev_lower.contains("copyright")
                    && YEAR_PREFIX_BY_RE.is_match(raw)
                    && lower.contains(&author_lower)
                {
                    return false;
                }
            }

            if line_number == author.end_line {
                return true;
            }
            line_number = line_number.next();
        }
    });
}

pub(in super::super) fn drop_author_colon_lines_absorbed_into_year_only_copyrights(
    prepared_cache: &PreparedLines<'_>,
    copyrights: &[CopyrightDetection],
    authors: &mut Vec<AuthorDetection>,
) {
    if copyrights.is_empty() || authors.is_empty() || prepared_cache.raw_line_count() < 2 {
        return;
    }

    static YEAR_ONLY_COPY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?ix)^copyright\s*\(c\)\s*(?P<years>[0-9\s,\-–/]+)\s+.+$").unwrap()
    });
    static AUTHOR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?ix)^author\s*:\s*(?P<name>[^<]+?)\s*(?:<\s*(?P<email>[^>\s]+@[^>\s]+)\s*>)?\s*$",
        )
        .unwrap()
    });

    authors.retain(|author| {
        if author.start_line != author.end_line {
            return true;
        }
        let Some(previous_line_number) = author.start_line.prev() else {
            return true;
        };

        let Some(raw_line) = prepared_cache.line(author.start_line).map(|line| line.raw) else {
            return true;
        };
        let normalized_line = raw_line.trim().trim_start_matches('*').trim_start();
        if !AUTHOR_LINE_RE.is_match(normalized_line) {
            return true;
        }

        copyrights.iter().all(|copyright| {
            if copyright.start_line != previous_line_number
                || copyright.end_line != author.start_line
            {
                return true;
            }
            !YEAR_ONLY_COPY_RE.is_match(copyright.copyright.as_str())
        })
    });
}

pub(in super::super) fn drop_shadowed_prefix_authors(authors: &mut Vec<AuthorDetection>) {
    if authors.len() < 2 {
        return;
    }
    let originals = authors.clone();

    authors.retain(|author| {
        let a = author.author.trim();
        if a.is_empty() {
            return true;
        }

        for other in &originals {
            let b = other.author.trim();
            if b.len() <= a.len() {
                continue;
            }
            if let Some(stripped) = b.strip_prefix(a) {
                let tail = stripped.trim_start();
                let boundary = b
                    .as_bytes()
                    .get(a.len())
                    .is_some_and(|ch| ch.is_ascii_whitespace() || matches!(ch, b',' | b'/' | b'('));

                let a_has_email = a.contains('@') || a.contains('<');
                let b_has_email = b.contains('@') || b.contains('<');

                let short_word = a.split_whitespace().count() == 1;
                if short_word && boundary {
                    if a.chars().all(|c| c.is_ascii_lowercase()) {
                        continue;
                    }
                    return false;
                }
                if !a_has_email && b_has_email && boundary {
                    return false;
                }
                if boundary {
                    let tail_lower = tail.to_ascii_lowercase();
                    if a_has_email && b_has_email {
                        continue;
                    }
                    if tail.starts_with(',')
                        || tail.starts_with('<')
                        || tail_lower.starts_with("or")
                        || tail_lower.starts_with("and")
                        || tail_lower.starts_with("author-email")
                    {
                        return false;
                    }
                }
            }
        }

        true
    });
}

pub(in super::super) fn drop_same_span_contact_sentence_overruns(
    authors: &mut Vec<AuthorDetection>,
) {
    if authors.len() < 2 {
        return;
    }
    let originals = authors.clone();
    authors.retain(|author| {
        let candidate = author.author.trim();
        !originals.iter().any(|other| {
            if other.start_line != author.start_line || other.end_line != author.end_line {
                return false;
            }
            let clean = other.author.trim();
            if clean.len() >= candidate.len() || !clean.contains('@') {
                return false;
            }
            let Some(tail) = candidate.strip_prefix(clean) else {
                return false;
            };
            let tail = tail.trim_start();
            matches!(tail.chars().next(), Some('.' | ';'))
                && tail
                    .trim_start_matches(['.', ';'])
                    .trim_start()
                    .chars()
                    .next()
                    .is_some_and(char::is_uppercase)
        })
    });
}

pub(in super::super) fn drop_shadowed_author_prefixes(authors: &mut Vec<AuthorDetection>) {
    if authors.len() < 2 {
        return;
    }
    let originals = authors.clone();
    authors.retain(|author| {
        let candidate = author.author.trim();
        !originals.iter().any(|other| {
            if other.start_line != author.start_line
                || other.end_line.get() < author.end_line.get()
                || other.author.len() <= candidate.len()
            {
                return false;
            }
            let Some(tail) = other.author.trim().strip_prefix(candidate) else {
                return false;
            };
            let tail = tail.trim_start();
            let normalized_tail = tail
                .trim_start_matches([',', ';'])
                .trim_start()
                .to_ascii_lowercase();
            let ends_with_initial = candidate
                .split_whitespace()
                .next_back()
                .map(|word| word.trim_matches(|ch: char| !ch.is_alphabetic()))
                .is_some_and(|word| {
                    let mut chars = word.chars();
                    chars.next().is_some_and(char::is_uppercase) && chars.next().is_none()
                });
            (other.end_line == author.end_line
                && (tail.starts_with(',')
                    || tail.starts_with(';')
                    || normalized_tail.starts_with("and ")))
                || (ends_with_initial && other.end_line >= author.end_line)
                || normalized_tail.starts_with("with contributions from ")
                || normalized_tail.starts_with("and contributions from ")
        })
    });
}

pub(in super::super) fn drop_shadowed_compound_email_authors(authors: &mut Vec<AuthorDetection>) {
    if authors.is_empty() {
        return;
    }

    static EMAIL_AUTHOR_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"[A-Z][^<\n]{0,120}?<[^>\s]+@[^>\s]+>"#).unwrap());
    static TRAILING_CURRENT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"^(?P<author>[A-Z][^<\n]{0,120}?<[^>\s]+@[^>\s]+>)\s+Current(?:\s+.*)?$"#)
            .unwrap()
    });
    static TRAILING_MODULE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"^(?P<author>[A-Z][^<\n]{0,120}?<[^>\s]+@[^>\s]+>)\s+MODULE_[A-Z_].*$"#)
            .unwrap()
    });

    let existing: HashSet<String> = authors
        .iter()
        .map(|a| a.author.trim().to_string())
        .collect();

    authors.retain(|author| {
        let raw = author.author.trim();

        if let Some(cap) = TRAILING_CURRENT_RE.captures(raw) {
            let clean = cap
                .name("author")
                .map(|m| m.as_str().trim().to_string())
                .unwrap_or_default();
            return clean.is_empty() || !existing.contains(&clean);
        }

        if let Some(cap) = TRAILING_MODULE_RE.captures(raw) {
            let clean = cap
                .name("author")
                .map(|m| m.as_str().trim().to_string())
                .unwrap_or_default();
            return clean.is_empty() || !existing.contains(&clean);
        }

        let matches: Vec<String> = EMAIL_AUTHOR_RE
            .find_iter(raw)
            .map(|m| m.as_str().trim().to_string())
            .collect();
        !(matches.len() >= 2 && matches.iter().all(|candidate| existing.contains(candidate)))
    });
}

pub(in super::super) fn drop_ref_markup_authors(authors: &mut Vec<AuthorDetection>) {
    authors.retain(|author| !author.author.contains("@ref"));
}

pub(in super::super) fn normalize_json_blob_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    let mut normalized: Vec<AuthorDetection> = Vec::with_capacity(authors.len());
    let mut seen: HashSet<(LineNumber, LineNumber, String)> = HashSet::new();

    for author in authors.iter() {
        let Some(window) =
            json_author_window(raw_lines, author.start_line.get(), author.end_line.get())
        else {
            let key = (author.start_line, author.end_line, author.author.clone());
            if seen.insert(key) {
                normalized.push(author.clone());
            }
            continue;
        };

        if json_window_contains_code_like_author_usage(&window) {
            continue;
        }

        let replacement = if let Some(name) = extract_author_name_from_json_window(&window) {
            refine_json_author_candidate(&name, &window)
        } else if json_window_contains_developed_by(&window, &author.author) {
            refine_author(&author.author)
        } else {
            None
        };

        let Some(author_name) = replacement else {
            continue;
        };

        let key = (author.start_line, author.end_line, author_name.clone());
        if seen.insert(key) {
            normalized.push(AuthorDetection {
                author: author_name,
                start_line: author.start_line,
                end_line: author.end_line,
            });
        }
    }

    *authors = normalized;
}

pub(in super::super) fn drop_json_code_example_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    if raw_lines.is_empty() || authors.is_empty() {
        return;
    }

    authors.retain(|author| {
        if let Some(window) =
            surrounding_author_window(raw_lines, author.start_line.get(), author.end_line.get())
            && window_contains_code_style_author_usage(&window)
        {
            return false;
        }

        let Some(window) =
            json_author_window(raw_lines, author.start_line.get(), author.end_line.get())
        else {
            return true;
        };

        if json_window_contains_code_like_author_usage(&window) {
            return false;
        }

        if json_window_has_metadata_context(&window)
            || json_window_is_simple_author_only_fragment(&window)
        {
            return true;
        }

        let Some(name) = extract_author_name_from_json_window(&window) else {
            return true;
        };
        looks_like_name_with_parenthesized_url(name.trim())
    });
}

pub(in super::super) fn drop_markup_element_value_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    if raw_lines.is_empty() || authors.is_empty() {
        return;
    }

    authors.retain(|author| {
        let Some(window) =
            surrounding_author_window(raw_lines, author.start_line.get(), author.end_line.get())
        else {
            return true;
        };
        !window_contains_markup_element_author_value(&window, &author.author)
    });
}

/// Drop authors detected on an XML/DTD markup declaration line, such as the
/// `<!ELEMENT module (args?, description?, author*, copyright?,` and
/// `<!ATTLIST author` content models embedded in Erlang edoc comments. There the
/// `author` token names an element, not a person, and refinement has already
/// dropped the declaration marker the value would otherwise be filtered on.
pub(in super::super) fn drop_markup_declaration_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    if raw_lines.is_empty() || authors.is_empty() {
        return;
    }

    authors.retain(|author| {
        !(author.start_line.get()..=author.end_line.get()).any(|line_number| {
            raw_lines
                .get(line_number.saturating_sub(1))
                .is_some_and(|line| contains_xml_markup_declaration_token(line))
        })
    });
}

/// Drop an author harvested by an author-label word that closes a prose
/// sentence: `... have been regular contributors.  Brian Rosen did tremendous
/// service ...` and the RFC running footer `Groves, et al.    Standards Track
/// [Page 169]`. The capitalized words after the period open a new sentence or a
/// new footer column, so the label does not introduce them.
pub(in super::super) fn drop_authors_after_sentence_final_label(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    // The label is required to be lowercase and to follow a lowercase prose
    // word, so a heading (`Authors.  Jane Doe`) still introduces its author.
    static SENTENCE_FINAL_LABEL_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"\p{Ll}[\p{Ll}']*\s+(?:al|authors?|contributors?|maintainers?)\.\s+$").unwrap()
    });

    if raw_lines.is_empty() || authors.is_empty() {
        return;
    }

    authors.retain(|author| {
        let Some(name) = author.author.split_whitespace().next() else {
            return true;
        };
        if !name.starts_with(char::is_uppercase) {
            return true;
        }
        let line_number = author.start_line.get();
        let Some(line) = raw_lines.get(line_number.saturating_sub(1)) else {
            return true;
        };
        // The label can sit on the previous line when prose wraps, so both lines
        // are searched for the sentence end that precedes the name.
        let previous = line_number
            .checked_sub(2)
            .and_then(|index| raw_lines.get(index))
            .copied()
            .unwrap_or_default();
        !line.match_indices(name).any(|(at, _)| {
            line[..at]
                .chars()
                .next_back()
                .is_none_or(|ch| !ch.is_alphanumeric())
                && SENTENCE_FINAL_LABEL_RE.is_match(&format!("{previous} {}", &line[..at]))
        })
    });
}

/// Drop an object phrase misread as a name after a subject-role construction,
/// such as `Kent was the author or maintainer of 178 CPAN distributions`.
/// Here `author` is a predicate describing the named subject, not a label that
/// introduces the words following `of`.
pub(in super::super) fn drop_subject_role_object_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    static SUBJECT_ROLE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?ix)
            \b\p{Lu}[\p{L}\p{M}'’.-]*
            (?:\s+\p{Lu}[\p{L}\p{M}'’.-]*){0,5}
            \s+(?:is|was)\s+(?:the\s+)?
            (?:author|maintainer)
            (?:\s+or\s+(?:author|maintainer))?
            \s+of\b
            ",
        )
        .expect("valid subject-role author regex")
    });

    authors.retain(|author| {
        let start = author.start_line.get().saturating_sub(1);
        let end = author.end_line.get().min(raw_lines.len());
        start >= end || !SUBJECT_ROLE_RE.is_match(&raw_lines[start..end].join(" "))
    });
}

/// Drop a weak compact author phrase when it was harvested without a bounded
/// label or attribution. Lowercase names remain valid with explicit evidence.
pub(in super::super) fn drop_weak_prose_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    authors.retain(|author| {
        let candidate = author.author.trim();
        let normalized = candidate
            .trim_matches(|ch: char| !ch.is_alphabetic() && !ch.is_whitespace())
            .trim();
        let words: Vec<&str> = normalized.split_whitespace().collect();
        let is_weak_compact_phrase = !words.is_empty()
            && words.len() <= 2
            && normalized
                .chars()
                .all(|ch| ch.is_alphabetic() || ch.is_whitespace())
            && normalized
                .chars()
                .find(|ch| ch.is_alphabetic())
                .is_some_and(|ch| ch.is_lowercase());
        if !is_weak_compact_phrase {
            return true;
        }

        let Some(raw_line) = raw_lines.get(author.start_line.get().saturating_sub(1)) else {
            return true;
        };
        let lower = raw_line.to_lowercase();
        let candidate_lower = normalized.to_lowercase();
        let has_explicit_label = ["author:", "author :", "authors:", "authors :", "@author"]
            .iter()
            .any(|label| lower.contains(&format!("{label} {candidate_lower}")));
        let has_structured_author_field = lower.find(&candidate_lower).is_some_and(|index| {
            let prefix = &lower[..index];
            prefix
                .rfind("author")
                .is_some_and(|label_index| prefix[label_index + "author".len()..].contains(':'))
        });
        let attribution = format!("by {candidate_lower}");
        let has_bounded_by_attribution = lower.match_indices(&attribution).any(|(index, _)| {
            let tail = lower[index + attribution.len()..].trim_start();
            tail.is_empty()
                || tail
                    .chars()
                    .next()
                    .is_some_and(|ch| matches!(ch, '.' | ',' | ';' | ':' | ')' | ']' | '>'))
        });

        has_explicit_label || has_structured_author_field || has_bounded_by_attribution
    });
}

/// Prefer a complete `by NAME` credit that ends on its source line over a
/// parser span that absorbed the following comment sentence.
pub(in super::super) fn repair_complete_by_line_author_boundaries(
    raw_lines: &[&str],
    authors: &mut [AuthorDetection],
) {
    static TRAILING_BY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)\bby\s+(?P<who>[^,;:]+?)\s*$").expect("valid trailing by-author regex")
    });

    for author in authors {
        if author.end_line <= author.start_line {
            continue;
        }
        let Some(raw_line) = raw_lines.get(author.start_line.get().saturating_sub(1)) else {
            continue;
        };
        let following = raw_lines
            .get(author.start_line.get())
            .map(|line| prepare_text_line(line))
            .unwrap_or_default();
        let following_lower = following.to_ascii_lowercase();
        let following_has_obfuscated_contact =
            following_lower.contains(" at ") && following_lower.contains(" dot ");
        if following_lower.starts_with("(http://")
            || following_lower.starts_with("(https://")
            || following.contains('@')
            || following_has_obfuscated_contact
            || following_lower.starts_with("by ")
            || following_lower.contains(" by ")
        {
            continue;
        }
        let prepared = prepare_text_line(raw_line);
        let Some(captures) = TRAILING_BY_RE.captures(&prepared) else {
            continue;
        };
        let who = captures
            .name("who")
            .map(|matched| matched.as_str())
            .unwrap_or("")
            .trim();
        let who_lower = who.to_ascii_lowercase();
        let trailing_conjunction_words = who_lower
            .rsplit_once(" and ")
            .or_else(|| who_lower.rsplit_once(" or "))
            .map(|(_, tail)| tail.split_whitespace().count());
        if who_lower.ends_with(" and")
            || who_lower.ends_with(" or")
            || trailing_conjunction_words == Some(1)
        {
            continue;
        }
        let uppercase_words = who
            .split_whitespace()
            .filter(|word| {
                word.chars()
                    .find(|ch| ch.is_alphabetic())
                    .is_some_and(|ch| ch.is_uppercase())
            })
            .count();
        if uppercase_words < 2 {
            continue;
        }
        let Some(refined) = refine_author(who) else {
            continue;
        };
        if author.author != refined && author.author.starts_with(&refined) {
            author.author = refined;
            author.end_line = author.start_line;
        }
    }
}

/// Repair an author name followed by the first half of a hyphenated prose word
/// split across two source lines, such as `Name, poss-` / `ibly modified`.
pub(in super::super) fn repair_hyphenated_prose_tail_authors(
    raw_lines: &[&str],
    authors: &mut [AuthorDetection],
) {
    for author in authors {
        if author.end_line <= author.start_line {
            continue;
        }
        let Some((name, fragment)) = author.author.rsplit_once(',') else {
            continue;
        };
        let fragment = fragment.trim();
        if fragment.len() < 2 || !fragment.chars().all(|ch| ch.is_lowercase()) {
            continue;
        }
        let Some(first_raw) = raw_lines.get(author.start_line.get().saturating_sub(1)) else {
            continue;
        };
        let Some(next_raw) = raw_lines.get(author.start_line.get()) else {
            continue;
        };
        let first = prepare_text_line(first_raw);
        let next = prepare_text_line(next_raw);
        if !first.contains(&format!("{fragment}-"))
            || !next
                .chars()
                .find(|ch| ch.is_alphabetic())
                .is_some_and(|ch| ch.is_lowercase())
        {
            continue;
        }
        let Some(refined) = refine_author(name.trim()) else {
            continue;
        };
        author.author = refined;
        author.end_line = author.start_line;
    }
}

/// Drop a candidate introduced by `Authors` when that word is embedded in a
/// larger title-cased product or service name instead of acting as a label.
pub(in super::super) fn drop_embedded_authors_title_phrases(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    authors.retain(|author| {
        let candidate_lower = author.author.to_lowercase();
        !(author.start_line.get()..=author.end_line.get()).any(|line_number| {
            let Some(raw_line) = raw_lines.get(line_number.saturating_sub(1)) else {
                return false;
            };
            let prepared = prepare_text_line(raw_line);
            let words: Vec<&str> = prepared.split_whitespace().collect();
            words.windows(2).enumerate().any(|(index, pair)| {
                let label = pair[0];
                if label.contains(':')
                    || !label
                        .trim_matches(|ch: char| !ch.is_alphabetic())
                        .eq_ignore_ascii_case("authors")
                    || index == 0
                {
                    return false;
                }
                let previous = words[index - 1];
                let previous_is_title_cased = previous
                    .chars()
                    .find(|ch| ch.is_alphabetic())
                    .is_some_and(|ch| ch.is_uppercase());
                let tail_lower = words[index + 1..].join(" ").to_lowercase();
                previous_is_title_cased && tail_lower.contains(&candidate_lower)
            })
        })
    });
}

/// Drop a multi-line candidate when a complete candidate already ends on the
/// first line and the next line opens a distinct `... by ...` attribution.
pub(in super::super) fn drop_shadowed_multiline_author_overruns(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    if authors.len() < 2 {
        return;
    }
    let originals = authors.clone();

    authors.retain(|author| {
        !originals.iter().any(|complete| {
            if complete.start_line != author.start_line
                || complete.end_line >= author.end_line
                || complete.author.len() >= author.author.len()
                || !author.author.starts_with(&complete.author)
            {
                return false;
            }
            let boundary = author
                .author
                .as_bytes()
                .get(complete.author.len())
                .is_some_and(|ch| ch.is_ascii_whitespace() || matches!(ch, b',' | b'.'));
            if !boundary {
                return false;
            }
            let tail = author.author[complete.author.len()..]
                .trim_start_matches(|ch: char| ch.is_whitespace() || matches!(ch, ',' | '.'));
            let tail_lower = tail.to_ascii_lowercase();
            if tail_lower.starts_with("and ") || tail_lower.starts_with("or ") {
                return false;
            }

            raw_lines
                .get(complete.end_line.get())
                .map(|line| prepare_text_line(line).to_ascii_lowercase())
                .is_some_and(|line| line.contains(" by "))
        })
    });
}

/// Stop a contact-backed attribution before the next source line opens a
/// distinct attribution. This handles wrapped parsers that absorb the first
/// word of the next sentence into the preceding author.
pub(in super::super) fn repair_contact_author_before_new_attribution(
    raw_lines: &[&str],
    authors: &mut [AuthorDetection],
) {
    static TRAILING_BY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)\bby\s+(?P<who>.+?)\s*$").expect("valid contact by-author regex")
    });

    for author in authors {
        if author.end_line <= author.start_line {
            continue;
        }
        let start_index = author.start_line.get().saturating_sub(1);
        let end_index = author.end_line.get().min(raw_lines.len());
        let mut prefix = Vec::new();

        for (index, raw_line) in raw_lines
            .iter()
            .enumerate()
            .take(end_index)
            .skip(start_index)
        {
            let prepared = prepare_text_line(raw_line);
            if index > start_index {
                let lower = prepared.to_ascii_lowercase();
                let opens_new_attribution = lower.contains(" by ")
                    && !lower.starts_with("and ")
                    && !lower.starts_with("or ");
                let joined = prefix.join(" ");
                let joined_lower = joined.to_ascii_lowercase();
                let has_contact = joined.contains('@')
                    || joined.contains('<')
                    || (joined_lower.contains(" at ") && joined_lower.contains(" dot "));
                if opens_new_attribution && has_contact {
                    let Some(captures) = TRAILING_BY_RE.captures(&joined) else {
                        break;
                    };
                    let who = captures
                        .name("who")
                        .map(|matched| matched.as_str())
                        .unwrap_or("")
                        .trim();
                    let Some(refined) = refine_author(who) else {
                        break;
                    };
                    if author.author.starts_with(&refined) {
                        author.author = refined;
                        author.end_line = LineNumber::new(index).expect("valid source line");
                    }
                    break;
                }
            }
            prefix.push(prepared);
        }
    }
}

/// Drop product provenance mistaken for human authorship in passive creation
/// sentences, such as plural artifacts created by a versioned application.
pub(in super::super) fn drop_passive_product_creation_authors(
    raw_lines: &[&str],
    authors: &mut Vec<AuthorDetection>,
) {
    authors.retain(|author| {
        if author.author.contains('@') {
            return true;
        }
        let author_lower = author.author.to_ascii_lowercase();
        if author_lower.contains(" at ") && author_lower.contains(" dot ") {
            return true;
        }

        let window = (author.start_line.get()..=author.end_line.get())
            .filter_map(|line_number| raw_lines.get(line_number.saturating_sub(1)))
            .map(|line| prepare_text_line(line))
            .collect::<Vec<_>>()
            .join(" ");
        let window_lower = window.to_ascii_lowercase();
        let Some(created_index) = window_lower.find("created by") else {
            return true;
        };
        let subject = window_lower[..created_index]
            .split_whitespace()
            .rev()
            .map(|word| word.trim_matches(|ch: char| !ch.is_alphanumeric()))
            .find(|word| {
                !word.is_empty()
                    && !matches!(
                        *word,
                        "be" | "been" | "being" | "is" | "are" | "was" | "were"
                    )
            })
            .unwrap_or("");
        let plural_artifact = matches!(subject, "those" | "these" | "them")
            || (subject.len() > 2 && subject.ends_with('s') && subject != "this");
        if !plural_artifact {
            return true;
        }

        let tokens: Vec<&str> = author
            .author
            .split_whitespace()
            .map(|word| {
                word.trim_matches(|ch: char| !ch.is_alphanumeric() && ch != '\'' && ch != '’')
            })
            .filter(|word| !word.is_empty())
            .collect();
        let has_version_token = tokens.iter().any(|word| {
            let lower = word.to_ascii_lowercase();
            (word.contains('.') && word.chars().any(|ch| ch.is_ascii_digit()))
                || lower
                    .strip_prefix('v')
                    .is_some_and(|rest| rest.chars().next().is_some_and(|ch| ch.is_ascii_digit()))
        });
        let has_possessive = tokens
            .iter()
            .any(|word| word.ends_with("'s") || word.ends_with("’s"));
        let has_acronym = tokens.iter().any(|word| {
            let letters: Vec<char> = word.chars().filter(|ch| ch.is_alphabetic()).collect();
            letters.len() >= 3 && letters.iter().all(|ch| ch.is_uppercase())
        });

        !(has_version_token || (has_possessive && has_acronym))
    });
}

fn window_contains_markup_element_author_value(window: &str, author: &str) -> bool {
    let normalized = normalize_whitespace(window);
    if !(normalized.contains('<') && normalized.contains('>')) {
        return false;
    }

    let lower = normalized.to_ascii_lowercase();
    if lower.contains("copyright") || lower.contains("written by") || lower.contains("created by") {
        return false;
    }

    let has_author_element = (lower.contains("<author>")
        || lower.contains("</author>")
        || lower.contains("<author ")
        || lower.contains(":author>"))
        && !lower.contains("author=");
    if has_author_element {
        return true;
    }

    if has_author_element
        && (lower.contains("<first-name>")
            || lower.contains("<last-name>")
            || lower.contains("<first.name>")
            || lower.contains("<last.name>"))
    {
        return true;
    }

    if lower.contains("xml:lang") && author.trim().starts_with("XmlLang ") {
        return true;
    }

    let trimmed_author = author.trim();
    if trimmed_author.is_empty() {
        return false;
    }

    let escaped = regex::escape(trimmed_author);
    let exact_tag_re = Regex::new(&format!(
        r"(?is)<(?:name|title|id|email|uri|updated|first-name|last-name|first\.name|last\.name|firstname|surname)\b[^>]*>\s*{}\s*</",
        escaped
    ))
    .expect("valid exact markup data tag regex");
    if exact_tag_re.is_match(&normalized) {
        return true;
    }

    let looks_like_identifier = trimmed_author.contains('@')
        || trimmed_author.contains("http://")
        || trimmed_author.contains("https://")
        || trimmed_author.to_ascii_lowercase().starts_with("doi:")
        || trimmed_author.to_ascii_lowercase().starts_with("tag:")
        || trimmed_author.contains('T') && trimmed_author.ends_with('Z');

    looks_like_identifier
        && (lower.contains("<id>")
            || lower.contains("<email>")
            || lower.contains("<uri>")
            || lower.contains("<updated>"))
}

fn surrounding_author_window(
    raw_lines: &[&str],
    start_line: usize,
    end_line: usize,
) -> Option<String> {
    if start_line == 0
        || end_line == 0
        || start_line > raw_lines.len()
        || end_line > raw_lines.len()
    {
        return None;
    }
    let start = start_line.saturating_sub(2).max(1);
    let end = (end_line + 2).min(raw_lines.len());
    Some(raw_lines[start - 1..end].join(" "))
}

fn window_contains_code_style_author_usage(window: &str) -> bool {
    static CODE_OPERATOR_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"\$[A-Za-z_][A-Za-z0-9_]*"#).unwrap());
    static QUOTED_AUTHOR_ASSIGNMENT_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"\"author\"\s*:"#).unwrap());
    static BARE_OBJECT_AUTHOR_ASSIGNMENT_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"\{[^\r\n]*\bauthor\s*:\s*\"[^\"]+\""#).unwrap());

    CODE_OPERATOR_RE.is_match(window)
        && (QUOTED_AUTHOR_ASSIGNMENT_RE.is_match(window)
            || (window.contains('{')
                && window.contains('}')
                && BARE_OBJECT_AUTHOR_ASSIGNMENT_RE.is_match(window)))
}

fn is_json_like_line(line: &str) -> bool {
    static JSON_FIELD_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"^\s*\{?\s*"[^"]+"\s*:\s*(?:"[^"]*"|\{|\[|true|false|null|-?\d)"#).unwrap()
    });

    JSON_FIELD_RE.is_match(line) || line.trim() == "{" || line.trim() == "}" || line.trim() == "},"
}

fn json_author_window(raw_lines: &[&str], start_line: usize, end_line: usize) -> Option<String> {
    if start_line == 0
        || end_line == 0
        || start_line > raw_lines.len()
        || end_line > raw_lines.len()
    {
        return None;
    }
    let start = start_line.saturating_sub(2).max(1);
    let end = (end_line + 2).min(raw_lines.len());
    let lines = &raw_lines[start - 1..end];
    if !lines.iter().any(|line| is_json_like_line(line)) {
        return None;
    }
    Some(lines.join(" "))
}

pub(in super::super) fn json_window_contains_code_like_author_usage(window: &str) -> bool {
    static JSON_CODE_OPERATOR_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"\$[A-Za-z_][A-Za-z0-9_]*"#).unwrap());
    static JSON_AUTHOR_NUMERIC_VALUE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?i)(?:\"author\"|\bauthor)\s*:\s*(?:-?\d+|true|false|null)"#).unwrap()
    });

    JSON_CODE_OPERATOR_RE.is_match(window) || JSON_AUTHOR_NUMERIC_VALUE_RE.is_match(window)
}

fn json_window_has_metadata_context(window: &str) -> bool {
    static JSON_METADATA_KEY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?i)\"(?:name|supplier|publisher|version|license|licenses|bomFormat|components|purl|homepage|description|package|url)\"\s*:"#,
        )
        .unwrap()
    });

    JSON_METADATA_KEY_RE.is_match(window)
}

fn json_window_is_simple_author_only_fragment(window: &str) -> bool {
    static JSON_AUTHOR_ONLY_STRING_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?is)^\s*\{?\s*\"author\"\s*:\s*\"[^\"]+\"\s*,?\s*\}?\s*$"#).unwrap()
    });
    static JSON_AUTHOR_ONLY_OBJECT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?is)^\s*\{?\s*\"author\"\s*:\s*\{\s*\"name\"\s*:\s*\"[^\"]+\"(?:\s*,\s*\"(?:url|email)\"\s*:\s*\"[^\"]+\")*\s*\}\s*,?\s*\}?\s*$"#,
        )
        .unwrap()
    });

    JSON_AUTHOR_ONLY_STRING_RE.is_match(window) || JSON_AUTHOR_ONLY_OBJECT_RE.is_match(window)
}

fn looks_like_simple_machine_author_token(name: &str) -> bool {
    let trimmed = name.trim();
    trimmed.split_whitespace().count() == 1
        && trimmed.len() >= 6
        && trimmed
            .chars()
            .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-'))
}

pub(in super::super) fn looks_like_structured_json_author_fallback(value: &str) -> bool {
    let trimmed = value.trim();
    if looks_like_name_with_parenthesized_url(trimmed) {
        return true;
    }

    if trimmed.is_empty()
        || trimmed.contains('@')
        || trimmed.contains("http://")
        || trimmed.contains("https://")
        || json_window_contains_code_like_author_usage(trimmed)
    {
        return false;
    }

    let words: Vec<&str> = trimmed.split_whitespace().collect();
    if words.is_empty() {
        return false;
    }

    if words.len() == 1 {
        let token =
            words[0].trim_matches(|ch: char| !ch.is_alphanumeric() && ch != '-' && ch != '\'');
        if token.len() < 4 {
            return false;
        }
        let lower = token.to_ascii_lowercase();
        if matches!(
            lower.as_str(),
            "author" | "authors" | "guide" | "description" | "project"
        ) {
            return false;
        }
        return token
            .chars()
            .any(|ch| ch.is_uppercase() || ch.is_ascii_digit());
    }

    let lower = trimmed.to_ascii_lowercase();
    [
        " authors",
        " project",
        " team",
        " group",
        " foundation",
        " committee",
        " communities",
        " consortium",
        " developers",
    ]
    .iter()
    .any(|suffix| lower.ends_with(suffix))
}

pub(in super::super) fn refine_json_author_candidate(name: &str, window: &str) -> Option<String> {
    if json_window_contains_code_like_author_usage(window) {
        return None;
    }

    let prepared = prepare_text_line(name);
    let normalized = normalize_whitespace(&prepared);
    let trimmed = normalized
        .trim()
        .trim_end_matches(&[',', ';', '.'][..])
        .trim();
    let has_metadata_context = json_window_has_metadata_context(window);
    let is_simple_author_only_fragment = json_window_is_simple_author_only_fragment(window);

    if looks_like_simple_machine_author_token(trimmed) {
        return None;
    }

    if !has_metadata_context
        && !is_simple_author_only_fragment
        && !looks_like_name_with_parenthesized_url(trimmed)
    {
        return None;
    }
    if let Some(author) = refine_author(name) {
        return Some(author);
    }

    if !has_metadata_context
        && !is_simple_author_only_fragment
        && !looks_like_name_with_parenthesized_url(trimmed)
    {
        return None;
    }

    if looks_like_structured_json_author_fallback(trimmed) {
        Some(trimmed.to_string())
    } else {
        None
    }
}

pub(in super::super) fn extract_author_name_from_json_window(window: &str) -> Option<String> {
    static JSON_AUTHOR_OBJECT_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?is)"author"\s*:\s*\{[^{}]*?"name"\s*:\s*"(?P<name>[^"]+)""#).unwrap()
    });
    static JSON_AUTHOR_STRING_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"(?is)"author"\s*:\s*"(?P<name>[^"]+)""#).unwrap());

    JSON_AUTHOR_OBJECT_NAME_RE
        .captures(window)
        .or_else(|| JSON_AUTHOR_STRING_RE.captures(window))
        .and_then(|cap| cap.name("name"))
        .map(|m| m.as_str().trim().to_string())
        .filter(|name| !name.is_empty())
}

fn json_window_contains_developed_by(window: &str, author: &str) -> bool {
    let needle = format!("developed by {}", author.trim().to_ascii_lowercase());
    window.to_ascii_lowercase().contains(&needle)
}

pub(in super::super) fn drop_written_by_authors_preceded_by_copyright(
    prepared_cache: &PreparedLines<'_>,
    authors: &mut Vec<AuthorDetection>,
) {
    if authors.is_empty() {
        return;
    }

    static WRITTEN_BY_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?i)^\s*written\s+by\s+(?P<who>.+)$").unwrap());
    static COPYRIGHT_HINT_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?i)\bcopyright\b|\(c\)").unwrap());
    static WEAK_WRITTEN_BY_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?i)\b(?:and\s+others|et\s+al\.?|contributors?)\b").unwrap());

    if prepared_cache.len() < 2 {
        return;
    }

    let mut to_drop: HashSet<String> = HashSet::new();
    for (prev, line) in prepared_cache.adjacent_pairs() {
        let Some(cap) = WRITTEN_BY_RE.captures(line.prepared) else {
            continue;
        };
        let who = cap.name("who").map(|m| m.as_str()).unwrap_or("").trim();
        if who.is_empty() {
            continue;
        }
        if who.contains('@')
            || who.contains('<')
            || who.contains("http://")
            || who.contains("https://")
        {
            continue;
        }
        if !COPYRIGHT_HINT_RE.is_match(prev.prepared) {
            continue;
        }
        if !WEAK_WRITTEN_BY_RE.is_match(who) {
            continue;
        }
        if let Some(author) = refine_author(who) {
            to_drop.insert(author);
        }
    }

    if to_drop.is_empty() {
        return;
    }
    authors.retain(|a| !to_drop.contains(&a.author));
}