tga 10.0.0

Developer productivity analytics — git commit collection, classification, and reporting
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
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
//! Tests for [`super::resolver::IdentityResolver`] and helpers.
//!
//! Why: collected here so the production file stays under the 500-SLOC cap
//! while tests can use the 1500-SLOC test-file budget.
//! What: unit tests for alias resolution, fuzzy matching, canonical-domain
//! policy, and the `from_config` constructor.
//! Test: run with `cargo test -p tga`.

use super::*;
use crate::core::config::{TeamConfig, TeamMember};
use std::collections::HashMap;

fn make_team() -> TeamConfig {
    let mut aliases = HashMap::new();
    aliases.insert("bobby".into(), "Bob Smith".into());
    TeamConfig {
        members: vec![TeamMember {
            name: "Bob Smith".into(),
            email: "bob@example.com".into(),
            aliases: vec!["bsmith@example.com".into()],
        }],
        aliases,
        canonical_domain: None,
    }
}

#[test]
fn exact_email_alias_match() {
    let r = IdentityResolver::new(Some(&make_team()));
    let (n, e) = r.resolve("Whoever", "bsmith@example.com");
    assert_eq!(n, "Bob Smith");
    assert_eq!(e, "bob@example.com");
}

#[test]
fn exact_name_alias_match() {
    let r = IdentityResolver::new(Some(&make_team()));
    let (n, e) = r.resolve("bobby", "x@y.com");
    assert_eq!(n, "Bob Smith");
    assert_eq!(e, "bob@example.com");
}

#[test]
fn fuzzy_match_canonical_name() {
    let r = IdentityResolver::new(Some(&make_team()));
    // Slightly different spelling should still match (jaro_winkler high)
    let (n, _e) = r.resolve("Bob Smyth", "unknown@elsewhere.com");
    assert_eq!(n, "Bob Smith");
}

#[test]
fn no_match_returns_input() {
    let r = IdentityResolver::new(Some(&make_team()));
    let (n, e) = r.resolve("Zelda Q", "zelda@nowhere.test");
    assert_eq!(n, "Zelda Q");
    assert_eq!(e, "zelda@nowhere.test");
}

#[test]
fn empty_team_passthrough() {
    let r = IdentityResolver::new(None);
    let (n, e) = r.resolve("Anyone", "anyone@x.com");
    assert_eq!(n, "Anyone");
    assert_eq!(e, "anyone@x.com");
}

/// All aliases — emails AND non-email login handles — must be indexed
/// in the lookup map so every variant resolves to the canonical name.
#[test]
fn all_aliases_registered() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert(
        "Alice Smith".to_string(),
        vec![
            "alice@company.com".into(),
            "alice.smith@personal.com".into(),
            "asmith".into(), // non-email login handle
        ],
    );
    let r = IdentityResolver::from_alias_map(&map);

    // Primary email → canonical name + primary email.
    let (n, e) = r.resolve("whoever", "alice@company.com");
    assert_eq!(n, "Alice Smith");
    assert_eq!(e, "alice@company.com");

    // Secondary email → canonical name + canonical (first) email.
    let (n, e) = r.resolve("whoever", "alice.smith@personal.com");
    assert_eq!(n, "Alice Smith");
    assert_eq!(e, "alice@company.com");

    // Non-email handle as name → canonical name.
    let (n, e) = r.resolve("asmith", "noise@nowhere.test");
    assert_eq!(n, "Alice Smith");
    assert_eq!(e, "alice@company.com");
}

/// Email local-part fuzzy: a short raw name like `"Bob M"` plus an
/// email `<bob.matsuoka@co.com>` should resolve to `"Bob Matsuoka"`
/// via the normalized fuzzy pass even when raw Jaro-Winkler on the
/// short name falls below the strict 0.85 threshold.
#[test]
fn email_local_part_fuzzy_match() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert(
        "Bob Matsuoka".to_string(),
        vec!["bob.matsuoka@researchco.example".into()],
    );
    let r = IdentityResolver::from_alias_map(&map);

    // Different email + truncated name — only the email local-part
    // normalizes to "bob matsuoka" which matches the canonical name.
    let (n, e) = r.resolve("Bob M", "bob.matsuoka@otherdomain.com");
    assert_eq!(n, "Bob Matsuoka");
    assert_eq!(e, "bob.matsuoka@researchco.example");
}

/// Email case must not affect lookup — `ALICE@COMPANY.COM` resolves
/// the same as `alice@company.com`.
#[test]
fn case_insensitive_email_lookup() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert("Alice Smith".to_string(), vec!["alice@company.com".into()]);
    let r = IdentityResolver::from_alias_map(&map);

    let (n, e) = r.resolve("Whoever", "ALICE@COMPANY.COM");
    assert_eq!(n, "Alice Smith");
    assert_eq!(e, "alice@company.com");

    let (n2, e2) = r.resolve("WhoEver", "Alice@Company.Com");
    assert_eq!(n2, "Alice Smith");
    assert_eq!(e2, "alice@company.com");
}

/// Short truncated display names should still fuzzy-match the
/// canonical form when the email local-part backs them up.
#[test]
fn short_name_fuzzy() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert(
        "Bob Matsuoka".to_string(),
        vec!["bob.matsuoka@co.com".into()],
    );
    let r = IdentityResolver::from_alias_map(&map);

    // The unknown email forces fuzzy. "bob m" alone is too short for
    // raw Jaro-Winkler to clear 0.85 against "bob matsuoka", but the
    // local-part `bobm` normalizes and the normalized threshold (0.82)
    // accepts the match.
    let (n, _e) = r.resolve("Bob M", "bobm@unknown.test");
    assert_eq!(n, "Bob Matsuoka");
}

/// A completely unknown identity returns the raw input unchanged.
#[test]
fn unknown_author_passthrough() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert("Alice Smith".to_string(), vec!["alice@company.com".into()]);
    let r = IdentityResolver::from_alias_map(&map);

    let (n, e) = r.resolve("Zelda Q", "zelda@nowhere.test");
    assert_eq!(n, "Zelda Q");
    assert_eq!(e, "zelda@nowhere.test");
}

