fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
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
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::BTreeMap;
use std::path::Path;

use fallow_types::extract::is_anonymous_function_name;
use fallow_types::identity::{IdentifiedFinding, IdentityPaths};

use crate::duplicates::DuplicationReport;

/// Strip the project root from a path to produce a portable relative key.
///
/// Both `path` and `root` must be in the same form (both canonicalized or both
/// not) for `strip_prefix` to succeed. The analysis pipeline keeps all paths
/// non-canonicalized, so this invariant holds in practice.
fn relative_path(path: &Path, root: &Path) -> String {
    match path.strip_prefix(root) {
        Ok(relative) => relative.to_string_lossy().replace('\\', "/"),
        Err(_) => {
            tracing::debug!(
                path = %path.display(),
                root = %root.display(),
                "baseline key: path is not under project root, using absolute path as key"
            );
            path.to_string_lossy().replace('\\', "/")
        }
    }
}

fn package_json_dependency_key(package_name: &str, path: &Path, root: &Path) -> String {
    format!("{}:{package_name}", relative_path(path, root))
}

fn baseline_contains_dependency(
    baseline_keys: &FxHashSet<&str>,
    package_name: &str,
    path_key: &str,
) -> bool {
    baseline_keys.contains(path_key) || baseline_keys.contains(package_name)
}

fn retain_new_by_keys<T>(
    items: &mut Vec<T>,
    baseline_keys: &[String],
    root: &Path,
    key_builder: fn(&[T], &Path) -> Vec<String>,
) {
    let baseline_keys: FxHashSet<&str> = baseline_keys.iter().map(String::as_str).collect();
    let item_keys = key_builder(items, root);
    let mut key_iter = item_keys.into_iter();
    items.retain(|_| match key_iter.next() {
        Some(key) => !baseline_keys.contains(key.as_str()),
        None => true,
    });
}

/// Call `$callback!` with every finding field of a dead-code baseline. The
/// save path and the canonical filter read this one list, so a field cannot
/// be saved without being matched.
macro_rules! with_baseline_fields {
    ($callback:ident) => {
        $callback!(
            unused_files,
            unused_exports,
            unused_types,
            private_type_leaks,
            deprecated_exports_in_use,
            unused_dependencies,
            unused_dev_dependencies,
            circular_dependencies,
            re_export_cycles,
            package_cycles,
            unused_optional_dependencies,
            unused_enum_members,
            unused_class_members,
            unused_store_members,
            unused_namespace_members,
            unused_protected_class_members,
            namespace_escapes,
            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,
            unresolved_imports,
            unlisted_dependencies,
            unlisted_binaries,
            duplicate_exports,
            duplicate_export_aliases,
            type_only_dependencies,
            test_only_dependencies,
            dev_dependencies_in_production,
            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,
            route_collisions,
            dynamic_segment_name_conflicts,
            prop_drilling_chains,
            thin_wrappers,
            duplicate_prop_shapes,
        )
    };
}

mod finding_counts;
mod install_state;

use finding_counts::{baseline_finding_count, cascade_hidden_matches};
mod caller_review_keys;
mod health_categories;
use health_categories::{
    FileLengthCounting, HEALTH_FINDING_DIMENSIONS, HealthFindingCategory, health_finding_counts,
    severity_counts_for_dimension, severity_index,
};
mod health_match;
#[cfg(test)]
pub(crate) use health_match::filter_new_health_findings;
use health_match::{HealthMatch, match_health_baseline, match_severity_slots};
mod identity_counts;

#[cfg(test)]
mod legacy_key_builders;
use caller_review_keys::{absent_component_prop_baseline_keys, constant_parameter_baseline_keys};
mod prune;
mod saved_scope;
mod stale_advice;
#[cfg(test)]
use legacy_key_builders::{
    baseline_catalog_keys, baseline_dependency_keys, baseline_file_export_keys,
    baseline_graph_keys, baseline_member_import_keys,
};

pub use install_state::install_state_diagnostic;
#[cfg(test)]
pub(crate) use install_state::saved_node_modules_state;
pub use prune::{
    BaselinePrune, BaselinePruneRefusal, PrunedEntry, prune_dead_code_baseline,
    prune_dupes_baseline, prune_health_baseline,
};
pub use saved_scope::{saved_finding_categories, saved_scope_reasons};

#[path = "legacy_key_filter.rs"]
mod legacy_key_filter;
use legacy_key_filter::filter_new_issues_by_legacy_keys;

/// The sorted canonical keys of `items`, one for each occurrence.
fn canonical_keys<T: IdentifiedFinding>(items: &[T], paths: &IdentityPaths<'_>) -> Vec<String> {
    let mut keys: Vec<String> = items.iter().map(|item| item.canonical_key(paths)).collect();
    keys.sort_unstable();
    keys
}

/// Remove the findings that a saved occurrence covers. Each saved key hides
/// one current finding with the same canonical key, in input order.
fn retain_unsaved<T: IdentifiedFinding>(
    items: &mut Vec<T>,
    saved: &[String],
    paths: &IdentityPaths<'_>,
) {
    if saved.is_empty() {
        return;
    }
    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
    for key in saved {
        *remaining.entry(key.as_str()).or_default() += 1;
    }
    items.retain(|item| !consume_baseline_key(&mut remaining, &item.canonical_key(paths)));
}

/// Stale fraction (in percent) at which a partial-staleness warning fires.
///
/// A little drift is the normal state of a living baseline, so warning on any
/// stale entry would train people to ignore the note. A quarter of the
/// baseline matching nothing means the gate protects meaningfully less than
/// what was saved. Shared by the dead-code and health baselines so the two
/// warnings cannot drift apart.
const STALE_WARN_PERCENT: usize = 25;

/// True when `stale_entries` out of `baseline_entries` is a large enough share
/// to be worth warning about.
///
/// The threshold alone; [`BaselineStaleness::warning`] owns the surrounding
/// guards and is what commands call.
#[must_use]
const fn stale_share_warrants_warning(baseline_entries: usize, stale_entries: usize) -> bool {
    stale_entries > 0 && stale_entries * 100 >= baseline_entries * STALE_WARN_PERCENT
}

/// One run's view of a loaded baseline: everything needed to decide whether the
/// baseline still describes the project.
///
/// Every command that accepts `--baseline` builds one of these and asks it the
/// same two questions, so `dead-code`, `dupes` and `health` cannot answer
/// "is this baseline stale enough to say something" three different ways.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BaselineStaleness {
    /// Entries saved in the baseline file.
    pub entries: usize,
    /// Baseline entries that matched something in this run.
    pub matched: usize,
    /// Findings this run produced before the baseline filtered them. Zero means
    /// there was nothing to compare, either because the project is clean or the
    /// scope was empty, so staleness cannot be judged.
    pub current_findings: usize,
    /// True when this run cannot judge the loaded baseline, because its scope
    /// differs from the scope of the file. The baseline then matches less for
    /// reasons that are not rot.
    pub change_scoped: bool,
}

/// Which advisory warning a loaded baseline earns, if any.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BaselineStalenessWarning {
    /// Say nothing: the baseline is fresh enough, or this run cannot judge it.
    None,
    /// Nothing in the baseline matched, and there were findings to match.
    ZeroOverlap,
    /// A large enough share of the baseline matched nothing.
    Partial,
}

impl BaselineStaleness {
    /// Entries that matched no current finding on this run.
    #[must_use]
    pub const fn stale_entries(&self) -> usize {
        self.entries.saturating_sub(self.matched)
    }

    /// The advisory warning this run prints on stderr by default.
    ///
    /// Silent for a run narrowed to part of the project, because such a run
    /// legitimately sees only a slice of a whole-project baseline and re-saving
    /// from it would drop every entry the run never looked at. Silent as well
    /// when the run produced no findings: a cleaned project and a rotted
    /// baseline look identical from here, and the re-save advice is wrong when
    /// the right move is deleting the file.
    #[must_use]
    pub const fn warning(&self) -> BaselineStalenessWarning {
        if self.change_scoped || self.entries == 0 || self.current_findings == 0 {
            return BaselineStalenessWarning::None;
        }
        if self.matched == 0 {
            return BaselineStalenessWarning::ZeroOverlap;
        }
        if stale_share_warrants_warning(self.entries, self.stale_entries()) {
            return BaselineStalenessWarning::Partial;
        }
        BaselineStalenessWarning::None
    }

    /// Whether the opt-in `--fail-on-stale-baseline` gate fires.
    ///
    /// Deliberately stricter than [`Self::warning`]: any stale entry counts.
    /// The quarter threshold exists to keep an unasked-for line from training
    /// people to ignore it, and the empty-run silence exists because an
    /// advisory cannot tell rot from success; a repository that passes the flag
    /// has asked for both. Change-scope stays the one shared suppression,
    /// because a narrowed run still cannot judge a whole-project baseline.
    #[must_use]
    pub const fn trips_gate(&self) -> bool {
        stale_baseline_gate_trips(self.entries, self.matched, self.change_scoped)
    }
    /// This run's machine-readable view of the baseline, for the JSON envelope.
    ///
    /// Every member is derived here rather than in a consumer, so the advisory
    /// threshold and the gate rule have exactly one implementation. Only
    /// `health` can follow a file move; the commands that match entries by
    /// fingerprint pass `0`.
    ///
    /// `scope_reasons` and `unrecognised_format` come from the caller because
    /// only the command knows which channels it read and which format it read
    /// the file as; this struct carries the counts the analysis needs and
    /// nothing more. `change_scoped` and `scope_reasons` must agree, which is
    /// why every caller derives the boolean from the same reason set it passes
    /// here.
    ///
    /// `unrecognised_format` widens `gate_trips` here, at the single site that
    /// builds it, so the opt-in gate, the exit code, every CI surface that reads
    /// the boolean and the MCP sentences move together: a file this command
    /// cannot read as its own suppresses nothing, which no count can express.
    /// Unlike the count rule it is not suppressed by `change_scoped`, because
    /// telling a foreign file from this command's own needs no project-wide run.
    #[must_use]
    pub fn to_envelope(
        &self,
        moved_entries: usize,
        scope_reasons: fallow_output::BaselineScopeReasons,
        unrecognised_format: bool,
    ) -> fallow_output::BaselineStaleness {
        debug_assert_eq!(
            self.change_scoped,
            !scope_reasons.is_empty(),
            "change_scoped and scope_reasons must be derived from the same predicate"
        );
        let warning = self.warning();
        fallow_output::BaselineStaleness {
            baseline_entries: self.entries,
            matched_entries: self.matched,
            stale_entries: self.stale_entries(),
            current_findings: self.current_findings,
            remaining_findings: None,
            change_scoped: self.change_scoped,
            stale: warning != BaselineStalenessWarning::None,
            warning: match warning {
                BaselineStalenessWarning::None => fallow_output::BaselineStalenessAdvisory::None,
                BaselineStalenessWarning::ZeroOverlap => {
                    fallow_output::BaselineStalenessAdvisory::ZeroOverlap
                }
                BaselineStalenessWarning::Partial => {
                    fallow_output::BaselineStalenessAdvisory::Partial
                }
            },
            gate_trips: self.trips_gate() || unrecognised_format,
            moved_entries,
            unrecognised_format,
            saved_by: None,
            format: None,
            scope_reasons,
        }
    }
}

