fallow-api 3.48.0

Programmatic API contract types for fallow
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
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
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::Path;

use rustc_hash::{FxHashMap, FxHashSet};

#[path = "audit_keys_collection.rs"]
mod collection;
#[macro_use]
#[path = "audit_keys_ledger_collections.rs"]
mod ledger_collections;
#[path = "audit_keys_styling.rs"]
mod styling;

pub use styling::{
    styling_finding_key, styling_keys, styling_ledger_keys, styling_ledger_keys_with_diff,
};

use collection::AuditCollection;

use fallow_config::{ResolvedConfig, Severity};
use fallow_types::envelope::AuditIntroduced;
use fallow_types::identity::{IdentifiedFinding, IdentityPaths, dead_code_occurrence_keys};

pub use crate::audit_complexity::{
    ChangedPaths, ComplexityBaseline, ComplexityClass, ComplexityMetrics,
    classify_complexity_attribution, classify_complexity_attribution_against_all,
    classify_complexity_attribution_against_all_with_moves,
    classify_complexity_attribution_with_moves, classify_complexity_findings,
    classify_complexity_findings_against_all, complexity_baseline, complexity_baseline_keys,
    complexity_ledger_keys, remap_complexity_baseline_for_renames,
};

/// One dead-code finding classified for audit comparison.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditFindingRecord {
    /// JSON collection containing the finding.
    pub collection: &'static str,
    /// Stable position inside the collection for typed annotation routing.
    pub ordinal: usize,
    /// Stable cross-run identity used for base comparison.
    pub stable_key: String,
    /// Whether the finding is absent from the base snapshot.
    pub introduced: bool,
    /// Effective rule severity after per-file overrides.
    pub effective_severity: Severity,
}

fn is_counted_dead_code_finding(collection: &str, severity: Severity) -> bool {
    severity != Severity::Off
        && (!fallow_types::results::ERROR_ONLY_RESULT_KEYS.contains(&collection)
            || severity == Severity::Error)
}

/// Exhaustive dead-code comparison ledger shared by audit verdict and output.
#[derive(Debug, Clone, Default)]
pub struct DeadCodeAuditLedger {
    records: Vec<AuditFindingRecord>,
    keys: FxHashSet<String>,
    introduced_keys: FxHashSet<String>,
    inherited_keys: FxHashSet<String>,
    #[cfg(test)]
    classifications: usize,
}

impl DeadCodeAuditLedger {
    /// Classified findings in deterministic output order.
    #[must_use]
    pub fn records(&self) -> &[AuditFindingRecord] {
        &self.records
    }

    /// Stable current-run key set for cache snapshots and graph hashes.
    #[must_use]
    pub const fn keys(&self) -> &FxHashSet<String> {
        &self.keys
    }

    #[cfg(test)]
    const fn classification_count(&self) -> usize {
        self.classifications
    }

    /// Number of visible findings introduced since the base snapshot.
    #[must_use]
    pub fn introduced_count(&self) -> usize {
        self.introduced_keys.len()
    }

    /// Number of counted findings whose effective severity is not off.
    /// Advisory component findings remain available in the records.
    #[must_use]
    pub fn visible_count(&self) -> usize {
        self.records
            .iter()
            .filter(|record| {
                is_counted_dead_code_finding(record.collection, record.effective_severity)
            })
            .count()
    }

    /// Number of counted findings that are introduced, with the filter of
    /// [`Self::visible_count`]. This is the dead-code count of a report that
    /// keeps only introduced findings.
    #[must_use]
    pub fn visible_introduced_count(&self) -> usize {
        self.records
            .iter()
            .filter(|record| {
                record.introduced
                    && is_counted_dead_code_finding(record.collection, record.effective_severity)
            })
            .count()
    }

    /// Number of visible findings inherited from the base snapshot.
    #[must_use]
    pub fn inherited_count(&self) -> usize {
        self.inherited_keys.len()
    }

    /// Whether an introduced finding has effective error severity.
    #[must_use]
    pub fn has_introduced_errors(&self) -> bool {
        self.records
            .iter()
            .any(|record| record.introduced && record.effective_severity == Severity::Error)
    }
    /// Whether an introduced finding has effective warning severity.
    #[must_use]
    pub fn has_introduced_warnings(&self) -> bool {
        self.records
            .iter()
            .any(|record| record.introduced && record.effective_severity == Severity::Warn)
    }
    /// Demote introduced findings that have no syntactic counterpart in the
    /// current head run to inherited (advisory) status.
    ///
    /// Used by the audit's degraded type-aware path: when base and head
    /// semantic identities cannot be compared, attribution diffs the
    /// pre-refinement syntactic key sets. A head finding absent from its own
    /// syntactic set exists only because of semantic evidence and cannot be
    /// attributed against a syntactic base, so it must not fail the new-only
    /// gate. Findings present syntactically keep their classification, so a
    /// genuinely new syntactic finding still gates.
    pub fn demote_unattributable_introductions(&mut self, head_syntactic: &FxHashSet<String>) {
        for record in &mut self.records {
            if record.introduced && !head_syntactic.contains(&record.stable_key) {
                record.introduced = false;
                self.introduced_keys.remove(&record.stable_key);
                if is_counted_dead_code_finding(record.collection, record.effective_severity) {
                    self.inherited_keys.insert(record.stable_key.clone());
                }
            }
        }
    }
    /// Mark the introduced findings whose keys are in `inherit` as inherited:
    /// each one matches a base finding under another key.
    pub fn inherit_introductions(&mut self, inherit: &FxHashSet<String>) {
        for record in &mut self.records {
            if record.introduced && inherit.contains(&record.stable_key) {
                record.introduced = false;
                self.introduced_keys.remove(&record.stable_key);
                if is_counted_dead_code_finding(record.collection, record.effective_severity) {
                    self.inherited_keys.insert(record.stable_key.clone());
                }
            }
        }
    }
    /// Persist comparison membership into existing typed output fields.
    ///
    /// `StaleSuppression` is the sole legacy finding without a typed
    /// `introduced` slot. Its serializer keeps a narrow stable-key fallback.
    pub fn annotate_results(&self, results: &mut fallow_types::results::AnalysisResults) {
        macro_rules! annotate {
            (@no_slot $field:ident, $collection:literal) => {
                let _ = $field;
            };
            ($field:ident, $collection:literal) => {
                for (item, introduced) in $field.iter_mut().zip(self.flags($collection)) {
                    item.introduced = Some(AuditIntroduced(introduced));
                }
            };
        }
        for_each_ledger_collection!(results, annotate);
    }

    /// Remove every finding that the base snapshot already holds. A finding
    /// without a ledger record stays, so the filter never hides a finding
    /// that the comparison did not classify.
    pub fn retain_introduced_results(&self, results: &mut fallow_types::results::AnalysisResults) {
        macro_rules! retain {
            ($(@no_slot)? $field:ident, $collection:literal) => {
                let mut flags = self.flags($collection);
                $field.retain(|_| flags.next().unwrap_or(true));
            };
        }
        for_each_ledger_collection!(results, retain);
    }

    /// The introduced flag of each record of `collection`, in output order.
    fn flags<'a>(&'a self, collection: &'a str) -> impl Iterator<Item = bool> + 'a {
        self.records
            .iter()
            .filter(move |record| record.collection == collection)
            .map(|record| record.introduced)
    }
}

/// Stable-key membership for one non-dead-code audit domain.
#[derive(Debug, Clone, Default)]
pub struct AuditDomainLedger {
    records: Vec<(String, bool)>,
    keys: FxHashSet<String>,
    introduced_keys: FxHashSet<String>,
    inherited_keys: FxHashSet<String>,
    demoted_keys: FxHashSet<String>,
}