/// Multiple distinct emails for the same person all collapse onto a
/// single canonical name and email pair.
#[test]
fn multiple_emails_same_person() {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    map.insert(
        "Pedro Silva".to_string(),
        vec![
            "pedro.silva@researchco.example".into(),
            "100000001+pedrosilvaextern@users.noreply.github.com".into(),
            "pedro@personal.dev".into(),
        ],
    );
    let r = IdentityResolver::from_alias_map(&map);

    let (n1, e1) = r.resolve("Pedro Silva", "pedro.silva@researchco.example");
    let (n2, e2) = r.resolve(
        "pedrosilvaextern",
        "100000001+pedrosilvaextern@users.noreply.github.com",
    );
    let (n3, e3) = r.resolve("P. Silva", "pedro@personal.dev");

    assert_eq!(n1, "Pedro Silva");
    assert_eq!(n2, "Pedro Silva");
    assert_eq!(n3, "Pedro Silva");
    // Canonical email is the first email-looking alias for each.
    assert_eq!(e1, "pedro.silva@researchco.example");
    assert_eq!(e2, "pedro.silva@researchco.example");
    assert_eq!(e3, "pedro.silva@researchco.example");
}

/// Verify resolution end-to-end through `Config::load` + external
/// `aliases_file`, mirroring the shape of the deployed
/// `configs/duetto-contractors.yaml` setup. This guards against
/// regressions in YAML schema, path resolution, or resolver wiring.
///
/// The fixture is materialized into a `tempfile::TempDir` so the test is
/// hermetic: it does not depend on absolute paths outside the repo
/// (which would fail in CI). Previously this built its own `pid + nanos`
/// directory name, the same scheme that raced in the #4251 helper below —
/// `process::id()` is constant within a test binary and the `SystemTime`
/// remainder is coarser than a nanosecond, so the name is not actually
/// unique. `TempDir` also cleans up on panic, which the manual path did not.
#[test]
fn duetto_contractors_config_resolves() {
    let tmpdir = tempfile::TempDir::new().expect("create tmp");
    let tmp = tmpdir.path();

    // Aliases file shaped like a contractor alias map,
    // including the cases the assertions below exercise (case-folding,
    // fuzzy match on email-local-part, non-email handle alias).
    let aliases_yaml = r#"
developers:
  - name: "Pedro Silva"
    primary_email: "pedro.silva@researchco.example"
    aliases:
      - "100000001+pedrosilvaextern@users.noreply.github.com"
  - name: "Rohan Mehta"
    primary_email: "rohan.mehta@researchco.example"
    aliases:
      - "Rohan.Mehta-c@researchco.example"
      - "rohan-extern"
  - name: "Kiran Anand Kumar Nayak"
    primary_email: "kiran.nayak@researchco.example"
    aliases:
      - "kirannayak-extern"
      - "100000002+kirannayak-extern@users.noreply.github.com"
"#;
    let aliases_path = tmp.join("aliases.yaml");
    std::fs::write(&aliases_path, aliases_yaml).expect("write aliases");

    let config_yaml = format!(
        "version: \"1.0\"\naliases_file: \"{}\"\n",
        aliases_path.to_string_lossy()
    );
    let config_path = tmp.join("duetto-contractors.yaml");
    std::fs::write(&config_path, config_yaml).expect("write config");

    let cfg =
        crate::core::config::Config::load(&config_path).expect("load duetto-contractors yaml");
    let r = IdentityResolver::from_config(&cfg);

    // Known mapping from the YAML (canonical email match).
    let (n, _) = r.resolve("whoever", "pedro.silva@researchco.example");
    assert_eq!(n, "Pedro Silva");

    // Case-insensitive variant of an explicitly listed alias.
    let (n, _) = r.resolve("whoever", "Rohan.Mehta-c@researchco.example");
    assert_eq!(n, "Rohan Mehta");

    // Non-email login handle alias.
    let (n, _) = r.resolve("kirannayak-extern", "noise@nowhere.test");
    assert_eq!(n, "Kiran Anand Kumar Nayak");
}

#[test]
fn normalize_for_fuzzy_basic() {
    assert_eq!(normalize_for_fuzzy("Bob.Matsuoka"), "bob matsuoka");
    assert_eq!(normalize_for_fuzzy("alice_smith-c"), "alice smith c");
    assert_eq!(normalize_for_fuzzy("  Foo   Bar  "), "foo bar");
}

#[test]
fn email_local_part_basic() {
    assert_eq!(email_local_part("Bob@Example.COM"), "bob");
    assert_eq!(email_local_part("no-at-symbol"), "no-at-symbol");
}

#[test]
fn email_domain_matches_basic() {
    // Why: regression guard for the helper used by both the canonical-
    // email policy (#349) and the alias suggester (#347).
    assert!(email_domain_matches(
        "a@RESEARCHCO.EXAMPLE",
        "researchco.example"
    ));
    assert!(email_domain_matches(
        "a@researchco.example",
        "@researchco.example"
    ));
    assert!(!email_domain_matches("a@other.com", "researchco.example"));
    assert!(!email_domain_matches("invalid-email", "researchco.example"));
    assert!(!email_domain_matches("a@researchco.example", ""));
}

#[test]
fn canonical_domain_prefers_org_email_for_team_member() {
    // Why: when team.members lists an org email and the incoming commit
    // uses a personal address, resolve() already returns the org email.
    // This guards the existing happy path.
    let team = TeamConfig {
        members: vec![TeamMember {
            name: "Alice Org".into(),
            email: "alice@researchco.example".into(),
            aliases: vec!["alice@personal.com".into()],
        }],
        aliases: HashMap::new(),
        canonical_domain: Some("researchco.example".into()),
    };
    let r = IdentityResolver::new(Some(&team));
    let (_, e) = r.resolve("Alice Org", "alice@personal.com");
    assert_eq!(e, "alice@researchco.example");
    assert_eq!(r.canonical_domain(), Some("researchco.example"));
}