/// [`BaselineStaleness::trips_gate`] over the three counts it reads, for
/// callers that carry the numbers in their own output type.
#[must_use]
pub const fn stale_baseline_gate_trips(
    entries: usize,
    matched: usize,
    change_scoped: bool,
) -> bool {
    !change_scoped && entries > 0 && matched < entries
}

/// Whether a baseline file is written in the format it was loaded as.
///
/// The duplication and health formats give every field a serde default, so a
/// baseline another command saved, and an object with nothing in it, both
/// deserialize into zero entries and are indistinguishable from this command's
/// own baseline saved from a project that had nothing to record. Asking which
/// keys the file actually carries separates them: a file that declares at
/// least one key of the format it was read as is that command's baseline,
/// however empty it is.
///
/// False for anything that is not a JSON object, including a file this crate
/// would refuse to deserialize; those paths report their own error before a
/// caller gets here.
#[must_use]
pub fn declares_baseline_format(json: &str, declared_keys: &[&str]) -> bool {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
        return false;
    };
    value_declares_baseline_format(&value, declared_keys)
}

/// [`declares_baseline_format`] for a caller that has already parsed the file.
fn value_declares_baseline_format(value: &serde_json::Value, declared_keys: &[&str]) -> bool {
    let Some(object) = value.as_object() else {
        return false;
    };
    declared_keys.iter().any(|key| object.contains_key(*key))
}

/// Which command saved a baseline file.
///
/// Written as the top-level `kind` of every baseline this version saves, spelled
/// exactly as the envelope root kinds, so a file states which command can read
/// it instead of leaving three formats to be told apart by the keys they happen
/// to carry. A file saved before the member exists carries no `kind`, which
/// [`classify_baseline_file`] falls back from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BaselineKind {
    /// Saved by `fallow dead-code` (or `fallow check`), and by
    /// `fallow architecture`.
    ///
    /// The kind names the baseline format, not the command: `fallow
    /// architecture` runs the dead-code analysis, so it writes and reads this
    /// format although its JSON envelope has `kind: "architecture"`.
    DeadCode,
    /// Saved by `fallow dupes`.
    Dupes,
    /// Saved by `fallow health`.
    Health,
}

impl BaselineKind {
    /// The token this kind is written as, which is also the command to run.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DeadCode => "dead-code",
            Self::Dupes => "dupes",
            Self::Health => "health",
        }
    }

    /// The kind a `kind` token names, or `None` for a token this version does
    /// not know (for example one that only a newer fallow writes).
    #[must_use]
    fn from_token(token: &str) -> Option<Self> {
        [Self::DeadCode, Self::Dupes, Self::Health]
            .into_iter()
            .find(|kind| kind.as_str() == token)
    }

    /// The keys that identify this format in a file carrying no `kind`.
    #[must_use]
    const fn declared_keys(self) -> &'static [&'static str] {
        match self {
            Self::DeadCode => BaselineData::REQUIRED_KEYS,
            Self::Dupes => DuplicationBaselineData::DECLARED_KEYS,
            Self::Health => HealthBaselineData::DECLARED_KEYS,
        }
    }
}

/// What a saved baseline file is, read as one command's format.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BaselineFileKind {
    /// This command's own baseline: it names this command in `kind`, or it
    /// carries no `kind` and at least one key of this command's format.
    Own,
    /// A baseline another command saved, carrying the `kind` as written so a
    /// message can quote it, including a token only a newer fallow writes.
    Foreign(String),
    /// No `kind` and no key of this command's format: a baseline another
    /// command saved before `kind` existed, or an object with nothing of this
    /// command's in it.
    Unrecognised,
    /// Not a JSON object, so it says nothing about which command wrote it and
    /// the caller's own parse error is the honest report.
    NotAnObject,
}

impl BaselineFileKind {
    /// The known command that saved a file another command wrote.
    ///
    /// `None` for this command's own file, for a file that names no writer, and
    /// for a `kind` token this version does not know. The CLI computes this one
    /// time per loaded baseline and uses it for the stderr note and for
    /// `baseline_staleness.saved_by`, so the two cannot disagree.
    #[must_use]
    pub fn saved_by(&self) -> Option<BaselineKind> {
        match self {
            Self::Foreign(token) => BaselineKind::from_token(token),
            Self::Own | Self::Unrecognised | Self::NotAnObject => None,
        }
    }
}

/// Why a `--save-baseline` must not overwrite the file at `save_path`, or `None`
/// when the save may proceed.
///
/// A save serializes a fresh struct over the whole file, so one command's save
/// aimed at another command's baseline destroys it with nothing left to recover
/// from. Read from the destination's own `kind`: a file saved before that member
/// existed carries nothing to identify it and is still overwritten silently, and
/// an unreadable or absent destination is not a guard condition, exactly as the
/// health identity-overwrite guard treats one.
#[must_use]
pub fn refuse_baseline_kind_overwrite(save_path: &Path, saving: BaselineKind) -> Option<String> {
    let existing = std::fs::read_to_string(save_path).ok()?;
    let BaselineFileKind::Foreign(found) = classify_baseline_file(&existing, saving) else {
        return None;
    };
    Some(format!(
        "refusing to overwrite the baseline at {}: it was saved by `fallow {found}` and this is a \
         `fallow {}` save, which would destroy it. Save each command's baseline to its own path.",
        save_path.display(),
        saving.as_str(),
    ))
}

/// Which command a saved baseline file belongs to, read as `expected`'s format.
///
/// `kind` decides whenever the file carries one, which is every baseline saved
/// from this version onward. A file without one predates the member, so the keys
/// it carries decide instead, exactly as [`declares_baseline_format`] documents.
///
/// Reads the raw file rather than a deserialized struct, because the one format
/// with required fields (`dead-code`) has to answer this before its own parse
/// error hides the answer.
#[must_use]
pub fn classify_baseline_file(json: &str, expected: BaselineKind) -> BaselineFileKind {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
        return BaselineFileKind::NotAnObject;
    };
    classify_baseline_value(&value, expected)
}

/// [`classify_baseline_file`] for a caller that parses the file itself.
///
/// The `dead-code` read needs both this answer and the deserialized struct, and
/// its format is the one with required fields, so it parses once into a value and
/// asks here rather than paying for a second parse of the same bytes.
#[must_use]
fn classify_baseline_value(value: &serde_json::Value, expected: BaselineKind) -> BaselineFileKind {
    let Some(object) = value.as_object() else {
        return BaselineFileKind::NotAnObject;
    };
    match object.get("kind").and_then(serde_json::Value::as_str) {
        Some(token) if token == expected.as_str() => BaselineFileKind::Own,
        Some(token) => BaselineFileKind::Foreign(token.to_owned()),
        // A `kind` that is not a string is no statement about the writer, so the
        // keys answer as they do for a file that carries no `kind` at all.
        None => {
            if value_declares_baseline_format(value, expected.declared_keys()) {
                BaselineFileKind::Own
            } else {
                BaselineFileKind::Unrecognised
            }
        }
    }
}

/// The key scheme of a dead-code baseline that stores canonical keys.
///
/// A baseline with `"identity": "dc1"` stores, for each finding, the canonical
/// key from [`fallow_types::identity`] (`<rule>:<path>:<name>...`, never a
/// line), once for each occurrence. N saved occurrences of a key hide at most
/// N current findings with that key. A baseline without `identity` is a legacy
/// baseline: each entry keeps its old form (some old forms hold a line) and
/// hides every current finding with that exact key.
pub const BASELINE_KEY_SCHEME: &str = fallow_types::identity::DEAD_CODE_ID_SCHEME;