impl AuditDomainLedger {
    /// Compare ordered stable keys against an optional base snapshot.
    #[must_use]
    pub fn compare(
        keys: impl IntoIterator<Item = String>,
        base: Option<&FxHashSet<String>>,
    ) -> Self {
        let mut records = Vec::new();
        let mut unique_keys = FxHashSet::default();
        let mut introduced_keys = FxHashSet::default();
        let mut inherited_keys = FxHashSet::default();
        for key in keys {
            let introduced = base.is_some_and(|base| !base.contains(&key));
            if base.is_some() {
                if introduced {
                    introduced_keys.insert(key.clone());
                } else {
                    inherited_keys.insert(key.clone());
                }
            }
            unique_keys.insert(key.clone());
            records.push((key, introduced));
        }
        Self {
            records,
            keys: unique_keys,
            introduced_keys,
            inherited_keys,
            demoted_keys: FxHashSet::default(),
        }
    }

    /// Build a ledger from keys that the caller already classified, in
    /// typed output order. `has_base` is false when the run has no base
    /// snapshot, so no finding counts as introduced or inherited.
    #[must_use]
    pub fn from_classified(
        records: impl IntoIterator<Item = (String, bool)>,
        has_base: bool,
    ) -> Self {
        let mut ledger = Self::default();
        for (key, introduced) in records {
            let introduced = has_base && introduced;
            if has_base {
                if introduced {
                    ledger.introduced_keys.insert(key.clone());
                } else {
                    ledger.inherited_keys.insert(key.clone());
                }
            }
            ledger.keys.insert(key.clone());
            ledger.records.push((key, introduced));
        }
        ledger
    }

    /// Stable current-run key set.
    #[must_use]
    pub const fn keys(&self) -> &FxHashSet<String> {
        &self.keys
    }

    /// Number of introduced findings.
    #[must_use]
    pub fn introduced_count(&self) -> usize {
        self.introduced_keys.len()
    }

    /// Number of inherited findings.
    #[must_use]
    pub fn inherited_count(&self) -> usize {
        self.inherited_keys.len()
    }

    /// Introduced membership in typed output order.
    pub fn introduced(&self) -> impl ExactSizeIterator<Item = bool> + '_ {
        self.records.iter().map(|(_, introduced)| *introduced)
    }

    /// Number of findings demoted from introduced to inherited. Demoted
    /// findings stay counted as inherited, so
    /// `demoted_count() <= inherited_count()` holds by construction.
    #[must_use]
    pub fn demoted_count(&self) -> usize {
        self.demoted_keys.len()
    }

    /// Keys demoted from introduced to inherited by
    /// [`Self::demote_introductions`].
    #[must_use]
    pub const fn demoted_keys(&self) -> &FxHashSet<String> {
        &self.demoted_keys
    }

    /// Demoted membership in typed output order, parallel to
    /// [`Self::introduced`].
    pub fn demoted(&self) -> impl ExactSizeIterator<Item = bool> + '_ {
        self.records
            .iter()
            .map(|(key, _)| self.demoted_keys.contains(key))
    }

    /// Demote introduced findings whose keys are in `demote` to inherited
    /// (advisory) status so they no longer fail the new-only gate. Each key
    /// actually flipped is recorded so output surfaces can report the
    /// demotion (issue #2220).
    pub fn demote_introductions(&mut self, demote: &FxHashSet<String>) {
        for (key, introduced) in &mut self.records {
            if *introduced && demote.contains(key) {
                *introduced = false;
                self.introduced_keys.remove(key);
                self.inherited_keys.insert(key.clone());
                self.demoted_keys.insert(key.clone());
            }
        }
    }

    /// Whether the finding with `key` is introduced.
    #[must_use]
    pub fn is_introduced(&self, key: &str) -> bool {
        self.introduced_keys.contains(key)
    }

    /// Mark introduced findings whose keys are in `inherit` as inherited.
    /// Unlike [`Self::demote_introductions`], this records no demotion: the
    /// finding matches a base finding, only its key changed.
    pub fn inherit_introductions(&mut self, inherit: &FxHashSet<String>) {
        for (key, introduced) in &mut self.records {
            if *introduced && inherit.contains(key) {
                *introduced = false;
                self.introduced_keys.remove(key);
                self.inherited_keys.insert(key.clone());
            }
        }
    }
}

/// One-pass audit comparison shared by attribution, verdict, and annotations.
#[derive(Debug, Clone, Default)]
pub struct AuditComparison {
    /// Dead-code finding ledger with effective severity routing.
    pub dead_code: DeadCodeAuditLedger,
    /// Complexity finding membership.
    pub health: AuditDomainLedger,
    /// Attribution class of each complexity finding, in report order. Empty
    /// without a base snapshot.
    pub health_classes: Vec<crate::audit_complexity::ComplexityClass>,
    /// Duplication group membership. The introduced flag of a group is the
    /// gate result of its region.
    pub dupes: AuditDomainLedger,
    /// The clone regions: the head groups whose instances overlap, with a
    /// grade each. Empty until the audit grades them, or without a base.
    pub dupe_regions: crate::audit_run::CloneRegions,
    /// Styling finding membership.
    pub styling: AuditDomainLedger,
}

impl AuditComparison {
    /// Number of clone regions that fail the gate. Without graded regions,
    /// the number of introduced clone groups.
    #[must_use]
    pub fn duplication_introduced_count(&self) -> usize {
        if self.dupe_regions.regions().is_empty() {
            self.dupes.introduced_count()
        } else {
            self.dupe_regions.introduced_count()
        }
    }

    /// Number of clone regions that do not fail the gate. Without graded
    /// regions, the number of inherited clone groups.
    #[must_use]
    pub fn duplication_inherited_count(&self) -> usize {
        if self.dupe_regions.regions().is_empty() {
            self.dupes.inherited_count()
        } else {
            self.dupe_regions.inherited_count()
        }
    }

    /// Number of complexity findings whose attribution is `worsened`.
    #[must_use]
    pub fn complexity_worsened_count(&self) -> usize {
        self.health_classes
            .iter()
            .filter(|class| class.is_worsened())
            .count()
    }

    /// Reclassify worsened complexity findings as inherited when `worsened`
    /// is `audit.worsened: off`. Growth of an exceeded metric stays worsened,
    /// see [`ComplexityClass::clear_worsened_for_off`].
    pub fn clear_worsened_when_off(&mut self, worsened: fallow_config::AuditWorsened) {
        if worsened != fallow_config::AuditWorsened::Off {
            return;
        }
        for class in &mut self.health_classes {
            class.clear_worsened_for_off();
        }
    }
}

/// Remap root-relative path tokens inside base-snapshot attribution keys so a
/// finding on a renamed file matches its base counterpart under the old path.
///
/// `renames` maps base-relative old paths to head-relative new paths, both in
/// [`relative_key_path`] form. Keys embed paths as whole `:`-separated
/// segments, with sorted `|`-separated path lists inside one segment for
/// multi-file findings (duplication groups, circular dependencies, duplicate
/// exports). Segments are remapped only on an exact path match, and
/// multi-path list segments are re-sorted after remapping so they stay
/// canonical. Non-path segments (names, lines, hashes) never collide with a
/// relative path and pass through unchanged.
#[must_use]
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashMap/FxHashSet across audit attribution keys"
)]
pub fn remap_keys_for_renames(
    keys: &FxHashSet<String>,
    renames: &FxHashMap<String, String>,
) -> FxHashSet<String> {
    keys.iter()
        .map(|key| remap_key_for_renames(key, renames))
        .collect()
}