/// (#6142 review) `tga aliases merge` deletes the source row and keeps the
/// merge only in the destination's `aliases` array. The next collect must route
/// the merged-away address to that destination rather than re-creating the row
/// the operator deleted.
#[test]
fn a_merged_away_email_routes_to_its_canonical_row() {
    use crate::core::db::Database;
    use rusqlite::params;

    let db = Database::open_in_memory().expect("open db");
    db.connection()
        .execute(
            "INSERT INTO authors (canonical_name, canonical_email, aliases) \
             VALUES ('Alice', 'alice@corp.com', ?1)",
            params![r#"["alice@personal.com"]"#],
        )
        .expect("seed destination");
    let dst: i64 = db
        .connection()
        .query_row(
            "SELECT id FROM authors WHERE canonical_email = 'alice@corp.com'",
            [],
            |r| r.get(0),
        )
        .expect("dst id");

    let r = IdentityResolver::new(None);
    let id = r
        .upsert_author(&db, "Alice", "alice@personal.com")
        .expect("upsert");
    assert_eq!(id, dst, "the alias must route to its canonical identity");

    // Case-insensitively, too — git config addresses vary in case.
    let upper = r
        .upsert_author(&db, "Alice", "Alice@Personal.com")
        .expect("upsert");
    assert_eq!(upper, dst);

    let rows: i64 = db
        .connection()
        .query_row("SELECT COUNT(*) FROM authors", [], |r| r.get(0))
        .expect("count");
    assert_eq!(rows, 1, "no row may be re-created for a merged-away email");

    // A LIKE match that is not an exact array element must not hijack: the
    // longer address contains the alias as a substring.
    let other = r
        .upsert_author(&db, "Bob", "not-alice@personal.com.example")
        .expect("upsert");
    assert_ne!(other, dst, "a substring match must not claim the identity");
}

/// (#6142 review) One normalisation for the configured canonical domain, used
/// by the resolver, `tga aliases suggest`, and the audit's authorship pass.
#[test]
fn configured_canonical_domain_normalises_the_value() {
    use crate::collect::identity::resolver::configured_canonical_domain;
    use crate::core::config::Config;

    let mut config = Config::default();
    assert_eq!(configured_canonical_domain(&config), None, "no team block");

    config.team = Some(TeamConfig {
        members: vec![],
        aliases: HashMap::new(),
        canonical_domain: Some("  @Corp.COM ".into()),
    });
    assert_eq!(
        configured_canonical_domain(&config),
        Some("corp.com".to_string())
    );

    config.team = Some(TeamConfig {
        members: vec![],
        aliases: HashMap::new(),
        canonical_domain: Some("   ".into()),
    });
    assert_eq!(
        configured_canonical_domain(&config),
        None,
        "empty is absent"
    );
}

#[test]
fn canonical_domain_routes_new_personal_email_to_existing_org_row() {
    use crate::core::db::Database;
    use rusqlite::params;

    // Why: #349 — when the first-seen commit produces a row with an
    // org-domain email, a subsequent commit by the same name under a
    // non-org email must merge into the existing org row instead of
    // creating a new personal-email identity.
    let team = TeamConfig {
        members: vec![],
        aliases: HashMap::new(),
        canonical_domain: Some("researchco.example".into()),
    };
    let r = IdentityResolver::new(Some(&team));
    let db = Database::open_in_memory().expect("db");
    // Seed an existing identity at the org-domain address.
    let _ = r
        .upsert_author(&db, "Bob Matsuoka", "bob@researchco.example")
        .expect("seed");

    // Now the same person commits from a personal address. With the
    // canonical-domain policy this must collapse onto the existing row,
    // not insert a second one.
    let id = r
        .upsert_author(&db, "Bob Matsuoka", "bob@personal.com")
        .expect("upsert");
    let stored_email: String = db
        .connection()
        .query_row(
            "SELECT canonical_email FROM authors WHERE id = ?1",
            params![id],
            |row| row.get(0),
        )
        .expect("lookup");
    assert_eq!(stored_email, "bob@researchco.example");

    // Exactly one row for "Bob Matsuoka".
    let count: i64 = db
        .connection()
        .query_row(
            "SELECT COUNT(*) FROM authors WHERE canonical_name = 'Bob Matsuoka'",
            [],
            |row| row.get(0),
        )
        .expect("count");
    assert_eq!(count, 1);
}

#[test]
fn canonical_domain_absent_falls_back_to_first_seen_email() {
    use crate::core::db::Database;

    // Why: without a configured canonical_domain we must preserve the
    // legacy first-seen behaviour so existing setups are unchanged.
    let r = IdentityResolver::new(None);
    assert_eq!(r.canonical_domain(), None);
    let db = Database::open_in_memory().expect("db");
    let _ = r
        .upsert_author(&db, "Carol", "carol@personal.com")
        .expect("seed");
    let _ = r
        .upsert_author(&db, "Carol", "carol@work.com")
        .expect("upsert");
    let count: i64 = db
        .connection()
        .query_row(
            "SELECT COUNT(*) FROM authors WHERE canonical_name = 'Carol'",
            [],
            |row| row.get(0),
        )
        .expect("count");
    // Without the policy, both emails become separate identities.
    assert_eq!(count, 2);
}

#[test]
fn email_domain_basic() {
    // Why: regression guard for the helper backing the Tier-3 domain gate
    // (#2253).
    assert_eq!(email_domain("ops+snyk@Duetto.COM"), "duetto.com");
    assert_eq!(email_domain("no-at-symbol"), "");
    // Only the last `@` delimits the domain.
    assert_eq!(email_domain("weird@name@example.org"), "example.org");
}

/// Issue #2253: two unrelated bots sharing a long common domain suffix must
/// NOT collapse into one identity via the Tier-3 fuzzy pass.
///
/// Before the fix, Tier 3 scored Jaro-Winkler on the FULL email string, so
/// `jaro_winkler("ops+snyk@duettoresearch.com", "jenkins@duettoresearch.com")`
/// = 0.857 ≥ 0.85 (the shared 18-char domain suffix alone cleared the bar),
/// misattributing every Snyk-bot commit to "Jenkins CI". Comparing
/// local-parts under a domain-equality gate keeps them distinct.
#[test]
fn tier3_does_not_merge_bots_sharing_domain_suffix() {
    let team = TeamConfig {
        members: vec![TeamMember {
            name: "Jenkins CI".into(),
            email: "jenkins@duettoresearch.com".into(),
            aliases: vec![],
        }],
        aliases: HashMap::new(),
        canonical_domain: None,
    };
    let r = IdentityResolver::new(Some(&team));

    // Sanity: the pre-fix root cause really did clear the threshold on the
    // full-string comparison, so this test is guarding a real regression.
    assert!(
        jaro_winkler("ops+snyk@duettoresearch.com", "jenkins@duettoresearch.com")
            >= DEFAULT_SIMILARITY_THRESHOLD,
        "precondition: full-string similarity should exceed the threshold"
    );

    let (name, email) = r.resolve("Snyk Bot", "ops+snyk@duettoresearch.com");
    assert_ne!(
        name, "Jenkins CI",
        "Snyk bot must not be misattributed to Jenkins CI (#2253)"
    );
    // The unrelated bot falls through unchanged.
    assert_eq!(name, "Snyk Bot");
    assert_eq!(email, "ops+snyk@duettoresearch.com");
}

/// The #2253 fix must not over-tighten: a genuine same-person match — same
/// domain, near-identical local-parts — must STILL resolve via Tier 3 even
/// when the display name is too different to carry the match on its own.
#[test]
fn tier3_still_matches_same_domain_near_identical_local_parts() {
    let team = TeamConfig {
        members: vec![TeamMember {
            name: "Alice Cooper".into(),
            email: "alice.cooper@acme.com".into(),
            aliases: vec![],
        }],
        aliases: HashMap::new(),
        canonical_domain: None,
    };
    let r = IdentityResolver::new(Some(&team));

    // Display name "acoopr" is far from "Alice Cooper"; the match rides on
    // the email local-part `alice.coopr` ~= `alice.cooper` under the shared
    // `acme.com` domain.
    let (name, email) = r.resolve("acoopr", "alice.coopr@acme.com");
    assert_eq!(name, "Alice Cooper");
    assert_eq!(email, "alice.cooper@acme.com");
}

// ---------------------------------------------------------------------------
// Issue #4251 — Tier-3/4 fuzzy fallback must not fire when a comprehensive
// `aliases_file` is supplied.
// ---------------------------------------------------------------------------

/// Roster-shaped fixture modelled on a 177-entry alias map — only the
/// members implicated in the #4251 misattributions, plus two entries whose
/// explicit aliases must keep resolving through Tiers 1/2.
const ISSUE_4251_ALIASES_YAML: &str = r#"
developers:
  - name: "Crisandra Fonseca"
    primary_email: "crisandra.fonseca@researchco.example"
    aliases: []
  - name: "Nico Mercer"
    primary_email: "nico.mercer@researchco.example"
    aliases: []
  - name: "Marcel Sutton"
    primary_email: "marcel.sutton@researchco.example"
    aliases: []
  - name: "Joshua Kepler"
    primary_email: "joshua.kepler@researchco.example"
    aliases: []
  - name: "Joshua McFarland"
    primary_email: "joshua.mcfarland@researchco.example"
    aliases: []
  - name: "Rohan Mehta"
    primary_email: "rohan.mehta@researchco.example"
    aliases:
      - "Rohan.Mehta-c@researchco.example"
      - "rohan-extern"
  - name: "Pedro Silva"
    primary_email: "pedro.silva@researchco.example"
    aliases:
      - "100000001+pedrosilvaextern@users.noreply.github.com"
"#;

/// The `(author_name, author_email)` pairs, modelled on the `tga.db` rows that
/// #4251 reports as misattributed, paired with the roster member each was
/// wrongly collapsed onto.
const ISSUE_4251_MISATTRIBUTIONS: &[(&str, &str, &str)] = &[
    (
        "Crispian Alvarenga",
        "crispian.alvarenga@researchco.example",
        "Crisandra Fonseca",
    ),
    (
        "Nico Vanderbergheim",
        "nico.vanderbergheim@researchco.example",
        "Nico Mercer",
    ),
    (
        "Marci Dalton",
        "marci.dalton@researchco.example",
        "Marcel Sutton",
    ),
    ("Josh Dorsey", "josh@researchco.example", "Joshua Kepler"),
    ("Joseph Wu", "joseph.wu@researchco.example", "Joshua Kepler"),
];

/// Materialize a `config.yaml` + external `aliases_file` pair into a private
/// temp directory and load it through the real
/// [`crate::core::config::Config::load`] path, returning `(resolver, tmpdir)`.
/// The caller must keep `tmpdir` alive for the duration of the test.
///
/// Why: #4251 is a *config-shape* defect — it only manifests when the alias map
/// arrives via `aliases_file`. Constructing the resolver by hand would bypass
/// the very wiring under test.
///
/// Uses [`tempfile::TempDir`] rather than a hand-rolled `pid + nanos` name.
/// Tests in one binary share a process, so `process::id()` is constant, and the
/// `SystemTime` remainder is coarser than a nanosecond on macOS: hand-rolled
/// names collided across the parallel tests below, and each test's cleanup then
/// deleted a directory another test was still using. Because
/// `Config::resolved_aliases()` swallows alias-file load errors, the victim
/// silently got a resolver with ZERO members — which returns every input
/// unchanged and so satisfied the primary #4251 assertion *vacuously*.
/// `TempDir` gives a kernel-guaranteed unique name and RAII cleanup that also
/// runs on panic.
fn resolver_from_aliases_file(extra_config_yaml: &str) -> (IdentityResolver, tempfile::TempDir) {
    let tmp = tempfile::TempDir::new().unwrap();

    let aliases_path = tmp.path().join("aliases.yaml");
    std::fs::write(&aliases_path, ISSUE_4251_ALIASES_YAML).unwrap();

    let config_yaml = format!(
        "version: \"1.0\"\naliases_file: \"{}\"\n{extra_config_yaml}",
        aliases_path.to_string_lossy()
    );
    let config_path = tmp.path().join("config.yaml");
    std::fs::write(&config_path, config_yaml).unwrap();

    let cfg = crate::core::config::Config::load(&config_path).unwrap();
    (IdentityResolver::from_config(&cfg), tmp)
}

/// Assert the roster actually loaded.
///
/// Why: a resolver built from a failed alias load has zero members and returns
/// **every** input unchanged — which is exactly what the #4251 pass-through
/// assertions check. Without this positive control those assertions can pass
/// against a resolver that never read the alias file. `fuzzy_fallback()` is not
/// a substitute: it is derived from config, not from load success.
fn assert_roster_loaded(r: &IdentityResolver) {
    assert_eq!(
        r.resolve("whoever", "crisandra.fonseca@researchco.example"),
        (
            "Crisandra Fonseca".to_string(),
            "crisandra.fonseca@researchco.example".to_string()
        ),
        "non-vacuity: the roster must actually be loaded, otherwise a \
         pass-through result proves nothing"
    );
    assert_eq!(
        r.resolve("rohan-extern", "noise@nowhere.test").0,
        "Rohan Mehta",
        "non-vacuity: declared login-handle aliases must be present"
    );
}

/// Issue #4251 (primary reproduction): with a comprehensive `aliases_file`
/// supplied, an author who has no alias entry must pass through UNCHANGED
/// rather than being fuzzy-guessed onto the nearest-spelled roster member.
///
/// Each pair below models a reported misattribution. The precondition
/// assertions prove the fuzzy tiers genuinely clear their thresholds on these
/// inputs, so the test cannot pass vacuously.
#[test]
fn aliases_file_disables_tier34_name_fuzzy() {
    let (r, _tmp) = resolver_from_aliases_file("");
    assert!(
        !r.fuzzy_fallback(),
        "supplying an aliases_file must disable the fuzzy fallback"
    );
    // MUST come first: everything below asserts pass-through, which a
    // zero-member resolver would also satisfy.
    assert_roster_loaded(&r);

    // Collect every resolution before asserting so a failure reports the whole
    // misattribution set, not just the first pair to trip.
    let mut observed: Vec<String> = Vec::new();
    let mut expected: Vec<String> = Vec::new();
    for (name, email, wrong_target) in ISSUE_4251_MISATTRIBUTIONS {
        // Precondition: at least one fuzzy tier really does score this pair
        // above its acceptance threshold, i.e. the defect is live in the
        // scoring functions and this assertion is guarding real behaviour.
        let raw_name = jaro_winkler(&name.to_lowercase(), &wrong_target.to_lowercase());
        let norm_local = jaro_winkler(
            &normalize_for_fuzzy(&email_local_part(email)),
            &normalize_for_fuzzy(wrong_target),
        );
        assert!(
            raw_name >= DEFAULT_SIMILARITY_THRESHOLD
                || norm_local >= NORMALIZED_SIMILARITY_THRESHOLD,
            "precondition: {name} vs {wrong_target} must be fuzzy-reachable \
             (tier3 name={raw_name:.4}, tier4 normalized={norm_local:.4})"
        );

        let (resolved_name, resolved_email) = r.resolve(name, email);
        observed.push(format!(
            "{name} <{email}> => {resolved_name} <{resolved_email}>"
        ));
        // Correct behaviour: an undeclared identity is returned untouched.
        expected.push(format!("{name} <{email}> => {name} <{email}>"));
    }
    assert_eq!(
        observed, expected,
        "#4251: undeclared authors must pass through, not be guessed onto the \
         nearest-spelled roster member"
    );
}

/// The #4251 gate must not cost us the alias-table resolutions that the
/// 130 → 177 entry expansion was made FOR. Every genuine correction rides on
/// Tiers 1/2 (exact alias / canonical email / login handle), which the gate
/// leaves untouched.
#[test]
fn aliases_file_gate_preserves_tier12_declared_resolutions() {
    let (r, _tmp) = resolver_from_aliases_file("");

    // Declared secondary email (the `-c` contractor variant) → canonical pair.
    let (n, e) = r.resolve("whoever", "Rohan.Mehta-c@researchco.example");
    assert_eq!(n, "Rohan Mehta");
    assert_eq!(e, "rohan.mehta@researchco.example");

    // Declared non-email login handle.
    let (n, e) = r.resolve("rohan-extern", "noise@nowhere.test");
    assert_eq!(n, "Rohan Mehta");
    assert_eq!(e, "rohan.mehta@researchco.example");

    // Declared GitHub noreply alias.
    let (n, e) = r.resolve(
        "pedrosilvaextern",
        "100000001+pedrosilvaextern@users.noreply.github.com",
    );
    assert_eq!(n, "Pedro Silva");
    assert_eq!(e, "pedro.silva@researchco.example");

    // Canonical email, case-folded.
    let (n, e) = r.resolve("whoever", "CRISANDRA.FONSECA@RESEARCHCO.EXAMPLE");
    assert_eq!(n, "Crisandra Fonseca");
    assert_eq!(e, "crisandra.fonseca@researchco.example");
}

/// `fuzzy_identity_fallback: true` is the documented escape hatch: a project
/// that wants the old guessing behaviour alongside its alias file can say so,
/// and then the reported misattributions come back.
#[test]
fn explicit_opt_in_reenables_fuzzy_with_aliases_file() {
    let (r, _tmp) = resolver_from_aliases_file("fuzzy_identity_fallback: true\n");
    assert!(
        r.fuzzy_fallback(),
        "explicit opt-in must re-enable Tier 3/4"
    );
    assert_roster_loaded(&r);

    // With fuzzy back on, `Marci Dalton` collapses onto `Marcel Sutton` again —
    // the exact defect #4251 reports, proving the flag is load-bearing and the
    // primary test above is not passing for some unrelated reason.
    let (n, _) = r.resolve("Marci Dalton", "marci.dalton@researchco.example");
    assert_eq!(n, "Marcel Sutton");
}

/// The non-vacuity control must actually reject a resolver that never loaded
/// the roster.
///
/// Why: `assert_roster_loaded` is the only thing standing between a zero-member
/// resolver and a vacuously-green #4251 proof. Measured on the pre-fix helper,
/// a zero-member resolver satisfied **every** assertion of
/// `aliases_file_disables_tier34_name_fuzzy`, including `!fuzzy_fallback()` —
/// pass-through is what an empty resolver does. A guard nobody proves is
/// load-bearing is not a guard, so this pins it.
#[test]
#[should_panic(expected = "non-vacuity")]
fn non_vacuity_control_rejects_zero_member_resolver() {
    let empty: HashMap<String, Vec<String>> = HashMap::new();
    let r = IdentityResolver::from_alias_map(&empty);
    // Sanity: this resolver passes everything through, exactly like the racing
    // zero-member resolver did.
    assert_eq!(
        r.resolve(
            "Crispian Alvarenga",
            "crispian.alvarenga@researchco.example"
        ),
        (
            "Crispian Alvarenga".to_string(),
            "crispian.alvarenga@researchco.example".to_string()
        )
    );
    assert_roster_loaded(&r); // must panic
}

/// A declared-but-unloadable `aliases_file` must NOT disable the fallback.
///
/// Why: `Config::resolved_aliases` swallows alias-file load errors. If the gate
/// keyed on the mere presence of the `aliases_file` key, a typo'd path would
/// produce an empty alias table AND a disabled fallback — every author
/// fragments to its raw identity and nothing in the resolution path says why.
/// Gating on a successful, non-empty load means a broken config degrades to the
/// documented pre-#4251 behaviour instead of to silent fragmentation.
#[test]
fn broken_aliases_file_keeps_fuzzy_enabled() {
    let tmp = tempfile::TempDir::new().unwrap();
    let missing = tmp.path().join("does-not-exist.yaml");
    let config_yaml = format!(
        "version: \"1.0\"\naliases_file: \"{}\"\n",
        missing.to_string_lossy()
    );
    let config_path = tmp.path().join("config.yaml");
    std::fs::write(&config_path, config_yaml).unwrap();

    let cfg = crate::core::config::Config::load(&config_path).unwrap();
    // Precondition: the alias map really did fail to load, and the failure
    // really is swallowed — this is the trap being guarded.
    assert!(cfg.resolved_alias_map(cfg.config_dir()).is_err());
    assert!(cfg.resolved_aliases().is_empty());

    let r = IdentityResolver::from_config(&cfg);
    assert!(
        r.fuzzy_fallback(),
        "a declared aliases_file that failed to load must not be treated as a \
         comprehensive alias table"
    );
}

/// An `aliases_file` that loads but declares no developers is equally not a
/// comprehensive table, and must not disable the fallback either.
#[test]
fn empty_aliases_file_keeps_fuzzy_enabled() {
    let tmp = tempfile::TempDir::new().unwrap();
    let aliases_path = tmp.path().join("aliases.yaml");
    std::fs::write(&aliases_path, "developers: []\n").unwrap();
    let config_yaml = format!(
        "version: \"1.0\"\naliases_file: \"{}\"\n",
        aliases_path.to_string_lossy()
    );
    let config_path = tmp.path().join("config.yaml");
    std::fs::write(&config_path, config_yaml).unwrap();

    let cfg = crate::core::config::Config::load(&config_path).unwrap();
    assert!(cfg.resolved_alias_map(cfg.config_dir()).unwrap().is_empty());

    let r = IdentityResolver::from_config(&cfg);
    assert!(r.fuzzy_fallback());
}

/// A non-empty INLINE `developer_aliases` map must not disable the fallback.
///
/// Why: this pins the gate to `aliases_file` specifically, which is what #4251
/// asks for. A gate written as `map.is_empty() && aliases_file.is_none()` would
/// silently flip every inline-alias deployment to fuzzy-off — a behaviour
/// change well outside the issue's scope. This test fails under that form.
#[test]
fn inline_developer_aliases_do_not_disable_fuzzy() {
    let yaml = r#"
version: "1.0"
developer_aliases:
  "Marcel Sutton":
    - "marcel.sutton@researchco.example"
"#;
    let cfg: crate::core::config::Config = serde_yaml::from_str(yaml).unwrap();
    assert!(
        !cfg.resolved_aliases().is_empty(),
        "inline map must be loaded"
    );
    let r = IdentityResolver::from_config(&cfg);
    assert!(
        r.fuzzy_fallback(),
        "#4251 gates on aliases_file, not on any non-empty alias map"
    );
    // Historical fuzzy behaviour is intact for these deployments.
    let (n, _) = r.resolve("Marci Dalton", "marci.dalton@researchco.example");
    assert_eq!(n, "Marcel Sutton");
}

/// `fuzzy_identity_fallback: false` turns the fallback off even when no
/// `aliases_file` is present (inline `developer_aliases` deployments).
#[test]
fn explicit_opt_out_disables_fuzzy_without_aliases_file() {
    let yaml = r#"
version: "1.0"
fuzzy_identity_fallback: false
developer_aliases:
  "Marcel Sutton":
    - "marcel.sutton@researchco.example"
"#;
    let cfg: crate::core::config::Config = serde_yaml::from_str(yaml).unwrap();
    let r = IdentityResolver::from_config(&cfg);
    assert!(!r.fuzzy_fallback());
    let (n, e) = r.resolve("Marci Dalton", "marci.dalton@researchco.example");
    assert_eq!(n, "Marci Dalton");
    assert_eq!(e, "marci.dalton@researchco.example");
}

/// No `aliases_file` and no explicit flag → historical behaviour is preserved
/// exactly. This is the compatibility guarantee for every existing deployment
/// that relies on fuzzy resolution.
#[test]
fn no_aliases_file_keeps_fuzzy_enabled_by_default() {
    let yaml = r#"
version: "1.0"
developer_aliases:
  "Bob Matsuoka":
    - "bob.matsuoka@researchco.example"
"#;
    let cfg: crate::core::config::Config = serde_yaml::from_str(yaml).unwrap();
    let r = IdentityResolver::from_config(&cfg);
    assert!(r.fuzzy_fallback());
    let (n, _) = r.resolve("Bob M", "bob.matsuoka@otherdomain.com");
    assert_eq!(n, "Bob Matsuoka");
}

/// The builder switch works for callers that never touch `Config`
/// (`trusty-review`'s profile selector, `feed_azdo_users`, benches).
#[test]
fn with_fuzzy_fallback_false_suppresses_tier34() {
    let r = IdentityResolver::new(Some(&make_team()));
    // Baseline: fuzzy on, "Bob Smyth" collapses onto "Bob Smith".
    assert_eq!(
        r.resolve("Bob Smyth", "unknown@elsewhere.com").0,
        "Bob Smith"
    );

    let r = IdentityResolver::new(Some(&make_team())).with_fuzzy_fallback(false);
    let (n, e) = r.resolve("Bob Smyth", "unknown@elsewhere.com");
    assert_eq!(n, "Bob Smyth");
    assert_eq!(e, "unknown@elsewhere.com");
    // Exact alias resolution is untouched by the switch.
    assert_eq!(r.resolve("bobby", "x@y.com").0, "Bob Smith");
}

/// Issue #2253 regression guard, re-asserted under #4251: the email-domain
/// gate is orthogonal to the new switch and must still hold on a resolver with
/// fuzzy ENABLED (no `aliases_file`), which is the configuration #2253 fixed.
#[test]
fn issue_2253_domain_gate_intact_when_fuzzy_enabled() {
    let team = TeamConfig {
        members: vec![
            TeamMember {
                name: "Jenkins CI".into(),
                email: "jenkins@duettoresearch.com".into(),
                aliases: vec![],
            },
            TeamMember {
                name: "Alice Cooper".into(),
                email: "alice.cooper@acme.com".into(),
                aliases: vec![],
            },
        ],
        aliases: HashMap::new(),
        canonical_domain: None,
    };
    let r = IdentityResolver::new(Some(&team));
    assert!(r.fuzzy_fallback(), "no aliases_file → fuzzy stays on");

    // Shared domain suffix alone must NOT merge two unrelated bots (#2253).
    assert!(
        jaro_winkler("ops+snyk@duettoresearch.com", "jenkins@duettoresearch.com")
            >= DEFAULT_SIMILARITY_THRESHOLD,
        "precondition: full-string similarity clears the threshold"
    );
    let (n, e) = r.resolve("Snyk Bot", "ops+snyk@duettoresearch.com");
    assert_eq!(n, "Snyk Bot");
    assert_eq!(e, "ops+snyk@duettoresearch.com");

    // ...while a genuine same-domain, near-identical local-part still matches.
    let (n, e) = r.resolve("acoopr", "alice.coopr@acme.com");
    assert_eq!(n, "Alice Cooper");
    assert_eq!(e, "alice.cooper@acme.com");
}

#[test]
fn canonical_domain_read_from_config() {
    // Why: confirms YAML deserialization wires the new key end-to-end.
    let yaml = r#"
team:
  canonical_domain: "researchco.example"
  members:
    - name: "Alice"
      email: "alice@researchco.example"
"#;
    let cfg: crate::core::config::Config = serde_yaml::from_str(yaml).expect("parse");
    let r = IdentityResolver::from_config(&cfg);
    assert_eq!(r.canonical_domain(), Some("researchco.example"));
}

// ---------------------------------------------------------------------------
// Issue #4293 — identity-resolution determinism.
// ---------------------------------------------------------------------------

/// Why: #4293 — `from_alias_map` pushed members in `HashMap` iteration order,
/// which std randomises per map instance, so two resolvers built from the same
/// roster in the same process held different `members` slices.
/// What: rebuilds the map and the resolver from scratch and asserts the
/// `members` slice, and one fuzzy resolution over it, are identical every time.
#[test]
fn member_order_is_deterministic_across_rebuilds() {
    fn build() -> IdentityResolver {
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        for (name, email) in [
            ("Joshua Kepler", "joshua.kepler@acme.com"),
            ("Joshua Mcfarland", "joshua.mcfarland@acme.com"),
            ("Joshua Renner", "joshua.renner@acme.com"),
            ("Joshua Vance", "joshua.vance@acme.com"),
            ("Joshua Whitlock", "joshua.whitlock@acme.com"),
            ("Joshua Ackley", "joshua.ackley@acme.com"),
        ] {
            map.insert(name.to_string(), vec![email.to_string()]);
        }
        IdentityResolver::from_alias_map(&map)
    }

    // Sorted by (canonical_email, canonical_name), not by declaration order.
    let expected_members: Vec<(String, String)> = [
        ("Joshua Ackley", "joshua.ackley@acme.com"),
        ("Joshua Kepler", "joshua.kepler@acme.com"),
        ("Joshua Mcfarland", "joshua.mcfarland@acme.com"),
        ("Joshua Renner", "joshua.renner@acme.com"),
        ("Joshua Vance", "joshua.vance@acme.com"),
        ("Joshua Whitlock", "joshua.whitlock@acme.com"),
    ]
    .iter()
    .map(|(n, e)| ((*n).to_string(), (*e).to_string()))
    .collect();

    let expected_resolution = build().resolve("josh", "josh@unaffiliated.test");
    for i in 0..100 {
        let r = build();
        assert_eq!(
            r.members, expected_members,
            "members order differs on rebuild {i}"
        );
        assert_eq!(
            r.resolve("josh", "josh@unaffiliated.test"),
            expected_resolution,
            "resolution differs on rebuild {i}"
        );
    }
}

/// Why: #4293 — both fuzzy tiers kept the incumbent on an exact score tie, so
/// two roster members scoring identically were separated by declaration order.
/// What: two members share a canonical name and differ only by email, which
/// makes their Jaro-Winkler scores exactly equal; the resolver must pick the
/// lower `(canonical_email, canonical_name)` key in either declaration order.
#[test]
fn fuzzy_tie_breaks_on_stable_key() {
    fn team(order: [(&str, &str); 2]) -> TeamConfig {
        TeamConfig {
            members: order
                .iter()
                .map(|(n, e)| TeamMember {
                    name: (*n).to_string(),
                    email: (*e).to_string(),
                    aliases: vec![],
                })
                .collect(),
            aliases: HashMap::new(),
            canonical_domain: None,
        }
    }

    let a = ("Sam Taylor", "a.taylor@acme.com");
    let b = ("Sam Taylor", "b.taylor@acme.com");
    let inbound_name = "Sam Taylorr";
    let inbound_email = "sam@unaffiliated.test";

    // Precondition: the two members score an EXACT tie for this inbound pair.
    // An exact tie is the trigger condition for the defect.
    let score_a = jaro_winkler(&inbound_name.to_lowercase(), &a.0.to_lowercase());
    let score_b = jaro_winkler(&inbound_name.to_lowercase(), &b.0.to_lowercase());
    assert_eq!(score_a, score_b, "precondition: scores must tie exactly");
    assert!(
        score_a >= DEFAULT_SIMILARITY_THRESHOLD,
        "precondition: the tied score must clear the Tier-3 threshold"
    );

    for order in [[a, b], [b, a]] {
        let r = IdentityResolver::new(Some(&team(order)));
        let (n, e) = r.resolve(inbound_name, inbound_email);
        assert_eq!(n, "Sam Taylor");
        assert_eq!(
            e, "a.taylor@acme.com",
            "tie must go to the lowest (email, name) key; declared order was {order:?}"
        );
    }
}

/// Why: #4293 — an alias claimed by two canonical identities was resolved
/// last-writer-wins over `HashMap` iteration order, so it mapped to a different
/// person between two resolvers built from identical input.
/// What: rebuilds a map in which both identities declare `jr` and asserts the
/// same canonical identity every time — the first claimant in sorted
/// canonical-name order keeps the alias.
#[test]
fn alias_collision_resolves_deterministically() {
    fn build() -> IdentityResolver {
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        map.insert(
            "Jane Roe".to_string(),
            vec!["jane.roe@acme.com".into(), "jr".into()],
        );
        map.insert(
            "John Roe".to_string(),
            vec!["john.roe@acme.com".into(), "jr".into()],
        );
        IdentityResolver::from_alias_map(&map)
    }

    for i in 0..200 {
        let (n, e) = build().resolve("jr", "jr@unaffiliated.test");
        assert_eq!(n, "Jane Roe", "alias collision flipped on rebuild {i}");
        assert_eq!(
            e, "jane.roe@acme.com",
            "alias collision flipped on rebuild {i}"
        );
    }
}

/// A `TeamConfig` carrying both collision shapes #4293 covers on the `team:`
/// path: two members declaring the alias `jr`, and two free-form `team.aliases`
/// keys that both lower-case to `jr2`. Rebuilt per call so each iteration gets
/// a fresh `HashMap` with its own iteration order.
fn colliding_team_resolver() -> IdentityResolver {
    let mut aliases = HashMap::new();
    // Two keys that collide once lowercased. "JR2" sorts before "jr2".
    aliases.insert("JR2".to_string(), "John Roe".to_string());
    aliases.insert("jr2".to_string(), "Jane Roe".to_string());
    let team = TeamConfig {
        members: vec![
            TeamMember {
                name: "Jane Roe".into(),
                email: "jane.roe@acme.com".into(),
                aliases: vec!["jr".into()],
            },
            TeamMember {
                name: "John Roe".into(),
                email: "john.roe@acme.com".into(),
                aliases: vec!["jr".into()],
            },
        ],
        aliases,
        canonical_domain: None,
    };
    IdentityResolver::new(Some(&team))
}

/// Why: #4293 — `new()` wrote member aliases with a raw `HashMap::insert`, so a
/// contested alias went to the LAST member declared: the opposite policy from
/// `from_alias_map`'s first-claimant-wins.
/// What: two members declare `jr`; the lowest `(email, name)` member must claim
/// it, not the one declared last.
#[test]
fn team_member_alias_collision_goes_to_the_first_claimant() {
    for i in 0..200 {
        let (n, e) = colliding_team_resolver().resolve("jr", "jr@unaffiliated.test");
        assert_eq!(
            n, "Jane Roe",
            "member alias collision flipped on rebuild {i}"
        );
        assert_eq!(
            e, "jane.roe@acme.com",
            "member alias collision flipped on rebuild {i}"
        );
    }
}

/// Why: #4293 — `team.aliases` is a `HashMap`, so two keys differing only by
/// case raced for the same lowercased slot and the last writer took it.
/// What: `JR2` and `jr2` both lower-case to `jr2`; the first in sorted key order
/// must claim it on every rebuild.
#[test]
fn team_free_form_alias_case_collision_goes_to_the_first_claimant() {
    for i in 0..200 {
        let (n, e) = colliding_team_resolver().resolve("jr2", "jr2@unaffiliated.test");
        assert_eq!(
            n, "John Roe",
            "team.aliases case collision flipped on rebuild {i}"
        );
        assert_eq!(
            e, "john.roe@acme.com",
            "team.aliases case collision flipped on rebuild {i}"
        );
    }
}