/// Baseline data for comparison.
///
/// The per-field notes below give the legacy key forms. A baseline with an
/// `identity` stores canonical keys in every field; see
/// [`BASELINE_KEY_SCHEME`].
#[derive(serde::Serialize, serde::Deserialize)]
pub struct BaselineData {
    /// The command that saved this file, written on every save and never read
    /// back through this struct: [`classify_baseline_file`] reads it off the raw
    /// file, before the required fields below can reject another command's
    /// baseline. `skip_deserializing` keeps a `kind` only a newer fallow writes
    /// from turning a loadable file into a parse error.
    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
    kind: Option<BaselineKind>,
    /// Analysis identity plus install state; legacy files read as syntactic,
    /// never silently compared with type-aware output.
    #[serde(default)]
    analysis_identity: install_state::BaselineAnalysisIdentity,
    /// The key scheme of the entries: [`BASELINE_KEY_SCHEME`] for canonical,
    /// count-matched keys, absent for a legacy baseline.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    identity: Option<String>,
    /// The `scope_reasons` of the run that saved this file, absent for a
    /// whole-project save. A listed reason means the file holds only the
    /// findings in that scope, so a wider run that loads it can report old
    /// findings as new. Read back with [`saved_scope_reasons`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    scope_reasons: Vec<String>,
    unused_files: Vec<String>,
    unused_exports: Vec<String>,
    unused_types: Vec<String>,
    #[serde(default)]
    private_type_leaks: Vec<String>,
    /// Deprecated exports still in use, keyed by `path:export_name`.
    #[serde(default)]
    deprecated_exports_in_use: Vec<String>,
    /// Unused dependencies, keyed by `package.json:package_name`. Legacy
    /// bare `package_name` keys are still matched for back-compat with
    /// baselines saved by older fallow versions.
    unused_dependencies: Vec<String>,
    /// Unused dev dependencies, keyed by `package.json:package_name`. Legacy
    /// bare `package_name` keys are still matched for back-compat with
    /// baselines saved by older fallow versions.
    unused_dev_dependencies: Vec<String>,
    /// Circular dependency chains, keyed by sorted file paths joined with `->`.
    #[serde(default)]
    circular_dependencies: Vec<String>,
    /// Re-export cycles, keyed by `kind:sorted_file_paths_joined_with_<->`
    /// (where `kind` is `multi-node` or `self-loop`). The kind prefix keeps
    /// self-loops from keyspace-colliding with future single-file multi-node
    /// shapes.
    #[serde(default)]
    re_export_cycles: Vec<String>,
    /// Package cycles, keyed by package names in canonical cycle order joined
    /// with `->`.
    #[serde(default)]
    package_cycles: Vec<String>,
    /// Unused optional dependencies, keyed by `package.json:package_name`.
    /// Legacy bare `package_name` keys are still matched for back-compat
    /// with baselines saved by older fallow versions.
    #[serde(default)]
    unused_optional_dependencies: Vec<String>,
    /// Unused enum members, keyed by `file:parent.member`.
    #[serde(default)]
    unused_enum_members: Vec<String>,
    /// Unused class members, keyed by `file:parent.member`.
    #[serde(default)]
    unused_class_members: Vec<String>,
    /// Unused store members, keyed by `file:parent.member`.
    #[serde(default)]
    unused_store_members: Vec<String>,
    /// Unused namespace members, keyed by `file:parent.member`.
    #[serde(default)]
    unused_namespace_members: Vec<String>,
    /// Unused protected class members, keyed by `file:parent.member`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    unused_protected_class_members: Vec<String>,
    /// Namespace escapes, keyed by the canonical finding identity.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    namespace_escapes: Vec<String>,
    /// Unprovided injects, keyed by `file:key_name`.
    #[serde(default)]
    unprovided_injects: Vec<String>,
    /// Unrendered components, keyed by `file:component_name`.
    #[serde(default)]
    unrendered_components: Vec<String>,
    /// Unused component props, keyed by `file:prop_name`.
    #[serde(default)]
    unused_component_props: Vec<String>,
    #[serde(default)]
    absent_component_props: Vec<String>,
    /// Constant parameters, keyed by `file:function:parameter`.
    #[serde(default)]
    constant_parameters: Vec<String>,
    /// Unused component emits, keyed by `file:emit_name`.
    #[serde(default)]
    unused_component_emits: Vec<String>,
    /// Unused component inputs, keyed by `file:input_name`.
    #[serde(default)]
    unused_component_inputs: Vec<String>,
    /// Unused component outputs, keyed by `file:output_name`.
    #[serde(default)]
    unused_component_outputs: Vec<String>,
    /// Unused Svelte dispatched events, keyed by `file:event_name`.
    #[serde(default)]
    unused_svelte_events: Vec<String>,
    /// Unused Effect layers, keyed by `file:layer_name`.
    #[serde(default)]
    unused_effect_layers: Vec<String>,
    /// Unused tagged errors, keyed by `file:class_name`.
    #[serde(default)]
    unused_tagged_errors: Vec<String>,
    /// Unproduced catch tags, keyed by `file:tag`.
    #[serde(default)]
    unproduced_catch_tags: Vec<String>,
    /// Unused server actions, keyed by `file:action_name`.
    #[serde(default)]
    unused_server_actions: Vec<String>,
    /// Unused SvelteKit load() data keys, keyed by `file:key_name`.
    #[serde(default)]
    unused_load_data_keys: Vec<String>,
    /// Unresolved imports, keyed by `file:specifier`.
    #[serde(default)]
    unresolved_imports: Vec<String>,
    /// Unlisted dependencies, keyed by package name.
    #[serde(default)]
    unlisted_dependencies: Vec<String>,
    /// Unlisted binaries, keyed by binary name.
    #[serde(default)]
    unlisted_binaries: Vec<String>,
    /// Duplicate exports, keyed by export name.
    #[serde(default)]
    duplicate_exports: Vec<String>,
    /// Bindings exported under two or more names in one file, keyed by the
    /// canonical finding key. No legacy key form exists.
    #[serde(default)]
    duplicate_export_aliases: Vec<String>,
    /// Type-only dependencies, keyed by `package.json:package_name`. Legacy
    /// bare `package_name` keys are still matched for back-compat with
    /// baselines saved by older fallow versions.
    #[serde(default)]
    type_only_dependencies: Vec<String>,
    /// Test-only dependencies, keyed by `package.json:package_name`. Legacy
    /// bare `package_name` keys are still matched for back-compat with
    /// baselines saved by older fallow versions.
    #[serde(default)]
    test_only_dependencies: Vec<String>,
    /// Dev dependencies used in production, keyed by `package.json:package_name`.
    #[serde(default)]
    dev_dependencies_in_production: Vec<String>,
    /// Boundary violations, keyed by `from_path->to_path`.
    #[serde(default)]
    boundary_violations: Vec<String>,
    /// Boundary coverage violations, keyed by `path`.
    #[serde(default)]
    boundary_coverage_violations: Vec<String>,
    /// Boundary call violations, keyed by `path:callee`.
    #[serde(default)]
    boundary_call_violations: Vec<String>,
    /// Rule-pack policy violations, keyed by `path:pack/rule_id:matched`.
    #[serde(default)]
    policy_violations: Vec<String>,
    /// Stale suppressions, keyed by `file:line`.
    #[serde(default)]
    stale_suppressions: Vec<String>,
    /// Unused pnpm catalog entries, keyed by `catalog_name:entry_name`.
    #[serde(default)]
    unused_catalog_entries: Vec<String>,
    /// Empty pnpm catalog groups, keyed by `catalog_name`.
    #[serde(default)]
    empty_catalog_groups: Vec<String>,
    /// Unresolved catalog references, keyed by `path:line:catalog_name:entry_name`.
    #[serde(default)]
    unresolved_catalog_references: Vec<String>,
    /// Unused package-manager dependency overrides, keyed by `source:raw_key`.
    #[serde(default)]
    unused_dependency_overrides: Vec<String>,
    /// Misconfigured package-manager dependency overrides, keyed by `source:raw_key`.
    #[serde(default)]
    misconfigured_dependency_overrides: Vec<String>,
    /// Invalid `"use client"` exports, keyed by `path:export_name`.
    #[serde(default)]
    invalid_client_exports: Vec<String>,
    /// Mixed client/server barrels, keyed by `path:client_origin:server_origin`.
    #[serde(default)]
    mixed_client_server_barrels: Vec<String>,
    /// Misplaced `"use client"` / `"use server"` directives, keyed by
    /// `path:line:directive`.
    #[serde(default)]
    misplaced_directives: Vec<String>,
    /// Next.js route collisions, keyed by `path:url`.
    #[serde(default)]
    route_collisions: Vec<String>,
    /// Next.js dynamic-segment name conflicts, keyed by `path:position`.
    #[serde(default)]
    dynamic_segment_name_conflicts: Vec<String>,
    /// Reviewed prop chains, keyed by source component and prop with occurrence matching.
    #[serde(default)]
    prop_drilling_chains: Vec<String>,
    /// Reviewed thin wrappers, keyed by source component with occurrence matching.
    #[serde(default)]
    thin_wrappers: Vec<String>,
    /// Reviewed duplicate prop shapes, keyed by component and significant shape.
    #[serde(default)]
    duplicate_prop_shapes: Vec<String>,
}