pub(crate) fn remap_key_for_renames(key: &str, renames: &FxHashMap<String, String>) -> String {
    let renamed = |segment: &str| {
        if segment.contains('|') {
            segment
                .split('|')
                .any(|piece| renamed_set_member(piece, renames).is_some())
        } else {
            renamed_part(segment, renames).is_some()
        }
    };
    if !key.split(':').any(renamed) {
        return key.to_string();
    }
    let segments: Vec<String> = key
        .split(':')
        .map(|segment| {
            if segment.contains('|') {
                let mut pieces: Vec<String> = segment
                    .split('|')
                    .map(|piece| {
                        renamed_set_member(piece, renames).unwrap_or_else(|| piece.to_string())
                    })
                    .collect();
                // The key sorts the set members before it escapes the part.
                pieces.sort_unstable_by_key(|piece| unescape_key_part(piece));
                pieces.dedup();
                pieces.join("|")
            } else {
                renamed_part(segment, renames).unwrap_or_else(|| segment.to_string())
            }
        })
        .collect();
    segments.join(":")
}

/// The head path of a renamed key part, in the form of the part.
///
/// A dead-code key escapes `%` and `:` in each part, and the rename map holds
/// plain paths, so an escaped part is compared and returned in the escaped
/// form. Other keys hold the plain path.
fn renamed_part(part: &str, renames: &FxHashMap<String, String>) -> Option<String> {
    if let Some(renamed) = renames.get(part) {
        return Some(renamed.clone());
    }
    if !part.contains('%') {
        return None;
    }
    renames
        .get(&unescape_key_part(part))
        .map(|renamed| escape_key_part(renamed))
}

/// The head path of a renamed member of a `|`-separated path set, in the form
/// of the member.
///
/// A dead-code key escapes each set member (`%` as `%25`, `|` as `%7C`) and
/// then the whole part, so an escaped member is decoded twice and encoded
/// twice. Other keys hold the plain path.
fn renamed_set_member(member: &str, renames: &FxHashMap<String, String>) -> Option<String> {
    if let Some(renamed) = renames.get(member) {
        return Some(renamed.clone());
    }
    if !member.contains('%') {
        return None;
    }
    let path = unescape_key_part(member)
        .replace("%7C", "|")
        .replace("%25", "%");
    renames
        .get(&path)
        .map(|renamed| escape_key_part(&renamed.replace('%', "%25").replace('|', "%7C")))
}

/// A key part as the finding holds it: `%3A` is `:` and `%25` is `%`.
pub(crate) fn unescape_key_part(part: &str) -> String {
    part.replace("%3A", ":").replace("%25", "%")
}

/// A path as a dead-code key part holds it: `%` is `%25` and `:` is `%3A`.
fn escape_key_part(path: &str) -> String {
    path.replace('%', "%25").replace(':', "%3A")
}

/// Canonical path form used inside attribution keys. The engine owns the one
/// implementation, because its module-graph maps use the same keys.
pub use fallow_engine::module_graph::relative_key_path;

/// The audit keys of one finding collection, in collection order.
///
/// Each key is the canonical key of the finding (see
/// [`fallow_types::identity`]), so a line shift does not change it. A repeated
/// key gets an occurrence suffix, so the base and the head compare by count:
/// a new second finding with an inherited key is introduced.
pub fn collection_keys<T: IdentifiedFinding>(items: &[T], root: &Path) -> Vec<String> {
    dead_code_occurrence_keys(items, &IdentityPaths::new(root))
}

/// The six dependency-related finding slices, bundled so the dependency
/// dispatcher takes one parameter instead of six.
#[derive(Clone, Copy)]
struct DependencyFindingSlices<'a> {
    unused_dependencies: &'a [fallow_types::output_dead_code::UnusedDependencyFinding],
    unused_dev_dependencies: &'a [fallow_types::output_dead_code::UnusedDevDependencyFinding],
    unused_optional_dependencies:
        &'a [fallow_types::output_dead_code::UnusedOptionalDependencyFinding],
    unlisted_dependencies: &'a [fallow_types::output_dead_code::UnlistedDependencyFinding],
    type_only_dependencies: &'a [fallow_types::output_dead_code::TypeOnlyDependencyFinding],
    test_only_dependencies: &'a [fallow_types::output_dead_code::TestOnlyDependencyFinding],
    dev_dependencies_in_production:
        &'a [fallow_types::output_dead_code::DevDependencyInProductionFinding],
}

/// The six framework-specific finding slices, bundled so the framework
/// dispatcher takes one parameter instead of six.
#[derive(Clone, Copy)]
struct FrameworkFindingSlices<'a> {
    unprovided_injects: &'a [fallow_types::output_dead_code::UnprovidedInjectFinding],
    unrendered_components: &'a [fallow_types::output_dead_code::UnrenderedComponentFinding],
    unused_server_actions: &'a [fallow_types::output_dead_code::UnusedServerActionFinding],
    unused_load_data_keys: &'a [fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
    route_collisions: &'a [fallow_types::output_dead_code::RouteCollisionFinding],
    dynamic_segment_name_conflicts:
        &'a [fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
}

#[derive(Clone, Copy)]
struct ComponentContractFindingSlices<'a> {
    unused_component_props: &'a [fallow_types::output_dead_code::UnusedComponentPropFinding],
    absent_component_props: &'a [fallow_types::output_dead_code::AbsentComponentPropFinding],
    constant_parameters: &'a [fallow_types::results::ConstantParameterFinding],
    unused_component_emits: &'a [fallow_types::output_dead_code::UnusedComponentEmitFinding],
    unused_component_inputs: &'a [fallow_types::output_dead_code::UnusedComponentInputFinding],
    unused_component_outputs: &'a [fallow_types::output_dead_code::UnusedComponentOutputFinding],
    unused_svelte_events: &'a [fallow_types::output_dead_code::UnusedSvelteEventFinding],
    unused_effect_layers: &'a [fallow_types::output_dead_code::UnusedEffectLayerFinding],
    unused_tagged_errors: &'a [fallow_types::output_dead_code::UnusedTaggedErrorFinding],
    unproduced_catch_tags: &'a [fallow_types::output_dead_code::UnproducedCatchTagFinding],
}

/// Build the set of audit attribution keys for all dead-code findings in
/// `results`.
///
/// Each key is a stable string that uniquely identifies one finding across
/// runs (e.g. `unused-file:src/dead.ts`, `unused-export:src/a.ts:Foo`).
/// `retain_introduced_dead_code` and `annotate_dead_code_json` use the same
/// key format to diff the current run against a base snapshot.
///
/// This destructure is deliberately exhaustive: adding a field to
/// `AnalysisResults` must fail compilation here so the author decides
/// explicitly whether the new finding type needs an audit key (add a loop)
/// or has no key representation today (bind with underscore and document why).
///
/// Sibling exhaustive sites: `retain_in_scope` in `crates/engine/src/result_scope.rs`,
/// `retain_introduced_dead_code`.
/// Non-exhaustive siblings the compiler will NOT flag (wire manually when a
/// finding type is added): `annotate_dead_code_json` (same key formats, this
/// file) and the per-collection `off` filter branches in
/// `crates/engine/src/dead_code.rs` (`apply_rule_severities`). The severity of
/// each record comes from the `RuleSeverity` table in
/// `crates/engine/src/effective_severity.rs`, whose visitors are exhaustive.
/// TypeScript mirror: `editors/vscode/scripts/codegen-contracts.mjs` derives
/// backwards-compatible aliases from `fallow schema` `ts_alias` rows.
pub fn dead_code_keys(
    results: &fallow_types::results::AnalysisResults,
    root: &Path,
) -> FxHashSet<String> {
    let mut collector = DeadCodeKeyCollector::new(root);
    collector.add_all_findings(results);
    collector.into_keys()
}

/// Build the exhaustive dead-code comparison ledger once for an audit run.
#[must_use]
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn dead_code_audit_ledger(
    results: &fallow_types::results::AnalysisResults,
    root: &Path,
    config: &ResolvedConfig,
    base: Option<&FxHashSet<String>>,
) -> DeadCodeAuditLedger {
    let mut collector = DeadCodeKeyCollector::for_comparison(root, config, base);
    collector.add_all_findings(results);
    collector.into_ledger()
}

impl DeadCodeKeyCollector<'_> {
    #[expect(
        clippy::too_many_lines,
        reason = "flat field-by-field destructure of the large AnalysisResults struct (with per-field provenance comments) plus straight-line dispatch; length tracks the field count, not branching"
    )]
    fn add_all_findings(&mut self, results: &fallow_types::results::AnalysisResults) {
        let fallow_types::results::AnalysisResults {
            shared_state: _,
            unused_files,
            unused_exports,
            unused_types,
            private_type_leaks,
            deprecated_exports_in_use,
            unused_dependencies,
            unused_dev_dependencies,
            unused_optional_dependencies,
            unused_enum_members,
            unused_class_members,
            unused_namespace_members,
            unused_protected_class_members,
            namespace_escapes,
            unused_store_members,
            unresolved_imports,
            unlisted_dependencies,
            unlisted_binaries,
            duplicate_exports,
            duplicate_export_aliases,
            type_only_dependencies,
            test_only_dependencies,
            dev_dependencies_in_production,
            circular_dependencies,
            re_export_cycles,
            package_cycles,
            boundary_violations,
            boundary_coverage_violations,
            boundary_call_violations,
            policy_violations,
            stale_suppressions,
            unused_catalog_entries,
            empty_catalog_groups,
            unresolved_catalog_references,
            unused_dependency_overrides,
            misconfigured_dependency_overrides,
            invalid_client_exports,
            mixed_client_server_barrels,
            misplaced_directives,
            unprovided_injects,
            unrendered_components,
            unused_component_props,
            absent_component_props,
            constant_parameters,
            unused_component_emits,
            unused_component_inputs,
            unused_component_outputs,
            unused_svelte_events,
            unused_effect_layers,
            unused_tagged_errors,
            unproduced_catch_tags,
            unused_server_actions,
            unused_load_data_keys,
            unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
            route_collisions,
            dynamic_segment_name_conflicts,
            // Non-finding fields: counts and metadata, not attributable to a key.
            cascade_hidden: _cascade_hidden,
            cascade: _cascade,
            suppression_count: _suppression_count,
            unused_component_props_exempted: _unused_component_props_exempted,
            active_suppressions: _active_suppressions,
            feature_flags: _feature_flags,
            // Security findings are emitted via `fallow security`, not the audit
            // dead-code gate; they have no dead-code key representation today.
            security_findings: _security_findings,
            suppressed_security_findings: _suppressed_security_findings,
            security_unresolved_edge_files: _security_unresolved_edge_files,
            security_unresolved_callee_sites: _security_unresolved_callee_sites,
            security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
            prop_drilling_chains,
            thin_wrappers,
            duplicate_prop_shapes,
            // Export usages and entry-point summary are metadata, not issue
            // collections; no key needed.
            export_usages: _export_usages,
            entry_point_summary: _entry_point_summary,
            // Render fan-in is a whole-project descriptive metric, not an issue
            // collection; no attribution key needed.
            render_fan_in: _render_fan_in,
            // Per-component React intel is a descriptive ambient-editor carrier,
            // not an issue collection; no attribution key needed.
            react_component_intel: _react_component_intel,
            semantic_reachable_files: _,
            semantic_framework_contracts: _semantic_framework_contracts,
            constant_parameter_candidates: _constant_parameter_candidates,
        } = results;

        self.add_items(AuditCollection::PropDrillingChains, prop_drilling_chains);
        self.add_items(AuditCollection::ThinWrappers, thin_wrappers);
        self.add_items(AuditCollection::DuplicatePropShapes, duplicate_prop_shapes);
        self.add_core_findings(
            unused_files,
            unused_exports,
            unused_types,
            private_type_leaks,
        );
        self.add_deprecated_exports_in_use(deprecated_exports_in_use);
        self.add_client_directive_findings(
            invalid_client_exports,
            mixed_client_server_barrels,
            misplaced_directives,
        );
        self.add_unlisted_binaries(unlisted_binaries);
        self.add_dependency_findings(&DependencyFindingSlices {
            unused_dependencies,
            unused_dev_dependencies,
            unused_optional_dependencies,
            unlisted_dependencies,
            type_only_dependencies,
            test_only_dependencies,
            dev_dependencies_in_production,
        });
        self.add_dependency_override_findings(
            unused_dependency_overrides,
            misconfigured_dependency_overrides,
        );
        self.add_member_findings(
            unused_enum_members,
            unused_class_members,
            unused_namespace_members,
            unused_protected_class_members,
            unused_store_members,
        );
        self.add_items(AuditCollection::NamespaceEscapes, namespace_escapes);
        self.add_component_contract_findings(&ComponentContractFindingSlices {
            unused_component_props,
            absent_component_props,
            constant_parameters,
            unused_component_emits,
            unused_component_inputs,
            unused_component_outputs,
            unused_svelte_events,
            unused_effect_layers,
            unused_tagged_errors,
            unproduced_catch_tags,
        });
        self.add_items(
            AuditCollection::DuplicateExportAliases,
            duplicate_export_aliases,
        );
        self.add_graph_findings(
            unresolved_imports,
            duplicate_exports,
            circular_dependencies,
            re_export_cycles,
            package_cycles,
        );
        self.add_boundary_findings(
            boundary_violations,
            boundary_coverage_violations,
            boundary_call_violations,
            policy_violations,
            stale_suppressions,
        );
        self.add_catalog_findings(
            unresolved_catalog_references,
            unused_catalog_entries,
            empty_catalog_groups,
        );
        self.add_framework_findings(&FrameworkFindingSlices {
            unprovided_injects,
            unrendered_components,
            unused_server_actions,
            unused_load_data_keys,
            route_collisions,
            dynamic_segment_name_conflicts,
        });
    }
}

struct DeadCodeKeyCollector<'a> {
    root: &'a Path,
    keys: FxHashSet<String>,
    introduced_keys: FxHashSet<String>,
    inherited_keys: FxHashSet<String>,
    records: Vec<AuditFindingRecord>,
    collection_counts: FxHashMap<&'static str, usize>,
    config: Option<&'a ResolvedConfig>,
    base: Option<&'a FxHashSet<String>>,
    #[cfg(test)]
    classifications: usize,
}

impl<'a> DeadCodeKeyCollector<'a> {
    fn new(root: &'a Path) -> Self {
        Self {
            root,
            keys: FxHashSet::default(),
            introduced_keys: FxHashSet::default(),
            inherited_keys: FxHashSet::default(),
            records: Vec::new(),
            collection_counts: FxHashMap::default(),
            config: None,
            base: None,
            #[cfg(test)]
            classifications: 0,
        }
    }

    fn for_comparison(
        root: &'a Path,
        config: &'a ResolvedConfig,
        base: Option<&'a FxHashSet<String>>,
    ) -> Self {
        Self {
            root,
            keys: FxHashSet::default(),
            introduced_keys: FxHashSet::default(),
            inherited_keys: FxHashSet::default(),
            records: Vec::new(),
            collection_counts: FxHashMap::default(),
            config: Some(config),
            base,
            #[cfg(test)]
            classifications: 0,
        }
    }

    fn into_keys(self) -> FxHashSet<String> {
        self.keys
    }