impl BaselineData {
    /// The keys a dead-code baseline cannot load without. They carry no serde
    /// default, so a file that deserializes into this struct carries all of
    /// them, and a file carrying none of them is not a dead-code baseline
    /// however it is spelled. Deliberately a subset of what the format writes:
    /// the rest are optional and say nothing about which command wrote the file.
    const REQUIRED_KEYS: &'static [&'static str] = &[
        "unused_files",
        "unused_exports",
        "unused_types",
        "unused_dependencies",
        "unused_dev_dependencies",
    ];

    /// Build baseline keys from analysis results under the syntactic identity.
    #[cfg(test)]
    fn from_results(results: &crate::results::AnalysisResults, root: &Path) -> Self {
        Self::from_results_with_identity(
            results,
            root,
            fallow_types::semantic::SemanticAnalysisIdentity::syntactic(),
        )
    }

    /// Build baseline keys from analysis results, stamping the given analysis
    /// identity so later loads can reject baselines produced under an
    /// incompatible analysis mode.
    ///
    /// Every entry is a canonical key, written once for each occurrence and
    /// sorted, so the file does not change when findings move.
    pub fn from_results_with_identity(
        results: &crate::results::AnalysisResults,
        root: &Path,
        analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
    ) -> Self {
        let paths = IdentityPaths::new(root);
        macro_rules! build {
            ($($field:ident),* $(,)?) => {
                Self {
                    kind: Some(BaselineKind::DeadCode),
                    analysis_identity: analysis_identity.into(),
                    identity: Some(BASELINE_KEY_SCHEME.to_owned()),
                    scope_reasons: Vec::new(),
                    $($field: canonical_keys(&results.$field, &paths),)*
                }
            };
        }
        with_baseline_fields!(build)
    }

    /// Build a baseline in the legacy key forms that fallow wrote before
    /// canonical keys. Tests use it to prove that legacy files still load.
    #[cfg(test)]
    fn legacy_from_results(results: &crate::results::AnalysisResults, root: &Path) -> Self {
        let analysis_identity = fallow_types::semantic::SemanticAnalysisIdentity::syntactic();
        let file_exports = baseline_file_export_keys(results, root);
        let member_imports = baseline_member_import_keys(results, root);
        let dependencies = baseline_dependency_keys(results, root);
        let graph = baseline_graph_keys(results, root);
        let catalog = baseline_catalog_keys(results, root);

        Self {
            kind: Some(BaselineKind::DeadCode),
            analysis_identity: analysis_identity.into(),
            identity: None,
            scope_reasons: Vec::new(),
            unused_files: file_exports.unused_files,
            unused_exports: file_exports.unused_exports,
            unused_types: file_exports.unused_types,
            private_type_leaks: file_exports.private_type_leaks,
            deprecated_exports_in_use: file_exports.deprecated_exports_in_use,
            unused_dependencies: dependencies.unused,
            unused_dev_dependencies: dependencies.unused_dev,
            circular_dependencies: graph.circular_dependencies,
            re_export_cycles: graph.re_export_cycles,
            package_cycles: graph.package_cycles,
            unused_optional_dependencies: dependencies.unused_optional,
            unused_enum_members: member_imports.unused_enum_members,
            unused_class_members: member_imports.unused_class_members,
            unused_store_members: member_imports.unused_store_members,
            unused_namespace_members: member_imports.unused_namespace_members,
            unused_protected_class_members: member_imports.unused_protected_class_members,
            namespace_escapes: Vec::new(),
            unprovided_injects: member_imports.unprovided_injects,
            unrendered_components: member_imports.unrendered_components,
            unused_component_props: member_imports.unused_component_props,
            absent_component_props: member_imports.absent_component_props,
            constant_parameters: member_imports.constant_parameters,
            unused_component_emits: member_imports.unused_component_emits,
            unused_component_inputs: member_imports.unused_component_inputs,
            unused_component_outputs: member_imports.unused_component_outputs,
            unused_svelte_events: member_imports.unused_svelte_events,
            unused_effect_layers: member_imports.unused_effect_layers,
            unused_tagged_errors: member_imports.unused_tagged_errors,
            unproduced_catch_tags: member_imports.unproduced_catch_tags,
            unused_server_actions: member_imports.unused_server_actions,
            unused_load_data_keys: member_imports.unused_load_data_keys,
            unresolved_imports: member_imports.unresolved_imports,
            unlisted_dependencies: dependencies.unlisted,
            unlisted_binaries: Vec::new(),
            duplicate_exports: member_imports.duplicate_exports,
            duplicate_export_aliases: Vec::new(),
            type_only_dependencies: dependencies.type_only,
            test_only_dependencies: dependencies.test_only,
            dev_dependencies_in_production: dependencies.dev_in_prod,
            boundary_violations: graph.boundary_violations,
            boundary_coverage_violations: graph.boundary_coverage_violations,
            boundary_call_violations: graph.boundary_call_violations,
            policy_violations: graph.policy_violations,
            stale_suppressions: member_imports.stale_suppressions,
            unused_catalog_entries: catalog.unused_catalog_entries,
            empty_catalog_groups: catalog.empty_catalog_groups,
            unresolved_catalog_references: catalog.unresolved_catalog_references,
            unused_dependency_overrides: catalog.unused_dependency_overrides,
            misconfigured_dependency_overrides: catalog.misconfigured_dependency_overrides,
            invalid_client_exports: file_exports.invalid_client_exports,
            mixed_client_server_barrels: file_exports.mixed_client_server_barrels,
            misplaced_directives: file_exports.misplaced_directives,
            route_collisions: file_exports.route_collisions,
            dynamic_segment_name_conflicts: file_exports.dynamic_segment_name_conflicts,
            prop_drilling_chains: Vec::new(),
            thin_wrappers: Vec::new(),
            duplicate_prop_shapes: Vec::new(),
        }
    }

    /// The analysis identity this baseline was captured under.
    #[must_use]
    pub const fn analysis_identity(&self) -> &fallow_types::semantic::SemanticAnalysisIdentity {
        &self.analysis_identity.semantic
    }

    /// Total number of entries across all categories.
    fn total_entries(&self) -> usize {
        self.unused_files.len()
            + self.unused_exports.len()
            + self.unused_types.len()
            + self.private_type_leaks.len()
            + self.deprecated_exports_in_use.len()
            + self.unused_dependencies.len()
            + self.unused_dev_dependencies.len()
            + self.circular_dependencies.len()
            + self.re_export_cycles.len()
            + self.package_cycles.len()
            + self.unused_optional_dependencies.len()
            + self.unused_enum_members.len()
            + self.unused_class_members.len()
            + self.unused_store_members.len()
            + self.unused_namespace_members.len()
            + self.unused_protected_class_members.len()
            + self.namespace_escapes.len()
            + self.unprovided_injects.len()
            + self.unrendered_components.len()
            + self.unused_component_props.len()
            + self.absent_component_props.len()
            + self.constant_parameters.len()
            + self.unused_component_emits.len()
            + self.unused_component_inputs.len()
            + self.unused_component_outputs.len()
            + self.unused_svelte_events.len()
            + self.unused_effect_layers.len()
            + self.unused_tagged_errors.len()
            + self.unproduced_catch_tags.len()
            + self.unused_server_actions.len()
            + self.unused_load_data_keys.len()
            + self.unresolved_imports.len()
            + self.unlisted_dependencies.len()
            + self.unlisted_binaries.len()
            + self.duplicate_exports.len()
            + self.duplicate_export_aliases.len()
            + self.type_only_dependencies.len()
            + self.test_only_dependencies.len()
            + self.dev_dependencies_in_production.len()
            + self.boundary_violations.len()
            + self.boundary_coverage_violations.len()
            + self.boundary_call_violations.len()
            + self.policy_violations.len()
            + self.stale_suppressions.len()
            + self.unused_catalog_entries.len()
            + self.empty_catalog_groups.len()
            + self.unresolved_catalog_references.len()
            + self.unused_dependency_overrides.len()
            + self.misconfigured_dependency_overrides.len()
            + self.invalid_client_exports.len()
            + self.mixed_client_server_barrels.len()
            + self.misplaced_directives.len()
            + self.route_collisions.len()
            + self.dynamic_segment_name_conflicts.len()
            + self.prop_drilling_chains.len()
            + self.thin_wrappers.len()
            + self.duplicate_prop_shapes.len()
    }
}

#[cfg(test)]
struct BaselineFileExportKeys {
    unused_files: Vec<String>,
    unused_exports: Vec<String>,
    unused_types: Vec<String>,
    private_type_leaks: Vec<String>,
    deprecated_exports_in_use: Vec<String>,
    invalid_client_exports: Vec<String>,
    mixed_client_server_barrels: Vec<String>,
    misplaced_directives: Vec<String>,
    route_collisions: Vec<String>,
    dynamic_segment_name_conflicts: Vec<String>,
}

#[cfg(test)]
struct BaselineMemberImportKeys {
    unused_enum_members: Vec<String>,
    unused_class_members: Vec<String>,
    unused_store_members: Vec<String>,
    unused_namespace_members: Vec<String>,
    unused_protected_class_members: Vec<String>,
    unprovided_injects: Vec<String>,
    unrendered_components: Vec<String>,
    unused_component_props: Vec<String>,
    absent_component_props: Vec<String>,
    constant_parameters: Vec<String>,
    unused_component_emits: Vec<String>,
    unused_component_inputs: Vec<String>,
    unused_component_outputs: Vec<String>,
    unused_svelte_events: Vec<String>,
    unused_effect_layers: Vec<String>,
    unused_tagged_errors: Vec<String>,
    unproduced_catch_tags: Vec<String>,
    unused_server_actions: Vec<String>,
    unused_load_data_keys: Vec<String>,
    unresolved_imports: Vec<String>,
    duplicate_exports: Vec<String>,
    stale_suppressions: Vec<String>,
}

fn stale_suppression_baseline_key(
    suppression: &crate::results::StaleSuppression,
    root: &Path,
) -> String {
    let rule_id = if suppression.missing_reason {
        "missing-suppression-reason"
    } else {
        "stale-suppression"
    };
    format!(
        "{rule_id}:{}:{}",
        relative_path(&suppression.path, root),
        suppression.line
    )
}

fn inject_baseline_keys(
    items: &[crate::results::UnprovidedInjectFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|f| {
            format!(
                "{}:{}",
                relative_path(&f.inject.path, root),
                f.inject.key_name
            )
        })
        .collect()
}

fn component_baseline_keys(
    items: &[crate::results::UnrenderedComponentFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|c| {
            format!(
                "{}:{}",
                relative_path(&c.component.path, root),
                c.component.component_name
            )
        })
        .collect()
}

fn component_prop_baseline_keys(
    items: &[crate::results::UnusedComponentPropFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|p| format!("{}:{}", relative_path(&p.prop.path, root), p.prop.prop_name))
        .collect()
}

fn component_emit_baseline_keys(
    items: &[crate::results::UnusedComponentEmitFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|e| format!("{}:{}", relative_path(&e.emit.path, root), e.emit.emit_name))
        .collect()
}

fn component_input_baseline_keys(
    items: &[crate::results::UnusedComponentInputFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|i| {
            format!(
                "{}:{}",
                relative_path(&i.input.path, root),
                i.input.input_name
            )
        })
        .collect()
}

fn component_output_baseline_keys(
    items: &[crate::results::UnusedComponentOutputFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|o| {
            format!(
                "{}:{}",
                relative_path(&o.output.path, root),
                o.output.output_name
            )
        })
        .collect()
}

fn effect_layer_baseline_keys(
    items: &[crate::results::UnusedEffectLayerFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|f| format!("{}:{}", relative_path(&f.layer.path, root), f.layer.name))
        .collect()
}

fn tagged_error_baseline_keys(
    items: &[crate::results::UnusedTaggedErrorFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|f| format!("{}:{}", relative_path(&f.error.path, root), f.error.name))
        .collect()
}

fn catch_tag_baseline_keys(
    items: &[crate::results::UnproducedCatchTagFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|f| {
            format!(
                "{}:{}",
                relative_path(&f.catch_tag.path, root),
                f.catch_tag.tag
            )
        })
        .collect()
}

fn svelte_event_baseline_keys(
    items: &[crate::results::UnusedSvelteEventFinding],
    root: &Path,
) -> Vec<String> {
    items
        .iter()
        .map(|e| {
            format!(
                "{}:{}",
                relative_path(&e.event.path, root),
                e.event.event_name
            )
        })
        .collect()
}

#[cfg(test)]
struct BaselineDependencyKeys {
    unused: Vec<String>,
    unused_dev: Vec<String>,
    unused_optional: Vec<String>,
    unlisted: Vec<String>,
    type_only: Vec<String>,
    test_only: Vec<String>,
    dev_in_prod: Vec<String>,
}

/// Generate a stable key for a boundary violation: `from_path->to_path`.
fn boundary_violation_key(v: &crate::results::BoundaryViolation, root: &Path) -> String {
    format!(
        "{}->{}",
        relative_path(&v.from_path, root),
        relative_path(&v.to_path, root),
    )
}

/// Generate a stable key for a boundary call violation: `path:callee`.
fn boundary_call_violation_key(v: &crate::results::BoundaryCallViolation, root: &Path) -> String {
    format!("{}:{}", relative_path(&v.path, root), v.callee)
}

/// Generate a stable key for a duplicate export: `name|sorted_paths`.
fn duplicate_export_key(dup: &crate::results::DuplicateExport, root: &Path) -> String {
    let mut locs: Vec<String> = dup
        .locations
        .iter()
        .map(|l| relative_path(&l.path, root))
        .collect();
    locs.sort();
    format!("{}|{}", dup.export_name, locs.join("|"))
}