    fn into_ledger(self) -> DeadCodeAuditLedger {
        DeadCodeAuditLedger {
            records: self.records,
            keys: self.keys,
            introduced_keys: self.introduced_keys,
            inherited_keys: self.inherited_keys,
            #[cfg(test)]
            classifications: self.classifications,
        }
    }

    fn insert(&mut self, collection: AuditCollection, key: String, effective_severity: Severity) {
        let collection = collection.json_key();
        let ordinal = self.collection_counts.entry(collection).or_default();
        if self.config.is_some() {
            #[cfg(test)]
            {
                self.classifications += 1;
            }
            let introduced = self.base.is_some_and(|base| !base.contains(&key));
            if self.base.is_some() && is_counted_dead_code_finding(collection, effective_severity) {
                if introduced {
                    self.introduced_keys.insert(key.clone());
                } else {
                    self.inherited_keys.insert(key.clone());
                }
            }
            self.records.push(AuditFindingRecord {
                collection,
                ordinal: *ordinal,
                introduced,
                effective_severity,
                stable_key: key.clone(),
            });
        }
        *ordinal += 1;
        self.keys.insert(key);
    }

    /// Insert every finding of one collection under its audit key.
    fn add_items<T>(&mut self, collection: AuditCollection, items: &[T])
    where
        T: IdentifiedFinding + fallow_engine::dead_code::RuleSeverity,
    {
        let keys = collection_keys(items, self.root);
        for (item, key) in items.iter().zip(keys) {
            self.insert_rule(collection, key, item);
        }
    }

    /// Insert a finding with the severity that the shared rule table gives
    /// it. The exit code and the CI formats read the same table.
    fn insert_rule(
        &mut self,
        collection: AuditCollection,
        key: String,
        item: &impl fallow_engine::dead_code::RuleSeverity,
    ) {
        let effective = self.config.map_or(Severity::Off, |config| {
            item.rule_severity(&fallow_engine::dead_code::SeveritySource::from_config(
                config,
            ))
        });
        self.insert(collection, key, effective);
    }

    fn add_core_findings(
        &mut self,
        unused_files: &[fallow_types::output_dead_code::UnusedFileFinding],
        unused_exports: &[fallow_types::output_dead_code::UnusedExportFinding],
        unused_types: &[fallow_types::output_dead_code::UnusedTypeFinding],
        private_type_leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
    ) {
        self.add_unused_files(unused_files);
        self.add_unused_exports(unused_exports);
        self.add_unused_types(unused_types);
        self.add_private_type_leaks(private_type_leaks);
    }

    fn add_client_directive_findings(
        &mut self,
        invalid_client_exports: &[fallow_types::output_dead_code::InvalidClientExportFinding],
        mixed_client_server_barrels: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
        misplaced_directives: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
    ) {
        self.add_invalid_client_exports(invalid_client_exports);
        self.add_mixed_client_server_barrels(mixed_client_server_barrels);
        self.add_misplaced_directives(misplaced_directives);
    }

    fn add_dependency_findings(&mut self, deps: &DependencyFindingSlices<'_>) {
        let DependencyFindingSlices {
            unused_dependencies,
            unused_dev_dependencies,
            unused_optional_dependencies,
            unlisted_dependencies,
            type_only_dependencies,
            test_only_dependencies,
            dev_dependencies_in_production,
        } = *deps;
        self.add_unused_dependencies(unused_dependencies);
        self.add_unused_dev_dependencies(unused_dev_dependencies);
        self.add_unused_optional_dependencies(unused_optional_dependencies);
        self.add_unlisted_dependencies(unlisted_dependencies);
        self.add_type_only_dependencies(type_only_dependencies);
        self.add_test_only_dependencies(test_only_dependencies);
        self.add_dev_dependencies_in_production(dev_dependencies_in_production);
    }

    fn add_dependency_override_findings(
        &mut self,
        unused_dependency_overrides: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
        misconfigured_dependency_overrides: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
    ) {
        self.add_unused_dependency_overrides(unused_dependency_overrides);
        self.add_misconfigured_dependency_overrides(misconfigured_dependency_overrides);
    }

    fn add_member_findings(
        &mut self,
        unused_enum_members: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
        unused_class_members: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
        unused_namespace_members: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
        unused_protected_class_members: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
        unused_store_members: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
    ) {
        self.add_unused_enum_members(unused_enum_members);
        self.add_unused_class_members(unused_class_members);
        self.add_unused_namespace_members(unused_namespace_members);
        self.add_unused_protected_class_members(unused_protected_class_members);
        self.add_unused_store_members(unused_store_members);
    }

    fn add_component_contract_findings(&mut self, components: &ComponentContractFindingSlices<'_>) {
        let ComponentContractFindingSlices {
            unused_component_props,
            absent_component_props,
            constant_parameters,
            unused_component_emits,
            unused_component_inputs,
            unused_component_outputs,
            unused_svelte_events,
            unused_effect_layers,
            unused_tagged_errors,
            unproduced_catch_tags,
        } = *components;
        self.add_unused_component_props(unused_component_props);
        self.add_items(
            AuditCollection::AbsentComponentProps,
            absent_component_props,
        );
        self.add_items(AuditCollection::ConstantParameters, constant_parameters);
        self.add_unused_component_emits(unused_component_emits);
        self.add_unused_component_inputs(unused_component_inputs);
        self.add_unused_component_outputs(unused_component_outputs);
        self.add_unused_svelte_events(unused_svelte_events);
        self.add_unused_effect_layers(unused_effect_layers);
        self.add_unused_tagged_errors(unused_tagged_errors);
        self.add_unproduced_catch_tags(unproduced_catch_tags);
    }

    fn add_graph_findings(
        &mut self,
        unresolved_imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
        duplicate_exports: &[fallow_types::output_dead_code::DuplicateExportFinding],
        circular_dependencies: &[fallow_types::output_dead_code::CircularDependencyFinding],
        re_export_cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
        package_cycles: &[fallow_types::output_dead_code::PackageCycleFinding],
    ) {
        self.add_unresolved_imports(unresolved_imports);
        self.add_duplicate_exports(duplicate_exports);
        self.add_circular_dependencies(circular_dependencies);
        self.add_re_export_cycles(re_export_cycles);
        self.add_package_cycles(package_cycles);
    }

    fn add_boundary_findings(
        &mut self,
        boundary_violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
        boundary_coverage_violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
        boundary_call_violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
        policy_violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
        stale_suppressions: &[fallow_types::results::StaleSuppression],
    ) {
        self.add_boundary_violations(boundary_violations);
        self.add_boundary_coverage_violations(boundary_coverage_violations);
        self.add_boundary_call_violations(boundary_call_violations);
        self.add_policy_violations(policy_violations);
        self.add_stale_suppressions(stale_suppressions);
    }

    fn add_catalog_findings(
        &mut self,
        unresolved_catalog_references: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
        unused_catalog_entries: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
        empty_catalog_groups: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
    ) {
        self.add_unresolved_catalog_references(unresolved_catalog_references);
        self.add_unused_catalog_entries(unused_catalog_entries);
        self.add_empty_catalog_groups(empty_catalog_groups);
    }

    fn add_framework_findings(&mut self, framework: &FrameworkFindingSlices<'_>) {
        let FrameworkFindingSlices {
            unprovided_injects,
            unrendered_components,
            unused_server_actions,
            unused_load_data_keys,
            route_collisions,
            dynamic_segment_name_conflicts,
        } = *framework;
        self.add_unprovided_injects(unprovided_injects);
        self.add_unrendered_components(unrendered_components);
        self.add_unused_server_actions(unused_server_actions);
        self.add_unused_load_data_keys(unused_load_data_keys);
        self.add_route_collisions(route_collisions);
        self.add_dynamic_segment_name_conflicts(dynamic_segment_name_conflicts);
    }

    fn add_unused_files(&mut self, items: &[fallow_types::output_dead_code::UnusedFileFinding]) {
        self.add_items(AuditCollection::UnusedFiles, items);
    }

    fn add_unused_exports(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedExportFinding],
    ) {
        self.add_items(AuditCollection::UnusedExports, items);
    }

    fn add_unused_types(&mut self, items: &[fallow_types::output_dead_code::UnusedTypeFinding]) {
        self.add_items(AuditCollection::UnusedTypes, items);
    }

    fn add_private_type_leaks(
        &mut self,
        items: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
    ) {
        self.add_items(AuditCollection::PrivateTypeLeaks, items);
    }

    fn add_deprecated_exports_in_use(
        &mut self,
        items: &[fallow_types::output_dead_code::DeprecatedExportInUseFinding],
    ) {
        self.add_items(AuditCollection::DeprecatedExportsInUse, items);
    }

    fn add_invalid_client_exports(
        &mut self,
        items: &[fallow_types::output_dead_code::InvalidClientExportFinding],
    ) {
        self.add_items(AuditCollection::InvalidClientExports, items);
    }

    fn add_mixed_client_server_barrels(
        &mut self,
        items: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
    ) {
        self.add_items(AuditCollection::MixedClientServerBarrels, items);
    }

    fn add_misplaced_directives(
        &mut self,
        items: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
    ) {
        self.add_items(AuditCollection::MisplacedDirectives, items);
    }

    fn add_unprovided_injects(
        &mut self,
        items: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
    ) {
        self.add_items(AuditCollection::UnprovidedInjects, items);
    }

    fn add_unrendered_components(
        &mut self,
        items: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
    ) {
        self.add_items(AuditCollection::UnrenderedComponents, items);
    }

    fn add_unused_component_props(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
    ) {
        self.add_items(AuditCollection::UnusedComponentProps, items);
    }

    fn add_unused_component_emits(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
    ) {
        self.add_items(AuditCollection::UnusedComponentEmits, items);
    }

    fn add_unused_component_inputs(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedComponentInputFinding],
    ) {
        self.add_items(AuditCollection::UnusedComponentInputs, items);
    }

    fn add_unused_component_outputs(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedComponentOutputFinding],
    ) {
        self.add_items(AuditCollection::UnusedComponentOutputs, items);
    }

    fn add_unused_svelte_events(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedSvelteEventFinding],
    ) {
        self.add_items(AuditCollection::UnusedSvelteEvents, items);
    }
    fn add_unused_effect_layers(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedEffectLayerFinding],
    ) {
        self.add_items(AuditCollection::UnusedEffectLayers, items);
    }
    fn add_unused_tagged_errors(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedTaggedErrorFinding],
    ) {
        self.add_items(AuditCollection::UnusedTaggedErrors, items);
    }
    fn add_unproduced_catch_tags(
        &mut self,
        items: &[fallow_types::output_dead_code::UnproducedCatchTagFinding],
    ) {
        self.add_items(AuditCollection::UnproducedCatchTags, items);
    }

    fn add_unused_server_actions(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedServerActionFinding],
    ) {
        self.add_items(AuditCollection::UnusedServerActions, items);
    }

    fn add_unused_load_data_keys(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
    ) {
        self.add_items(AuditCollection::UnusedLoadDataKeys, items);
    }

    fn add_route_collisions(
        &mut self,
        items: &[fallow_types::output_dead_code::RouteCollisionFinding],
    ) {
        self.add_items(AuditCollection::RouteCollisions, items);
    }

    fn add_dynamic_segment_name_conflicts(
        &mut self,
        items: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
    ) {
        self.add_items(AuditCollection::DynamicSegmentNameConflicts, items);
    }

    fn add_unused_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedDependencyFinding],
    ) {
        self.add_items(AuditCollection::UnusedDependencies, items);
    }

    fn add_unused_dev_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedDevDependencyFinding],
    ) {
        self.add_items(AuditCollection::UnusedDevDependencies, items);
    }

    fn add_unused_optional_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedOptionalDependencyFinding],
    ) {
        self.add_items(AuditCollection::UnusedOptionalDependencies, items);
    }

    fn add_unused_enum_members(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
    ) {
        self.add_items(AuditCollection::UnusedEnumMembers, items);
    }

    fn add_unused_class_members(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
    ) {
        self.add_items(AuditCollection::UnusedClassMembers, items);
    }

    fn add_unused_namespace_members(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
    ) {
        self.add_items(AuditCollection::UnusedNamespaceMembers, items);
    }

    fn add_unused_protected_class_members(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
    ) {
        self.add_items(AuditCollection::UnusedProtectedClassMembers, items);
    }

    fn add_unused_store_members(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
    ) {
        self.add_items(AuditCollection::UnusedStoreMembers, items);
    }

    fn add_unresolved_imports(
        &mut self,
        items: &[fallow_types::output_dead_code::UnresolvedImportFinding],
    ) {
        self.add_items(AuditCollection::UnresolvedImports, items);
    }

    fn add_unlisted_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::UnlistedDependencyFinding],
    ) {
        self.add_items(AuditCollection::UnlistedDependencies, items);
    }

    fn add_unlisted_binaries(
        &mut self,
        items: &[fallow_types::output_dead_code::UnlistedBinaryFinding],
    ) {
        self.add_items(AuditCollection::UnlistedBinaries, items);
    }

    fn add_duplicate_exports(
        &mut self,
        items: &[fallow_types::output_dead_code::DuplicateExportFinding],
    ) {
        self.add_items(AuditCollection::DuplicateExports, items);
    }

    fn add_type_only_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::TypeOnlyDependencyFinding],
    ) {
        self.add_items(AuditCollection::TypeOnlyDependencies, items);
    }

    fn add_test_only_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::TestOnlyDependencyFinding],
    ) {
        self.add_items(AuditCollection::TestOnlyDependencies, items);
    }

    fn add_dev_dependencies_in_production(
        &mut self,
        items: &[fallow_types::output_dead_code::DevDependencyInProductionFinding],
    ) {
        self.add_items(AuditCollection::DevDependenciesInProduction, items);
    }

    fn add_circular_dependencies(
        &mut self,
        items: &[fallow_types::output_dead_code::CircularDependencyFinding],
    ) {
        self.add_items(AuditCollection::CircularDependencies, items);
    }

    fn add_re_export_cycles(
        &mut self,
        items: &[fallow_types::output_dead_code::ReExportCycleFinding],
    ) {
        self.add_items(AuditCollection::ReExportCycles, items);
    }

    fn add_package_cycles(
        &mut self,
        items: &[fallow_types::output_dead_code::PackageCycleFinding],
    ) {
        self.add_items(AuditCollection::PackageCycles, items);
    }

    fn add_boundary_violations(
        &mut self,
        items: &[fallow_types::output_dead_code::BoundaryViolationFinding],
    ) {
        self.add_items(AuditCollection::BoundaryViolations, items);
    }

    fn add_boundary_coverage_violations(
        &mut self,
        items: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
    ) {
        self.add_items(AuditCollection::BoundaryCoverageViolations, items);
    }

    fn add_boundary_call_violations(
        &mut self,
        items: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
    ) {
        self.add_items(AuditCollection::BoundaryCallViolations, items);
    }

    fn add_policy_violations(
        &mut self,
        items: &[fallow_types::output_dead_code::PolicyViolationFinding],
    ) {
        self.add_items(AuditCollection::PolicyViolations, items);
    }

    fn add_stale_suppressions(&mut self, items: &[fallow_types::results::StaleSuppression]) {
        self.add_items(AuditCollection::StaleSuppressions, items);
    }

    fn add_unresolved_catalog_references(
        &mut self,
        items: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
    ) {
        self.add_items(AuditCollection::UnresolvedCatalogReferences, items);
    }

    fn add_unused_catalog_entries(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
    ) {
        self.add_items(AuditCollection::UnusedCatalogEntries, items);
    }

    fn add_empty_catalog_groups(
        &mut self,
        items: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
    ) {
        self.add_items(AuditCollection::EmptyCatalogGroups, items);
    }

    fn add_unused_dependency_overrides(
        &mut self,
        items: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
    ) {
        self.add_items(AuditCollection::UnusedDependencyOverrides, items);
    }

    fn add_misconfigured_dependency_overrides(
        &mut self,
        items: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
    ) {
        self.add_items(AuditCollection::MisconfiguredDependencyOverrides, items);
    }
}