/// Generate a stable key for a circular dependency based on sorted file paths.
fn circular_dep_key(dep: &crate::results::CircularDependency, root: &Path) -> String {
    let mut paths: Vec<String> = dep.files.iter().map(|f| relative_path(f, root)).collect();
    paths.sort();
    paths.join("->")
}

/// Generate a stable key for a re-export cycle based on its discriminator
/// kind plus sorted member paths. The `kind` prefix is mandatory: without
/// it a self-loop on `src/foo.ts` would keyspace-collide with any future
/// single-file multi-node shape, and the `--baseline new` filter would
/// silently drop the new one as already-seen (panel catch #7).
fn re_export_cycle_key(cycle: &crate::results::ReExportCycle, root: &Path) -> String {
    let kind = match cycle.kind {
        crate::results::ReExportCycleKind::MultiNode => "multi-node",
        crate::results::ReExportCycleKind::SelfLoop => "self-loop",
    };
    let mut paths: Vec<String> = cycle.files.iter().map(|f| relative_path(f, root)).collect();
    paths.sort();
    format!("{kind}:{}", paths.join("<->"))
}

/// Generate a stable key for a package cycle. The package names are already
/// in canonical cycle order, and they do not depend on the example import, so
/// the key survives a change of example import.
fn package_cycle_key(cycle: &crate::results::PackageCycle) -> String {
    cycle.packages.join("->")
}

fn private_type_leak_key(leak: &crate::results::PrivateTypeLeak, root: &Path) -> String {
    format!(
        "{}:{}->{}",
        relative_path(&leak.path, root),
        leak.export_name,
        leak.type_name
    )
}

fn deprecated_export_key(
    export: &fallow_types::results::DeprecatedExportInUse,
    root: &Path,
) -> String {
    format!(
        "{}:{}",
        relative_path(&export.path, root),
        export.export_name
    )
}

fn filter_private_type_leaks(
    leaks: &mut Vec<fallow_types::output_dead_code::PrivateTypeLeakFinding>,
    baseline_keys: &[String],
    root: &Path,
) {
    let baseline_private_type_leaks: FxHashSet<&str> =
        baseline_keys.iter().map(String::as_str).collect();
    leaks.retain(|entry| {
        let key = private_type_leak_key(&entry.leak, root);
        !baseline_private_type_leaks.contains(key.as_str())
    });
}

struct BaselineFilterContext<'a> {
    baseline: &'a BaselineData,
    root: &'a Path,
}

impl BaselineFilterContext<'_> {
    fn filter_cycles_and_members(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_circular: FxHashSet<&str> = self
            .baseline
            .circular_dependencies
            .iter()
            .map(String::as_str)
            .collect();
        results.circular_dependencies.retain(|cycle| {
            let key = circular_dep_key(&cycle.cycle, self.root);
            !baseline_circular.contains(key.as_str())
        });

        let baseline_re_export_cycles: FxHashSet<&str> = self
            .baseline
            .re_export_cycles
            .iter()
            .map(String::as_str)
            .collect();
        results.re_export_cycles.retain(|cycle| {
            let key = re_export_cycle_key(&cycle.cycle, self.root);
            !baseline_re_export_cycles.contains(key.as_str())
        });

        let baseline_package_cycles: FxHashSet<&str> = self
            .baseline
            .package_cycles
            .iter()
            .map(String::as_str)
            .collect();
        results.package_cycles.retain(|cycle| {
            !baseline_package_cycles.contains(package_cycle_key(&cycle.cycle).as_str())
        });

        self.filter_unused_members(results);
        self.filter_unresolved_and_exports(results);
    }

    fn filter_unused_members(&self, results: &mut crate::results::AnalysisResults) {
        self.filter_enum_class_store_members(results);
        self.filter_component_surface_members(results);
        self.filter_route_action_members(results);
    }

    fn filter_enum_class_store_members(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_enum_members: FxHashSet<&str> = self
            .baseline
            .unused_enum_members
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_enum_members.retain(|member| {
            let key = format!(
                "{}:{}.{}",
                relative_path(&member.member.path, self.root),
                member.member.parent_name,
                member.member.member_name
            );
            !baseline_enum_members.contains(key.as_str())
        });

        let baseline_class_members: FxHashSet<&str> = self
            .baseline
            .unused_class_members
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_class_members.retain(|member| {
            let key = format!(
                "{}:{}.{}",
                relative_path(&member.member.path, self.root),
                member.member.parent_name,
                member.member.member_name
            );
            !baseline_class_members.contains(key.as_str())
        });

        let baseline_store_members: FxHashSet<&str> = self
            .baseline
            .unused_store_members
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_store_members.retain(|member| {
            let key = format!(
                "{}:{}.{}",
                relative_path(&member.member.path, self.root),
                member.member.parent_name,
                member.member.member_name
            );
            !baseline_store_members.contains(key.as_str())
        });
        let baseline_namespace_members: FxHashSet<&str> = self
            .baseline
            .unused_namespace_members
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_namespace_members.retain(|member| {
            let key = format!(
                "{}:{}.{}",
                relative_path(&member.member.path, self.root),
                member.member.parent_name,
                member.member.member_name
            );
            !baseline_namespace_members.contains(key.as_str())
        });
        let baseline_protected_class_members: FxHashSet<&str> = self
            .baseline
            .unused_protected_class_members
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_protected_class_members.retain(|member| {
            let key = format!(
                "{}:{}.{}",
                relative_path(&member.member.path, self.root),
                member.member.parent_name,
                member.member.member_name
            );
            !baseline_protected_class_members.contains(key.as_str())
        });
    }

    fn filter_component_surface_members(&self, results: &mut crate::results::AnalysisResults) {
        retain_new_by_keys(
            &mut results.unprovided_injects,
            &self.baseline.unprovided_injects,
            self.root,
            inject_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unrendered_components,
            &self.baseline.unrendered_components,
            self.root,
            component_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_component_props,
            &self.baseline.unused_component_props,
            self.root,
            component_prop_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.absent_component_props,
            &self.baseline.absent_component_props,
            self.root,
            absent_component_prop_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.constant_parameters,
            &self.baseline.constant_parameters,
            self.root,
            constant_parameter_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_component_emits,
            &self.baseline.unused_component_emits,
            self.root,
            component_emit_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_component_inputs,
            &self.baseline.unused_component_inputs,
            self.root,
            component_input_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_component_outputs,
            &self.baseline.unused_component_outputs,
            self.root,
            component_output_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_svelte_events,
            &self.baseline.unused_svelte_events,
            self.root,
            svelte_event_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_effect_layers,
            &self.baseline.unused_effect_layers,
            self.root,
            effect_layer_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unused_tagged_errors,
            &self.baseline.unused_tagged_errors,
            self.root,
            tagged_error_baseline_keys,
        );
        retain_new_by_keys(
            &mut results.unproduced_catch_tags,
            &self.baseline.unproduced_catch_tags,
            self.root,
            catch_tag_baseline_keys,
        );
    }

    fn filter_route_action_members(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_unused_server_actions: FxHashSet<&str> = self
            .baseline
            .unused_server_actions
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_server_actions.retain(|finding| {
            let key = format!(
                "{}:{}",
                relative_path(&finding.action.path, self.root),
                finding.action.action_name
            );
            !baseline_unused_server_actions.contains(key.as_str())
        });

        let baseline_unused_load_data_keys: FxHashSet<&str> = self
            .baseline
            .unused_load_data_keys
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_load_data_keys.retain(|finding| {
            let key = format!(
                "{}:{}",
                relative_path(&finding.key.path, self.root),
                finding.key.key_name
            );
            !baseline_unused_load_data_keys.contains(key.as_str())
        });
    }

    fn filter_unresolved_and_exports(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_unresolved: FxHashSet<&str> = self
            .baseline
            .unresolved_imports
            .iter()
            .map(String::as_str)
            .collect();
        results.unresolved_imports.retain(|import| {
            let key = format!(
                "{}:{}",
                relative_path(&import.import.path, self.root),
                import.import.specifier
            );
            !baseline_unresolved.contains(key.as_str())
        });

        let baseline_unlisted: FxHashSet<&str> = self
            .baseline
            .unlisted_dependencies
            .iter()
            .map(String::as_str)
            .collect();
        results
            .unlisted_dependencies
            .retain(|dep| !baseline_unlisted.contains(dep.dep.package_name.as_str()));

        let baseline_dup_exports: FxHashSet<&str> = self
            .baseline
            .duplicate_exports
            .iter()
            .map(String::as_str)
            .collect();
        results.duplicate_exports.retain(|duplicate| {
            let key = duplicate_export_key(&duplicate.export, self.root);
            !baseline_dup_exports.contains(key.as_str())
        });
    }

    fn filter_dependency_variants(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_optional_deps: FxHashSet<&str> = self
            .baseline
            .unused_optional_dependencies
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_optional_dependencies.retain(|dep| {
            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
            !baseline_contains_dependency(
                &baseline_optional_deps,
                &dep.dep.package_name,
                key.as_str(),
            )
        });

        self.filter_type_and_test_only_dependencies(results);
    }

    fn filter_type_and_test_only_dependencies(
        &self,
        results: &mut crate::results::AnalysisResults,
    ) {
        let baseline_type_only: FxHashSet<&str> = self
            .baseline
            .type_only_dependencies
            .iter()
            .map(String::as_str)
            .collect();
        results.type_only_dependencies.retain(|dep| {
            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
            !baseline_contains_dependency(&baseline_type_only, &dep.dep.package_name, key.as_str())
        });

        let baseline_test_only: FxHashSet<&str> = self
            .baseline
            .test_only_dependencies
            .iter()
            .map(String::as_str)
            .collect();
        results.test_only_dependencies.retain(|dep| {
            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
            !baseline_contains_dependency(&baseline_test_only, &dep.dep.package_name, key.as_str())
        });

        let baseline_dev_in_prod: FxHashSet<&str> = self
            .baseline
            .dev_dependencies_in_production
            .iter()
            .map(String::as_str)
            .collect();
        results.dev_dependencies_in_production.retain(|dep| {
            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
            !baseline_contains_dependency(
                &baseline_dev_in_prod,
                &dep.dep.package_name,
                key.as_str(),
            )
        });
    }

    fn filter_boundaries_and_suppressions(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_boundary: FxHashSet<&str> = self
            .baseline
            .boundary_violations
            .iter()
            .map(String::as_str)
            .collect();
        results.boundary_violations.retain(|violation| {
            let key = boundary_violation_key(&violation.violation, self.root);
            !baseline_boundary.contains(key.as_str())
        });

        self.filter_boundary_details(results);
        self.filter_stale_suppressions(results);
        self.filter_invalid_client_exports(results);
        self.filter_mixed_client_server_barrels(results);
        self.filter_misplaced_directives(results);
        self.filter_route_collisions(results);
        self.filter_dynamic_segment_name_conflicts(results);
    }

    fn filter_invalid_client_exports(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_invalid: FxHashSet<&str> = self
            .baseline
            .invalid_client_exports
            .iter()
            .map(String::as_str)
            .collect();
        results.invalid_client_exports.retain(|finding| {
            let key = format!(
                "{}:{}",
                relative_path(&finding.export.path, self.root),
                finding.export.export_name
            );
            !baseline_invalid.contains(key.as_str())
        });
    }

    fn filter_mixed_client_server_barrels(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_barrels: FxHashSet<&str> = self
            .baseline
            .mixed_client_server_barrels
            .iter()
            .map(String::as_str)
            .collect();
        results.mixed_client_server_barrels.retain(|finding| {
            let key = format!(
                "{}:{}:{}",
                relative_path(&finding.barrel.path, self.root),
                finding.barrel.client_origin,
                finding.barrel.server_origin
            );
            !baseline_barrels.contains(key.as_str())
        });
    }

    fn filter_misplaced_directives(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_directives: FxHashSet<&str> = self
            .baseline
            .misplaced_directives
            .iter()
            .map(String::as_str)
            .collect();
        results.misplaced_directives.retain(|finding| {
            let key = format!(
                "{}:{}:{}",
                relative_path(&finding.directive_site.path, self.root),
                finding.directive_site.line,
                finding.directive_site.directive
            );
            !baseline_directives.contains(key.as_str())
        });
    }

    fn filter_route_collisions(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_collisions: FxHashSet<&str> = self
            .baseline
            .route_collisions
            .iter()
            .map(String::as_str)
            .collect();
        results.route_collisions.retain(|finding| {
            let key = format!(
                "{}:{}",
                relative_path(&finding.collision.path, self.root),
                finding.collision.url
            );
            !baseline_collisions.contains(key.as_str())
        });
    }

    fn filter_dynamic_segment_name_conflicts(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_conflicts: FxHashSet<&str> = self
            .baseline
            .dynamic_segment_name_conflicts
            .iter()
            .map(String::as_str)
            .collect();
        results.dynamic_segment_name_conflicts.retain(|finding| {
            let key = format!(
                "{}:{}",
                relative_path(&finding.conflict.path, self.root),
                finding.conflict.position
            );
            !baseline_conflicts.contains(key.as_str())
        });
    }

    fn filter_boundary_details(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_boundary_coverage: FxHashSet<&str> = self
            .baseline
            .boundary_coverage_violations
            .iter()
            .map(String::as_str)
            .collect();
        results.boundary_coverage_violations.retain(|violation| {
            let key = relative_path(&violation.violation.path, self.root);
            !baseline_boundary_coverage.contains(key.as_str())
        });

        let baseline_boundary_calls: FxHashSet<&str> = self
            .baseline
            .boundary_call_violations
            .iter()
            .map(String::as_str)
            .collect();
        results.boundary_call_violations.retain(|violation| {
            let key = boundary_call_violation_key(&violation.violation, self.root);
            !baseline_boundary_calls.contains(key.as_str())
        });
    }

    fn filter_stale_suppressions(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_stale: FxHashSet<&str> = self
            .baseline
            .stale_suppressions
            .iter()
            .map(String::as_str)
            .collect();
        results.stale_suppressions.retain(|suppression| {
            let key = stale_suppression_baseline_key(suppression, self.root);
            let legacy_key = format!(
                "{}:{}",
                relative_path(&suppression.path, self.root),
                suppression.line
            );
            !baseline_stale.contains(key.as_str()) && !baseline_stale.contains(legacy_key.as_str())
        });
    }

    fn filter_pnpm_entries(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_catalog: FxHashSet<&str> = self
            .baseline
            .unused_catalog_entries
            .iter()
            .map(String::as_str)
            .collect();
        results.unused_catalog_entries.retain(|entry| {
            let key = format!("{}:{}", entry.entry.catalog_name, entry.entry.entry_name);
            !baseline_catalog.contains(key.as_str())
        });

        let baseline_empty_catalog_groups: FxHashSet<&str> = self
            .baseline
            .empty_catalog_groups
            .iter()
            .map(String::as_str)
            .collect();
        results.empty_catalog_groups.retain(|group| {
            !baseline_empty_catalog_groups.contains(group.group.catalog_name.as_str())
        });

        self.filter_pnpm_references_and_overrides(results);
    }

    fn filter_pnpm_references_and_overrides(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_unresolved: FxHashSet<&str> = self
            .baseline
            .unresolved_catalog_references
            .iter()
            .map(String::as_str)
            .collect();
        results.unresolved_catalog_references.retain(|reference| {
            let key = format!(
                "{}:{}:{}:{}",
                relative_path(&reference.reference.path, self.root),
                reference.reference.line,
                reference.reference.catalog_name,
                reference.reference.entry_name,
            );
            !baseline_unresolved.contains(key.as_str())
        });

        self.filter_pnpm_overrides(results);
    }

    fn filter_pnpm_overrides(&self, results: &mut crate::results::AnalysisResults) {
        let baseline_unused_overrides: FxHashSet<&str> = self
            .baseline
            .unused_dependency_overrides
            .iter()
            .map(String::as_str)
            .collect();
        results
            .unused_dependency_overrides
            .retain(|override_entry| {
                let key = format!(
                    "{}:{}",
                    override_entry.entry.source, override_entry.entry.raw_key
                );
                !baseline_unused_overrides.contains(key.as_str())
            });

        let baseline_misconfigured_overrides: FxHashSet<&str> = self
            .baseline
            .misconfigured_dependency_overrides
            .iter()
            .map(String::as_str)
            .collect();
        results
            .misconfigured_dependency_overrides
            .retain(|override_entry| {
                let key = format!(
                    "{}:{}",
                    override_entry.entry.source, override_entry.entry.raw_key
                );
                !baseline_misconfigured_overrides.contains(key.as_str())
            });
    }
}

/// Filter results to only include issues not present in the baseline.
///
/// A baseline with an `identity` matches canonical keys by count. A legacy
/// baseline matches each entry in its old form, as older fallow versions did.
fn filter_new_issues(
    results: crate::results::AnalysisResults,
    baseline: &BaselineData,
    root: &Path,
) -> crate::results::AnalysisResults {
    if baseline.identity.is_some() {
        filter_new_issues_by_canonical_keys(results, baseline, root)
    } else {
        filter_new_issues_by_legacy_keys(results, baseline, root)
    }
}

fn filter_new_issues_by_canonical_keys(
    mut results: crate::results::AnalysisResults,
    baseline: &BaselineData,
    root: &Path,
) -> crate::results::AnalysisResults {
    let paths = IdentityPaths::new(root);
    macro_rules! retain {
        ($($field:ident),* $(,)?) => {
            $(retain_unsaved(&mut results.$field, &baseline.$field, &paths);)*
        };
    }
    with_baseline_fields!(retain);
    results
}

/// What a loaded dead-code baseline did to a result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeadCodeBaselineOutcome {
    /// The file is a dead-code baseline. The findings it holds are removed.
    Applied {
        /// This run's view of the baseline.
        staleness: BaselineStaleness,
        /// True when the file has no `identity`, so its entries use the legacy
        /// key forms. `--save-baseline` rewrites it with canonical keys.
        legacy_keys: bool,
    },
    /// The file is not a dead-code baseline: another command saved it
    /// (`saved_by` names that command), or nothing in it names a writer. It
    /// suppresses nothing, so every finding stays.
    NotDeadCode {
        /// This run's view of the file: zero entries, zero matches.
        staleness: BaselineStaleness,
        /// The known command that saved the file, when the file names one.
        saved_by: Option<BaselineKind>,
    },
}

/// Why a dead-code baseline could not be applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeadCodeBaselineError {
    /// The file is not valid JSON, or a dead-code baseline with a missing or
    /// wrong field.
    Parse(String),
    /// The baseline was saved with another analysis identity, for example a
    /// type-aware run. The fields that differ are listed.
    IncompatibleIdentity(Vec<&'static str>),
}

/// Apply a dead-code baseline to a result.
///
/// The CLI (`--baseline`) and the programmatic API read a baseline through this
/// one function, so a baseline hides the same findings on every surface.
/// `content` is the text of the baseline file. `change_scoped` is true when the
/// run analyzed only part of the project; see [`BaselineStaleness`].
///
/// The file kind is read before the strict parse. Several fields of the
/// dead-code format have no default, so another command's baseline would fail
/// the parse before anything could name its writer.
///
/// # Errors
///
/// Returns [`DeadCodeBaselineError`] when the file is not valid JSON, is a
/// broken dead-code baseline, or was saved with an incompatible analysis
/// identity.
pub fn apply_dead_code_baseline(
    results: &mut crate::results::AnalysisResults,
    content: &str,
    root: &Path,
    identity: &fallow_types::semantic::SemanticAnalysisIdentity,
    change_scoped: bool,
) -> Result<DeadCodeBaselineOutcome, DeadCodeBaselineError> {
    let parsed = serde_json::from_str::<serde_json::Value>(content)
        .map_err(|err| DeadCodeBaselineError::Parse(err.to_string()))?;
    let saved_by = match classify_baseline_value(&parsed, BaselineKind::DeadCode) {
        BaselineFileKind::Own | BaselineFileKind::NotAnObject => None,
        foreign @ BaselineFileKind::Foreign(_) => Some(foreign.saved_by()),
        BaselineFileKind::Unrecognised => Some(None),
    };
    if let Some(saved_by) = saved_by {
        return Ok(DeadCodeBaselineOutcome::NotDeadCode {
            staleness: BaselineStaleness {
                entries: 0,
                matched: 0,
                current_findings: results.total_issues(),
                change_scoped,
            },
            saved_by,
        });
    }
    let baseline = serde_json::from_value::<BaselineData>(parsed)
        .map_err(|err| DeadCodeBaselineError::Parse(err.to_string()))?;
    if let Some(scheme) = baseline.identity.as_deref()
        && scheme != BASELINE_KEY_SCHEME
    {
        return Err(DeadCodeBaselineError::Parse(format!(
            "unknown baseline identity `{scheme}`: this fallow version reads `{BASELINE_KEY_SCHEME}` and legacy baselines. Regenerate the file with --save-baseline"
        )));
    }
    let incompatible = baseline.analysis_identity().incompatible_fields(identity);
    if !incompatible.is_empty() {
        return Err(DeadCodeBaselineError::IncompatibleIdentity(incompatible));
    }
    let before = baseline_finding_count(results);
    let hidden_matched = cascade_hidden_matches(results, &baseline, root);
    *results = filter_new_issues(std::mem::take(results), &baseline, root);
    Ok(DeadCodeBaselineOutcome::Applied {
        staleness: BaselineStaleness {
            entries: baseline.total_entries(),
            matched: before.saturating_sub(baseline_finding_count(results)) + hidden_matched,
            current_findings: before,
            change_scoped,
        },
        legacy_keys: baseline.identity.is_none(),
    })
}