/// Retain only findings whose audit key was NOT present in `base` (i.e. was
/// introduced on the current branch).
///
/// When `base` is `None` (no baseline), all findings are kept.
///
/// This destructure is deliberately exhaustive: adding a field to
/// `AnalysisResults` must fail compilation here so the author decides
/// explicitly whether the new finding type needs an introduced-retain (add a
/// retain block) or has no key representation today (bind with underscore and
/// document why).
///
/// Sibling exhaustive sites: `retain_in_scope` in `crates/engine/src/result_scope.rs`,
/// `dead_code_keys`, `retain_introduced_dead_code`.
/// Non-exhaustive siblings the compiler will NOT flag (wire manually when a
/// finding type is added): `annotate_dead_code_json` (same key formats, this
/// file) and the per-collection `off` filter branches in
/// `crates/engine/src/dead_code.rs` (`apply_rule_severities`). The severity of
/// each record comes from the `RuleSeverity` table in
/// `crates/engine/src/effective_severity.rs`, whose visitors are exhaustive.
/// TypeScript mirror: `editors/vscode/scripts/codegen-contracts.mjs` derives
/// backwards-compatible aliases from `fallow schema` `ts_alias` rows.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn retain_introduced_dead_code(
    results: &mut fallow_types::results::AnalysisResults,
    root: &Path,
    base: Option<&FxHashSet<String>>,
) {
    let Some(base) = base else {
        return;
    };

    // Compute the introduced set before taking any mutable borrows. Note the
    // order differs from the pre-destructure code, which narrowed
    // unused_files/exports/types first and computed keys from the narrowed
    // results. Computing from the un-narrowed results is equivalent: those
    // retains keep exactly the items whose key is NOT in `base`, and the
    // `!base.contains(key)` filter below removes the same base-member keys
    // from the full key set, so `introduced` is identical either way.
    classify_introduced_dead_code_fields(results);
    macro_rules! retain {
        ($($field:ident),* $(,)?) => {
            $(retain_introduced(&mut results.$field, root, base);)*
        };
    }
    retain!(
        prop_drilling_chains,
        thin_wrappers,
        duplicate_prop_shapes,
        unused_files,
        unused_exports,
        unused_types,
        private_type_leaks,
        deprecated_exports_in_use,
        unused_enum_members,
        unused_class_members,
        unused_namespace_members,
        unused_protected_class_members,
        namespace_escapes,
        unused_store_members,
        unresolved_imports,
        unused_dependencies,
        unused_dev_dependencies,
        unused_optional_dependencies,
        unlisted_dependencies,
        unlisted_binaries,
        duplicate_exports,
        duplicate_export_aliases,
        type_only_dependencies,
        test_only_dependencies,
        circular_dependencies,
        re_export_cycles,
        package_cycles,
        boundary_violations,
        boundary_coverage_violations,
        boundary_call_violations,
        policy_violations,
        stale_suppressions,
        unresolved_catalog_references,
        unused_catalog_entries,
        empty_catalog_groups,
        unused_dependency_overrides,
        misconfigured_dependency_overrides,
        invalid_client_exports,
        mixed_client_server_barrels,
        misplaced_directives,
        unprovided_injects,
        unrendered_components,
        unused_component_props,
        absent_component_props,
        constant_parameters,
        unused_component_emits,
        unused_component_inputs,
        unused_component_outputs,
        unused_svelte_events,
        unused_effect_layers,
        unused_tagged_errors,
        unproduced_catch_tags,
        unused_server_actions,
        unused_load_data_keys,
        route_collisions,
        dynamic_segment_name_conflicts,
    );
}

/// Keep the findings of one collection whose audit key is absent from `base`.
fn retain_introduced<T: IdentifiedFinding>(
    items: &mut Vec<T>,
    root: &Path,
    base: &FxHashSet<String>,
) {
    let mut keys = collection_keys(items, root).into_iter();
    items.retain(|_| keys.next().is_some_and(|key| !base.contains(&key)));
}

/// The `introduced` flag of each finding in one collection, in order.
fn introduced_flags<T: IdentifiedFinding>(
    items: &[T],
    root: &Path,
    base: &FxHashSet<String>,
) -> Vec<bool> {
    collection_keys(items, root)
        .iter()
        .map(|key| !base.contains(key))
        .collect()
}

fn issue_was_introduced(key: &str, base: &FxHashSet<String>) -> bool {
    !base.contains(key)
}

fn annotate_issue_array<I>(json: &mut serde_json::Value, key: &str, introduced: I)
where
    I: IntoIterator<Item = bool>,
{
    let Some(items) = json.get_mut(key).and_then(serde_json::Value::as_array_mut) else {
        return;
    };
    for (item, introduced) in items.iter_mut().zip(introduced) {
        if let serde_json::Value::Object(map) = item {
            map.insert("introduced".to_string(), serde_json::json!(introduced));
        }
    }
}

/// Insert `"introduced": bool` into every dead-code finding object in the
/// serialized JSON by re-deriving each key and testing membership against
/// the base snapshot. JSON arrays must be in the same order as the typed
/// `results` collections they were serialized from.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn annotate_dead_code_json(
    json: &mut serde_json::Value,
    results: &fallow_types::results::AnalysisResults,
    root: &Path,
    base: &FxHashSet<String>,
) {
    macro_rules! annotate {
        ($($field:ident),* $(,)?) => {
            $(annotate_issue_array(
                json,
                stringify!($field),
                introduced_flags(&results.$field, root, base),
            );)*
        };
    }
    annotate!(
        prop_drilling_chains,
        thin_wrappers,
        duplicate_prop_shapes,
        unused_files,
        unused_exports,
        unused_types,
        private_type_leaks,
        deprecated_exports_in_use,
        unused_dependencies,
        unused_dev_dependencies,
        unused_optional_dependencies,
        type_only_dependencies,
        test_only_dependencies,
        unlisted_dependencies,
        unlisted_binaries,
        unused_enum_members,
        unused_class_members,
        unused_namespace_members,
        unused_protected_class_members,
        namespace_escapes,
        unused_store_members,
        unresolved_imports,
        duplicate_exports,
        duplicate_export_aliases,
        circular_dependencies,
        re_export_cycles,
        package_cycles,
        boundary_violations,
        boundary_coverage_violations,
        boundary_call_violations,
        policy_violations,
        stale_suppressions,
        unresolved_catalog_references,
        unused_catalog_entries,
        empty_catalog_groups,
        unused_dependency_overrides,
        misconfigured_dependency_overrides,
        invalid_client_exports,
        mixed_client_server_barrels,
        misplaced_directives,
        unprovided_injects,
        unrendered_components,
        unused_component_props,
        absent_component_props,
        constant_parameters,
        unused_component_emits,
        unused_component_inputs,
        unused_component_outputs,
        unused_svelte_events,
        unused_effect_layers,
        unused_tagged_errors,
        unproduced_catch_tags,
        unused_server_actions,
        route_collisions,
        dynamic_segment_name_conflicts,
    );
}