/// Baseline data for duplication comparison.
///
/// New baselines key every clone group by `<fingerprint>:<instance count>` in
/// `normalized_clone_fingerprints`. The fingerprint hashes normalized clone
/// content, so an unrelated line shift or formatting-only edit keeps it matched,
/// while a token edit or extra copy reports a new finding.
///
/// `clone_groups` keeps the oldest location keys, while `clone_fingerprints`
/// keeps the raw-fragment keys expected by older binaries. New readers prefer
/// the normalized field. This makes baselines readable in both directions.
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub struct DuplicationBaselineData {
    /// The command that saved this file. See [`BaselineData::kind`] for why it
    /// is written but never read back through this struct.
    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
    kind: Option<BaselineKind>,
    /// `production` when the saving run used production mode, absent otherwise.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    scope_reasons: Vec<String>,
    /// Legacy clone group keys: sorted list of `file:start-end` per group.
    #[serde(default)]
    pub clone_groups: Vec<String>,
    /// Legacy raw-fragment keys expected by older binaries.
    #[serde(default)]
    pub clone_fingerprints: Vec<String>,
    /// Normalized content keys used by current binaries.
    #[serde(default)]
    pub(crate) normalized_clone_fingerprints: Vec<String>,
}

impl DuplicationBaselineData {
    /// The keys this format writes, for [`declares_baseline_format`].
    const DECLARED_KEYS: &'static [&'static str] = &[
        "clone_groups",
        "clone_fingerprints",
        "normalized_clone_fingerprints",
    ];

    /// Build a duplication baseline from the current report.
    pub fn from_report(report: &DuplicationReport, root: &Path) -> Self {
        let fingerprints =
            crate::duplicates::CloneFingerprintSet::from_groups(&report.clone_groups);
        Self {
            kind: Some(BaselineKind::Dupes),
            scope_reasons: Vec::new(),
            clone_groups: report
                .clone_groups
                .iter()
                .map(|g| clone_group_key(g, root))
                .collect(),
            clone_fingerprints: report
                .clone_groups
                .iter()
                .map(legacy_clone_group_fingerprint_key)
                .collect(),
            normalized_clone_fingerprints: report
                .clone_groups
                .iter()
                .map(|group| clone_group_fingerprint_key(group, &fingerprints))
                .collect(),
        }
    }

    /// True when the baseline holds a key that older versions gave to every
    /// clone group whose code did not parse on its own. A re-save replaces it.
    #[must_use]
    pub fn has_unparsed_collision_keys(&self) -> bool {
        self.normalized_clone_fingerprints
            .iter()
            .any(|key| crate::duplicates::is_unparsed_collision_key(key))
    }

    /// Number of baseline entries actually used for comparison.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        if !self.normalized_clone_fingerprints.is_empty() {
            self.normalized_clone_fingerprints.len()
        } else if !self.clone_fingerprints.is_empty() {
            self.clone_fingerprints.len()
        } else {
            self.clone_groups.len()
        }
    }
}

/// Generate a stable key for a clone group based on its instance locations.
fn clone_group_key(group: &crate::duplicates::CloneGroup, root: &Path) -> String {
    let mut parts: Vec<String> = group
        .instances
        .iter()
        .map(|i| {
            format!(
                "{}:{}-{}",
                relative_path(&i.file, root),
                i.start_line,
                i.end_line
            )
        })
        .collect();
    parts.sort();
    parts.join("|")
}

/// Generate the normalized, location-independent key written by new baselines.
fn clone_group_fingerprint_key(
    group: &crate::duplicates::CloneGroup,
    fingerprints: &crate::duplicates::CloneFingerprintSet,
) -> String {
    fingerprints.ignored_clone_key_for_group(group)
}

/// Recreate the raw-fragment key written by baseline versions before normalized
/// clone identity. Kept only as a read fallback during migration.
fn legacy_clone_group_fingerprint_key(group: &crate::duplicates::CloneGroup) -> String {
    let representative = group
        .instances
        .iter()
        .min_by(|a, b| (a.file.as_path(), a.start_line).cmp(&(b.file.as_path(), b.start_line)))
        .map_or("", |i| i.fragment.as_str());
    let hash = if representative.as_bytes().contains(&b'\r') {
        xxhash_rust::xxh3::xxh3_64(representative.replace('\r', "").as_bytes())
    } else {
        xxhash_rust::xxh3::xxh3_64(representative.as_bytes())
    };
    format!(
        "{}{:08x}:{}",
        crate::duplicates::FINGERPRINT_PREFIX,
        hash as u32,
        group.instances.len()
    )
}

fn consume_baseline_key(remaining: &mut FxHashMap<&str, usize>, key: &str) -> bool {
    match remaining.get_mut(key) {
        Some(count) if *count > 0 => {
            *count -= 1;
            true
        }
        _ => false,
    }
}

/// Filter a duplication report to only include clone groups not present in the baseline.
///
/// Baselines carrying `normalized_clone_fingerprints` compare on normalized
/// content plus instance count. Older raw fingerprints and location keys remain
/// supported as fallbacks.
pub fn filter_new_clone_groups(
    mut report: DuplicationReport,
    baseline: &DuplicationBaselineData,
    root: &Path,
) -> DuplicationReport {
    if !baseline.normalized_clone_fingerprints.is_empty() {
        let fingerprints =
            crate::duplicates::CloneFingerprintSet::from_groups(&report.clone_groups);
        let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
        for key in &baseline.normalized_clone_fingerprints {
            *remaining.entry(key.as_str()).or_insert(0) += 1;
        }
        report.clone_groups.retain(|group| {
            let key = clone_group_fingerprint_key(group, &fingerprints);
            !consume_baseline_key(&mut remaining, &key)
        });
    } else if baseline.clone_fingerprints.is_empty() {
        let baseline_keys: FxHashSet<&str> =
            baseline.clone_groups.iter().map(String::as_str).collect();
        report.clone_groups.retain(|g| {
            let key = clone_group_key(g, root);
            !baseline_keys.contains(key.as_str())
        });
    } else {
        let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
        for key in &baseline.clone_fingerprints {
            *remaining.entry(key.as_str()).or_insert(0) += 1;
        }
        report.clone_groups.retain(|group| {
            let key = legacy_clone_group_fingerprint_key(group);
            !consume_baseline_key(&mut remaining, &key)
        });
    }

    crate::duplicates::refresh_scoped_report(&mut report, root);

    report
}

/// Recompute duplication statistics after filtering (baseline or `--changed-since`).
///
/// Covered lines are the union of the line ranges of each file, so
/// overlapping clone instances do not count a line two times.
pub fn recompute_stats(report: &DuplicationReport) -> crate::duplicates::DuplicationStats {
    crate::duplicates::recompute_stats(report)
}

/// Baseline data for health (complexity) comparison.
///
/// New baselines store count-per-category-per-file data in `finding_counts` so
/// line shifts do not leak pre-existing findings. Legacy baselines with
/// `findings: ["path:name:line"]` still load so users can refresh them in
/// place with `--save-baseline`.
///
/// `identity_finding_counts` carries the same counts bucketed per function
/// identity instead of per file, for the stricter [`HealthBaselineMode::Identity`]
/// comparison. It is written only when the baseline is saved in identity mode,
/// so default baselines keep their count-only shape. Identity baselines still
/// carry `finding_counts`, so they also work in count mode and with older
/// binaries.
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub struct HealthBaselineData {
    /// The command that saved this file. See [`BaselineData::kind`] for why it
    /// is written but never read back through this struct.
    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
    pub(crate) kind: Option<BaselineKind>,
    /// `production` when the saving run used production mode, absent otherwise.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) scope_reasons: Vec<String>,
    /// Legacy health baseline keys: `relative_path:function_name:line`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) findings: Vec<String>,
    /// Count-per-category-per-file baseline buckets.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub(crate) finding_counts: HealthFindingCountMap,
    /// Count-per-category buckets keyed by `relative_path\0function_name`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub(crate) identity_finding_counts: HealthFindingCountMap,
    /// Stable runtime-coverage finding IDs from the sidecar.
    #[serde(default)]
    pub(crate) runtime_coverage_findings: Vec<String>,
    /// Line-move-tolerant runtime-coverage suppression keys of the form
    /// `path\0name\0source_hash`. Unlike `runtime_coverage_findings` (whose
    /// keys hash the start line and so churn when a function moves), the
    /// `source_hash` component is the content digest of the function body, so a
    /// moved-but-unedited function keeps the same key and stays suppressed.
    /// Only findings whose `source_hash` is present contribute an entry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) runtime_coverage_source_hashes: Vec<String>,
    /// Refactoring target keys: `relative_path:category`.
    #[serde(default)]
    pub(crate) target_keys: Vec<String>,
    /// `true` when the counts hold file-length findings as `file_lines_*`. A
    /// file without the marker holds them as `complexity_*`, and a run reads
    /// it that way. See `FileLengthCounting`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub(crate) file_lines_categories: bool,
}

/// Serialized per-bucket finding tally inside a health baseline file.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct HealthBaselineCount {
    count: usize,
}

type HealthFindingCountMap = BTreeMap<String, BTreeMap<String, HealthBaselineCount>>;

/// How a saved health baseline is matched against current findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HealthBaselineMode {
    /// Match per file and finding category. Resilient to renames and line
    /// shifts, but a replacement hotspot consumes the allowance of the hotspot
    /// it replaced.
    ///
    /// Count buckets do not survive file moves: the bucket key is the path and
    /// the payload is category tallies alone, so a bucket whose file moved has
    /// no surviving identity component to re-match on. Guessing a new path
    /// from count shapes could silently transfer allowance between unrelated
    /// files, so no move tolerance is attempted in this mode.
    #[default]
    Count,
    /// Match per function identity (path plus function name) and finding
    /// category. A hotspot that replaces another hotspot in the same file is
    /// reported, while line shifts and in-place edits stay suppressed.
    ///
    /// Identity buckets tolerate file moves conservatively: a bucket whose
    /// path no longer exists on disk follows its function name to a new path
    /// when exactly one unclaimed current bucket carries that name, resolved
    /// by `moved_identity_bucket_remaps`.
    Identity,
}

impl HealthBaselineData {
    /// The keys this format writes, for [`declares_baseline_format`]. A health
    /// baseline omits the buckets it has nothing for, so a file carrying any
    /// one of these is health's own.
    const DECLARED_KEYS: &'static [&'static str] = &[
        "findings",
        "finding_counts",
        "identity_finding_counts",
        "runtime_coverage_findings",
        "runtime_coverage_source_hashes",
        "target_keys",
    ];

    /// Build a health baseline from findings and targets.
    pub(crate) fn from_findings(
        findings: &[fallow_output::ComplexityViolation],
        runtime_coverage_findings: &[fallow_output::RuntimeCoverageFinding],
        targets: &[fallow_output::RefactoringTarget],
        root: &Path,
    ) -> Self {
        Self {
            kind: Some(BaselineKind::Health),
            scope_reasons: Vec::new(),
            findings: Vec::new(),
            finding_counts: health_finding_counts(
                findings,
                root,
                HealthBaselineMode::Count,
                FileLengthCounting::Separate,
            ),
            identity_finding_counts: HealthFindingCountMap::new(),
            runtime_coverage_findings: runtime_coverage_findings
                .iter()
                .map(|f| runtime_coverage_finding_key(f, root))
                .collect(),
            runtime_coverage_source_hashes: runtime_coverage_findings
                .iter()
                .filter_map(|f| runtime_coverage_source_hash_key(f, root))
                .collect(),
            target_keys: targets
                .iter()
                .map(|t| target_baseline_key(t, root))
                .collect(),
            file_lines_categories: true,
        }
    }

    pub(crate) fn finding_entry_count(&self) -> usize {
        if self.finding_counts.is_empty() {
            self.findings.len()
        } else {
            self.finding_counts
                .values()
                .flat_map(BTreeMap::values)
                .map(|entry| entry.count)
                .sum()
        }
    }

    /// Add per-function identity buckets to a saved baseline.
    ///
    /// Only [`HealthBaselineMode::Identity`] saves record these, so a default
    /// baseline keeps carrying counts alone and stays free of function names.
    #[must_use]
    pub(crate) fn with_identity(
        mut self,
        findings: &[fallow_output::ComplexityViolation],
        root: &Path,
    ) -> Self {
        self.identity_finding_counts = health_finding_counts(
            findings,
            root,
            HealthBaselineMode::Identity,
            self.file_length_counting(),
        );
        self
    }

    /// `true` when identity matching would silently degrade because the saved
    /// baseline predates `identity_finding_counts` yet does carry findings.
    pub(crate) fn lacks_identity_data(&self) -> bool {
        self.identity_finding_counts.is_empty()
            && (!self.finding_counts.is_empty() || !self.findings.is_empty())
    }

    fn counts_for(&self, mode: HealthBaselineMode) -> &HealthFindingCountMap {
        match mode {
            HealthBaselineMode::Count => &self.finding_counts,
            HealthBaselineMode::Identity => &self.identity_finding_counts,
        }
    }
}

/// Baseline entry overlap for one run, split so followed file moves stay
/// observable in output rather than silently absorbed into the match count.
pub(crate) struct HealthBaselineOverlap {
    /// Entries that matched a current finding, including via followed moves.
    pub(crate) matched_entries: usize,
    /// Entries that matched only because a retired identity bucket was
    /// re-keyed to a moved file.
    pub(crate) moved_entries: usize,
}

/// Generate a stable key for a refactoring target: `relative_path:category`.
fn target_baseline_key(target: &fallow_output::RefactoringTarget, root: &Path) -> String {
    format!(
        "{}:{}",
        relative_path(&target.path, root),
        target.category.label()
    )
}

/// Generate a stable key for a health finding.
fn health_finding_key(finding: &fallow_output::ComplexityViolation, root: &Path) -> String {
    format!(
        "{}:{}:{}",
        relative_path(&finding.path, root),
        finding.name,
        finding.line
    )
}

/// Bucket a finding belongs to for the given comparison mode.
///
/// The NUL separator keeps the identity bucket unambiguous for paths and
/// function names that contain `:`.
fn health_bucket_key(
    finding: &fallow_output::ComplexityViolation,
    root: &Path,
    mode: HealthBaselineMode,
) -> String {
    let path = relative_path(&finding.path, root);
    match mode {
        HealthBaselineMode::Count => path,
        HealthBaselineMode::Identity => format!("{path}\0{}", finding.name),
    }
}

fn identity_bucket_parts(key: &str) -> Option<(&str, &str)> {
    key.split_once('\0')
}

/// Conservative file-move tolerance for identity baseline buckets.
///
/// A baseline bucket follows its function to a new path only when every one of
/// these holds:
///
/// - the bucket matched no current bucket at its saved path,
/// - the saved path no longer exists on disk under the project root, so the
///   file was moved or deleted rather than merely fixed,
/// - exactly one current bucket carries the same function name at a path the
///   baseline does not already cover,
/// - no other retired baseline bucket claims that same candidate.
///
/// The function name is the only identity component that survives a move, so
/// anything more permissive would risk transferring allowance between
/// unrelated functions. Anonymous placeholders never match. The result is
/// deterministic: both maps iterate in `BTreeMap` order and the
/// exactly-one rules make the outcome independent of iteration order.
fn moved_identity_bucket_remaps(
    baseline_counts: &HealthFindingCountMap,
    current_counts: &HealthFindingCountMap,
    root: &Path,
) -> Vec<(String, String)> {
    let mut candidates_by_name: FxHashMap<&str, Vec<&str>> = FxHashMap::default();
    for key in current_counts.keys() {
        if baseline_counts.contains_key(key) {
            continue;
        }
        if let Some((_, name)) = identity_bucket_parts(key)
            && !is_anonymous_function_name(name)
        {
            candidates_by_name.entry(name).or_default().push(key);
        }
    }

    let mut proposals: Vec<(&str, &str)> = Vec::new();
    let mut claims: FxHashMap<&str, usize> = FxHashMap::default();
    for key in baseline_counts.keys() {
        if current_counts.contains_key(key.as_str()) {
            continue;
        }
        let Some((path, name)) = identity_bucket_parts(key) else {
            continue;
        };
        if is_anonymous_function_name(name) || root.join(path).exists() {
            continue;
        }
        if let Some(candidates) = candidates_by_name.get(name)
            && let [only_candidate] = candidates.as_slice()
        {
            proposals.push((key.as_str(), only_candidate));
            *claims.entry(only_candidate).or_default() += 1;
        }
    }

    proposals
        .into_iter()
        .filter(|(_, candidate)| claims.get(candidate) == Some(&1))
        .map(|(old, new)| (old.to_string(), new.to_string()))
        .collect()
}

fn runtime_coverage_finding_key(
    finding: &fallow_output::RuntimeCoverageFinding,
    _root: &Path,
) -> String {
    finding
        .stable_id
        .clone()
        .unwrap_or_else(|| finding.id.clone())
}

/// Line-move-tolerant writer key: `path\0name\0source_hash`.
///
/// Returns `None` when the finding carries no `source_hash` (e.g. a 0.5-shape
/// sidecar or an un-migrated producer); such findings fall back to the
/// line-sensitive `runtime_coverage_finding_key` for suppression. The NUL
/// separator avoids collisions with paths/names that contain `:`.
fn runtime_coverage_source_hash_key(
    finding: &fallow_output::RuntimeCoverageFinding,
    root: &Path,
) -> Option<String> {
    finding.source_hash.as_deref().map(|hash| {
        format!(
            "{}\0{}\0{}",
            relative_path(&finding.path, root),
            finding.function,
            hash
        )
    })
}

pub(crate) fn filter_new_runtime_coverage_findings(
    mut findings: Vec<fallow_output::RuntimeCoverageFinding>,
    baseline: &HealthBaselineData,
    root: &Path,
) -> Vec<fallow_output::RuntimeCoverageFinding> {
    let baseline_keys: FxHashSet<&str> = baseline
        .runtime_coverage_findings
        .iter()
        .map(String::as_str)
        .collect();
    let baseline_source_hash_keys: FxHashSet<&str> = baseline
        .runtime_coverage_source_hashes
        .iter()
        .map(String::as_str)
        .collect();
    findings.retain(|finding| {
        let suppressed_by_stable_id = finding
            .stable_id
            .as_deref()
            .is_some_and(|id| baseline_keys.contains(id));
        let suppressed_by_legacy_id = baseline_keys.contains(finding.id.as_str());
        let suppressed_by_source_hash = runtime_coverage_source_hash_key(finding, root)
            .is_some_and(|key| baseline_source_hash_keys.contains(key.as_str()));
        !(suppressed_by_stable_id || suppressed_by_legacy_id || suppressed_by_source_hash)
    });
    findings
}

/// Filter refactoring targets to only include those not present in the baseline.
pub(crate) fn filter_new_health_targets(
    mut targets: Vec<fallow_output::RefactoringTarget>,
    baseline: &HealthBaselineData,
    root: &Path,
) -> Vec<fallow_output::RefactoringTarget> {
    let baseline_keys: FxHashSet<&str> = baseline.target_keys.iter().map(String::as_str).collect();
    targets.retain(|t| {
        let key = target_baseline_key(t, root);
        !baseline_keys.contains(key.as_str())
    });
    targets
}

/// Per-category delta between current results and a baseline.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CategoryDelta {
    /// Finding count in the current run.
    pub current: usize,
    /// Finding count recorded in the baseline.
    pub baseline: usize,
    /// `current - baseline`; positive means new findings appeared.
    pub delta: i64,
}

/// Deltas between current analysis results and a saved baseline.
///
/// Used in combined mode to show +/- counts in the failure summary and
/// to emit `baseline_deltas` in JSON output.
#[derive(Debug, Clone)]
pub struct BaselineDeltas {
    /// Net change in total issue count (positive = more issues).
    pub total_delta: i64,
    /// Per-category deltas keyed by category name.
    pub per_category: Vec<(String, CategoryDelta)>,
}

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