/// Annotate the sole legacy dead-code collection without a typed
/// `introduced` field. Every wrapper-backed collection is annotated from the
/// persisted [`AuditComparison`] instead.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn annotate_stale_suppressions_json(
    json: &mut serde_json::Value,
    results: &fallow_types::results::AnalysisResults,
    root: &Path,
    base: &FxHashSet<String>,
) {
    annotate_issue_array(
        json,
        "stale_suppressions",
        stale_suppression_introduced_flags(results, root, base),
    );
}

/// The audit flag of each stale suppression, in report order. A flag is
/// `true` when the base snapshot does not hold the key of the suppression.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
#[must_use]
pub fn stale_suppression_introduced_flags(
    results: &fallow_types::results::AnalysisResults,
    root: &Path,
    base: &FxHashSet<String>,
) -> Vec<bool> {
    introduced_flags(&results.stale_suppressions, root, base)
}

const STALE_SUPPRESSION_CHECK_NAMES: [&str; 2] = [
    "fallow/stale-suppression",
    "fallow/missing-suppression-reason",
];

/// Set the audit attribution on the stale-suppression issues of the
/// dead-code CodeClimate issues.
///
/// `introduced` holds one audit flag per stale suppression, in the order of
/// `AnalysisResults::stale_suppressions`. The builder emits one issue per
/// stale suppression in that order, so the flags match the issues by
/// position. The inline review comment then states if the change introduced
/// the stale suppression.
pub fn set_stale_suppression_audit_attribution(
    issues: &mut [fallow_output::CodeClimateIssue],
    introduced: impl IntoIterator<Item = bool>,
) {
    let stale_issues = issues
        .iter_mut()
        .filter(|issue| STALE_SUPPRESSION_CHECK_NAMES.contains(&issue.check_name.as_str()));
    for (issue, introduced) in stale_issues.zip(introduced) {
        issue.audit = Some(crate::dead_code_codeclimate::audit_review_context(
            introduced,
        ));
    }
}

/// Insert `"introduced": bool` into each `findings` and `styling_findings`
/// object in serialized health JSON, matching entries to the typed report by
/// array position.
///
/// A complexity finding keeps the typed `introduced` flag that the audit
/// comparison set, because that flag compares metric values. Only a finding
/// without the typed flag falls back to identity-key membership in `base`.
/// A styling finding also keeps its typed flag, because the audit can use the
/// run's diff to tell equal findings apart.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn annotate_health_json(
    json: &mut serde_json::Value,
    report: &fallow_output::HealthReport,
    root: &Path,
    base: &FxHashSet<String>,
) {
    if let Some(items) = json
        .get_mut("findings")
        .and_then(serde_json::Value::as_array_mut)
    {
        for (item, finding) in items.iter_mut().zip(&report.findings) {
            if let serde_json::Value::Object(map) = item {
                map.insert(
                    "introduced".to_string(),
                    serde_json::json!(finding.introduced.unwrap_or_else(|| {
                        issue_was_introduced(&health_finding_key(finding, root), base)
                    })),
                );
            }
        }
    }
    styling::annotate_styling_json(json, &report.styling_findings, root, base);
}

/// Insert `"introduced": bool` into each `clone_groups` object in serialized
/// duplication JSON, matching groups to the typed report by array position.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across audit attribution keys"
)]
pub fn annotate_dupes_json(
    json: &mut serde_json::Value,
    report: &fallow_types::duplicates::DuplicationReport,
    root: &Path,
    base: &FxHashSet<String>,
) {
    let Some(items) = json
        .get_mut("clone_groups")
        .and_then(serde_json::Value::as_array_mut)
    else {
        return;
    };
    for (item, group) in items.iter_mut().zip(&report.clone_groups) {
        if let serde_json::Value::Object(map) = item {
            map.insert(
                "introduced".to_string(),
                serde_json::json!(issue_was_introduced(&dupe_group_key(group, root), base)),
            );
        }
    }
}

/// Attach precomputed introduced membership to an audit JSON array.
pub fn annotate_domain_json(
    json: &mut serde_json::Value,
    collection: &str,
    introduced: impl IntoIterator<Item = bool>,
) {
    annotate_issue_array(json, collection, introduced);
}

/// Attach a `demotion_reason` to demoted entries of an audit JSON array,
/// matching entries to demoted membership by array position. Non-demoted
/// entries are left untouched so output without demotions stays byte-identical
/// (issue #2220).
pub fn annotate_domain_demotions_json(
    json: &mut serde_json::Value,
    collection: &str,
    demoted: impl IntoIterator<Item = bool>,
    reason: crate::CloneDemotionReason,
) {
    let Some(items) = json
        .get_mut(collection)
        .and_then(serde_json::Value::as_array_mut)
    else {
        return;
    };
    for (item, demoted) in items.iter_mut().zip(demoted) {
        if demoted && let serde_json::Value::Object(map) = item {
            map.insert("demotion_reason".to_string(), serde_json::json!(reason));
        }
    }
}

/// Attribution key set for every complexity finding in a health report.
pub fn health_keys(report: &fallow_output::HealthReport, root: &Path) -> FxHashSet<String> {
    report
        .findings
        .iter()
        .map(|finding| health_finding_key(finding, root))
        .collect()
}

/// Identity key for one complexity finding: `complexity:<path>:<function>`.
///
/// Line numbers are excluded, so a finding survives unrelated edits above it.
/// The exceeded category is excluded, so a category change keeps the match.
/// The new-only gate compares the metric values of matched findings, see
/// [`classify_complexity_findings`].
pub fn health_finding_key(finding: &fallow_output::ComplexityViolation, root: &Path) -> String {
    format!(
        "complexity:{}:{}",
        relative_key_path(Path::new(&finding.path), root),
        finding.name,
    )
}

/// Attribution key set for every clone group in a duplication report.
pub fn dupes_keys(
    report: &fallow_types::duplicates::DuplicationReport,
    root: &Path,
) -> FxHashSet<String> {
    report
        .clone_groups
        .iter()
        .map(|group| dupe_group_key(group, root))
        .collect()
}

/// Attribution key for one clone group:
/// `dupe:<sorted files joined by |>:<tokens>:<lines>:<fragment hash>`.
/// The fragment hash keeps distinct groups spanning the same files apart;
/// line positions are excluded so a group survives shifts within its files.
/// The fragment hash leaves out `\r`, so the line endings do not change the key.
/// It does not depend on the order of the instances, so a group keeps its
/// hash when the change moves its instances to other files.
pub fn dupe_group_key(group: &fallow_types::duplicates::CloneGroup, root: &Path) -> String {
    let mut files: Vec<String> = group
        .instances
        .iter()
        .map(|instance| relative_key_path(&instance.file, root))
        .collect();
    files.sort();
    files.dedup();
    let mut fragment_hashes: Vec<u64> = group
        .instances
        .iter()
        .map(|instance| {
            let mut hasher = DefaultHasher::new();
            if instance.fragment.contains('\r') {
                instance.fragment.replace('\r', "").hash(&mut hasher);
            } else {
                instance.fragment.hash(&mut hasher);
            }
            hasher.finish()
        })
        .collect();
    fragment_hashes.sort_unstable();
    let mut hasher = DefaultHasher::new();
    for fragment_hash in fragment_hashes {
        fragment_hash.hash(&mut hasher);
    }
    format!(
        "dupe:{}:{}:{}:{:x}",
        files.join("|"),
        group.token_count,
        group.line_count,
        hasher.finish()
    )
}

#[path = "audit_keys_introduced.rs"]
mod audit_keys_introduced;
use audit_keys_introduced::classify_introduced_dead_code_fields;

#[cfg(test)]
#[path = "audit_keys_tests.rs"]
mod tests;