cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
//! Pattern-candidate recommendations aggregated from projectwide evidence
//! (see todo.md §16 "Rust-Pattern-Empfehlungen aus projektweiter Evidenz").
//!
//! This is deliberately **not** the `Finding`/`Report`/verdict path: a
//! [`PatternCandidate`] is a heuristic design suggestion, never a gating
//! result. Nothing in this module is wired into `evidence_class_for_rule`,
//! the health score, or a baseline verdict (todo.md §16.1 "Pattern-
//! Empfehlungen sind keine normalen Findings").
//!
//! Scope of this module (MVP slice, todo.md §16.6):
//! [`PatternCandidate`]/[`CorroboratedEvidence`] plus the five §16.3 MVP
//! aggregation rules — `stringly-error-boundary`, `primitive-domain-value`,
//! `boolean-state-cluster`, `public-invariant-bypass`, and
//! `manual-resource-lifecycle` (see [`analyze_workspace`]). The latter four
//! are listed as "Deep" tier in todo.md §16.3's rule table; the versions
//! implemented here are deliberately narrower, Fast-Tier-reachable subsets
//! of their full definitions (see each rule function's doc comment for the
//! exact narrowing). The broader `PrincipleHeuristic` type from todo.md
//! §16.7 (abstract design-principle heuristics like SRP/KISS/YAGNI) is a
//! deliberately separate, later slice and is not implemented here.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use syn::spanned::Spanned;
use syn::visit::Visit;

use crate::advisory::clippy_import::ClippyBoolParamsHit;
use crate::finding::{Finding, FindingId};
use crate::ingest::{CrateInfo, Workspace};

/// The rule id for the `stringly-error-boundary` aggregation implemented in
/// this module (see todo.md §16.3's rule table). Distinct from a
/// [`RustPattern`] — the rule is the *evidence pattern* judge looks for, the
/// pattern is the *recommendation* it emits.
pub const STRINGLY_ERROR_BOUNDARY_RULE: &str = "stringly-error-boundary";

/// The rule id for the `primitive-domain-value` aggregation implemented in
/// this module (see [`primitive_domain_value_candidates`]).
pub const PRIMITIVE_DOMAIN_VALUE_RULE: &str = "primitive-domain-value";

/// The rule id for the `boolean-state-cluster` aggregation implemented in
/// this module (see [`boolean_state_cluster_candidates`]).
pub const BOOLEAN_STATE_CLUSTER_RULE: &str = "boolean-state-cluster";

/// The rule id for the `public-invariant-bypass` aggregation implemented in
/// this module (see [`public_invariant_bypass_candidates`]).
pub const PUBLIC_INVARIANT_BYPASS_RULE: &str = "public-invariant-bypass";

/// The rule id for the `manual-resource-lifecycle` aggregation implemented in
/// this module (see [`manual_resource_lifecycle_candidates`]).
pub const MANUAL_RESOURCE_LIFECYCLE_RULE: &str = "manual-resource-lifecycle";

/// A recommended Rust design pattern (todo.md §16.2, §16.3). Exactly the enum
/// from the todo.md sketch — no additional variants.
///
/// `Deserialize` is derived alongside `Serialize` so a
/// [`crate::pattern_baseline::PatternBaseline`] JSON file can be loaded back,
/// not just saved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RustPattern {
    ValidatedNewtype,
    SmartConstructor,
    StateEnum,
    TypeState,
    Builder,
    OptionsStruct,
    RaiiGuard,
    DomainError,
    FunctionalCore,
    EncapsulatedAggregate,
}

impl RustPattern {
    /// Stable kebab-case identifier, used both for [`PatternCandidateId`]
    /// computation and TTY rendering.
    pub const fn slug(self) -> &'static str {
        match self {
            Self::ValidatedNewtype => "validated-newtype",
            Self::SmartConstructor => "smart-constructor",
            Self::StateEnum => "state-enum",
            Self::TypeState => "type-state",
            Self::Builder => "builder",
            Self::OptionsStruct => "options-struct",
            Self::RaiiGuard => "raii-guard",
            Self::DomainError => "domain-error",
            Self::FunctionalCore => "functional-core",
            Self::EncapsulatedAggregate => "encapsulated-aggregate",
        }
    }
}

impl std::fmt::Display for RustPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.slug())
    }
}

/// Where a [`PatternCandidate`] applies: a crate, and (if the evidence
/// concentrates on specific items) the qualified item paths within it.
/// Deliberately not [`crate::finding::Location`] — that type is a single
/// file/line/item anchor for a line-precise finding, while a pattern
/// candidate is crate- or module-wide by construction (todo.md §16.1: many
/// local symptoms are aggregated into one design decision, so there is no
/// single line to anchor to).
#[derive(Debug, Clone, Serialize)]
pub struct CodeScope {
    /// The crate this candidate concerns (see [`CrateInfo::name`]).
    pub krate: String,
    /// Qualified item paths the evidence concentrates on, deduplicated and
    /// sorted. Empty when the candidate concerns the crate as a whole rather
    /// than specific items.
    pub modules: Vec<String>,
}

/// A single evidenced location backing an [`Evidence`] entry — a file, and
/// (if the evidence is item-scoped rather than file-scoped) a qualified item
/// path within it.
#[derive(Debug, Clone, Serialize)]
pub struct EvidenceLocation {
    pub file: PathBuf,
    pub item_path: Option<String>,
}

/// One piece of evidence: a human-readable description of what was observed
/// (phrased as an observation, never as an absolute claim — see todo.md
/// §16.7 "Sprachdisziplin"), plus the concrete locations backing it so the
/// claim stays checkable rather than asserted.
#[derive(Debug, Clone, Serialize)]
pub struct Evidence {
    pub description: String,
    pub locations: Vec<EvidenceLocation>,
}

/// At least two independently sourced signals corroborating one
/// [`PatternCandidate`] (todo.md §16.2, §16.6: "mindestens zwei unabhängige
/// Evidenzpunkte; andernfalls wird sie standardmäßig unterdrückt"). `primary`
/// and `independent` are mandatory and must come from different detection
/// mechanisms; `additional` holds any further corroborating signal beyond
/// those two.
#[derive(Debug, Clone, Serialize)]
pub struct CorroboratedEvidence {
    pub primary: Evidence,
    pub independent: Evidence,
    pub additional: Vec<Evidence>,
}

/// A situation in which the current structure can already be justified —
/// mandatory on every [`PatternCandidate`] (todo.md §16.4 "Gegenindikationen
/// sind Pflicht").
#[derive(Debug, Clone, Serialize)]
pub struct Contraindication {
    pub description: String,
}

/// A condition the recommendation assumes holds (e.g. "several boundary
/// functions in this crate convert errors the same way").
#[derive(Debug, Clone, Serialize)]
pub struct Precondition {
    pub description: String,
}

/// One numbered step of a migration plan. Text only — no patch is generated
/// (todo.md §16.5: "liefert zunächst nur einen geordneten Migrationsplan und
/// betroffene API-/Call-Sites, noch keinen Patch"). `affected_paths` names
/// the call sites/files that step concerns, when known.
#[derive(Debug, Clone, Serialize)]
pub struct MigrationStep {
    pub step: u32,
    pub description: String,
    pub affected_paths: Vec<PathBuf>,
}

/// Stable identifier for a [`PatternCandidate`], analogous in spirit to how
/// [`FindingId`] identifies a `Finding` — but composed differently, since a
/// pattern candidate has no single file/line to anchor an id string to.
/// Deterministically hashed from `(pattern, normalized scope, sorted
/// evidence identities)` (todo.md §16.5: "stabile ID aus Pattern,
/// normalisiertem Scope und Evidenzidentitäten bilden").
///
/// Note on the hash function: the task brief for this module referenced
/// Finding ids as a `b3:`-style blake3 hash and assumed blake3 was already a
/// project dependency. Neither holds for this codebase: `Finding` ids are
/// plain descriptive `rule:file:line:column` strings (see
/// `SlopVisitor::record` in `slop.rs`), and blake3 is not in `Cargo.toml`.
/// Adding a new dependency for a single hash call isn't justified, so this
/// uses a small hand-rolled, version-independent FNV-1a hash instead of
/// either blake3 or `std::hash::DefaultHasher` (whose algorithm is
/// explicitly not guaranteed stable across Rust releases — unsuitable for an
/// id meant to stay stable across judge upgrades).
///
/// `Deserialize` is derived alongside `Serialize` so a
/// [`crate::pattern_baseline::PatternBaseline`] JSON file can be loaded back,
/// not just saved.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PatternCandidateId(String);

impl PatternCandidateId {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    fn compute(pattern: RustPattern, scope: &CodeScope, evidence_identities: &[String]) -> Self {
        let mut modules = scope.modules.clone();
        modules.sort();
        let mut identities = evidence_identities.to_vec();
        identities.sort();
        identities.dedup();
        let normalized = format!(
            "{}|{}|{}|{}",
            pattern.slug(),
            scope.krate,
            modules.join(","),
            identities.join(",")
        );
        Self(format!(
            "pattern:{}:{}",
            pattern.slug(),
            crate::finding::fnv1a_hex(&normalized)
        ))
    }
}

impl std::fmt::Display for PatternCandidateId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// A pattern recommendation aggregated from corroborated projectwide
/// evidence (todo.md §16.2). Exactly the struct from the todo.md sketch, plus
/// one deliberate omission: there is no `confidence` field. That is a type-
/// level guarantee, not a convention — nothing in this module (or anywhere
/// else) can attach `PatternCandidate` to `Finding`/`Report`/the verdict
/// path, so this aggregate can never be serialized as a gating result
/// (todo.md §16.7: "Der Typ selbst garantiert, dass diese Aussage nie als...
/// CI-Verletzung serialisiert werden kann").
#[derive(Debug, Clone, Serialize)]
pub struct PatternCandidate {
    pub id: PatternCandidateId,
    pub pattern: RustPattern,
    pub scope: CodeScope,
    pub evidence: CorroboratedEvidence,
    pub preconditions: Vec<Precondition>,
    pub contraindications: Vec<Contraindication>,
    pub migration: Vec<MigrationStep>,
    pub related_findings: Vec<FindingId>,
}

// Keeps the candidate builders focused on their domain-specific evidence and
// migration advice while preserving the stable id construction in one place.
macro_rules! pattern_candidate {
    (
        pattern: $pattern:expr,
        $scope:expr,
        $evidence_identities:expr,
        {
            evidence: $evidence:expr,
            preconditions: $preconditions:expr,
            contraindications: $contraindications:expr,
            migration: $migration:expr,
            related_findings: $related_findings:expr $(,)?
        }
    ) => {{
        let pattern = $pattern;
        let scope = $scope;
        let evidence_identities = $evidence_identities;
        PatternCandidate {
            id: PatternCandidateId::compute(pattern, &scope, &evidence_identities),
            pattern,
            scope,
            evidence: $evidence,
            preconditions: $preconditions,
            contraindications: $contraindications,
            migration: $migration,
            related_findings: $related_findings,
        }
    }};
}

/// Runs every implemented pattern-aggregation rule over `workspace` and
/// `findings` (the combined output of `judge::rules::slop::analyze_workspace`, or
/// any superset of it): `stringly-error-boundary`, `primitive-domain-value`,
/// `boolean-state-cluster`, `public-invariant-bypass`, and
/// `manual-resource-lifecycle` — this is the dispatch point future rules
/// from todo.md §16.3 attach to.
pub fn analyze_workspace(workspace: &Workspace, findings: &[Finding]) -> Vec<PatternCandidate> {
    analyze_workspace_with_clippy(workspace, findings, &[])
}

/// Same as [`analyze_workspace`], plus `clippy_hits` — parsed
/// `clippy::fn_params_excessive_bools` results (see
/// [`crate::advisory::clippy_import::read_clippy_report`]) that
/// [`boolean_state_cluster_candidates`] uses as optional, additive
/// corroborating evidence. Passing an empty slice is exactly
/// [`analyze_workspace`]'s behavior — the clippy import is fully opt-in.
pub fn analyze_workspace_with_clippy(
    workspace: &Workspace,
    findings: &[Finding],
    clippy_hits: &[ClippyBoolParamsHit],
) -> Vec<PatternCandidate> {
    let mut candidates = stringly_error_boundary_candidates(workspace, findings);
    candidates.extend(primitive_domain_value_candidates(workspace));
    candidates.extend(boolean_state_cluster_candidates(workspace, clippy_hits));
    candidates.extend(public_invariant_bypass_candidates(workspace));
    candidates.extend(manual_resource_lifecycle_candidates(workspace));
    candidates
}

/// `stringly-error-boundary` (todo.md §16.3): concrete errors are converted
/// to `String`/context-free collectors at module/crate boundaries, while the
/// crate already has the raw material for a proper domain error. Requires
/// two independent signals per crate (todo.md §16.6's "mindestens zwei
/// unabhängige Evidenzpunkte", refined further by this rule's own brief:
/// signal 1 alone additionally needs at least two occurrences to count as a
/// pattern rather than a one-off):
///
/// 1. **Primary** — at least two `catch-all-error` findings within the same
///    crate (a syntax fact judge already computes; see `crate::rules::slop`).
/// 2. **Independent** — the same crate already defines at least one typed
///    error (an enum with `Error` in its name, an item carrying an
///    `Error`-suffixed derive such as `#[derive(thiserror::Error)]`, or an
///    `impl ... Error for ...`) — a structural-availability fact, not a
///    syntax-frequency one.
///
/// Only crates satisfying both produce a candidate — exactly one per crate,
/// referencing every contributing `catch-all-error` finding.
fn stringly_error_boundary_candidates(
    workspace: &Workspace,
    findings: &[Finding],
) -> Vec<PatternCandidate> {
    let mut by_crate: BTreeMap<&str, Vec<&Finding>> = BTreeMap::new();
    for finding in findings {
        if finding.rule.as_str() != crate::rules::slop::CATCH_ALL_ERROR_RULE {
            continue;
        }
        let Some(krate) = crate_for_file(workspace, &finding.location.file) else {
            continue;
        };
        by_crate
            .entry(krate.name.as_str())
            .or_default()
            .push(finding);
    }

    let mut candidates = Vec::new();
    for (krate_name, crate_findings) in by_crate {
        if crate_findings.len() < 2 {
            continue;
        }
        let Some(krate) = workspace.crates.iter().find(|k| k.name == krate_name) else {
            continue;
        };
        let Some(independent) = crate_defines_typed_error(krate) else {
            continue;
        };
        candidates.push(build_candidate(krate, &crate_findings, independent));
    }
    candidates
}

/// The crate a source file belongs to, matched against each crate's known
/// source-file list (populated by `judge::ingest::load`).
fn crate_for_file<'a>(workspace: &'a Workspace, file: &Path) -> Option<&'a CrateInfo> {
    workspace
        .crates
        .iter()
        .find(|krate| krate.source_files.iter().any(|source| source.path == file))
}

/// Reads and parses every source file in `krate` with `syn`, calling `visit`
/// with each file's path and parsed AST. A file that fails to read or parse
/// is silently skipped rather than surfaced as an analyzer error — every
/// rule in this module treats its `syn`-derived facts as best-effort
/// corroborating evidence, not ground truth, so skipping an unreadable file
/// just means one less place a signal could have come from. Shared by every
/// per-crate rule below instead of each repeating the same read/parse/skip
/// loop.
fn for_each_parsed_source(krate: &CrateInfo, mut visit: impl FnMut(&Path, &syn::File)) {
    for source in &krate.source_files {
        let Ok(text) = std::fs::read_to_string(&source.path) else {
            continue;
        };
        let Ok(ast) = syn::parse_file(&text) else {
            continue;
        };
        visit(&source.path, &ast);
    }
}

impl EvidenceLocation {
    /// An evidence location with a known item path — the shape every
    /// `build_X_candidate`/visitor in this module constructs once it has
    /// both a file and a qualified item path (as opposed to a file-only
    /// location, which uses the struct literal directly with `item_path:
    /// None`).
    fn new(file: PathBuf, item_path: impl Into<String>) -> Self {
        Self {
            file,
            item_path: Some(item_path.into()),
        }
    }
}

/// Sorts `locations` by `(file, item_path)` — the ordering discipline every
/// `build_X_candidate` applies to its evidence locations so output stays
/// deterministic across runs.
fn sort_evidence_locations(locations: &mut [EvidenceLocation]) {
    locations.sort_by(|a, b| (&a.file, &a.item_path).cmp(&(&b.file, &b.item_path)));
}

/// A [`CodeScope`] for `krate` with `modules` sorted and deduplicated — the
/// scope-construction step every crate-scoped `build_X_candidate` performs
/// before filling in its own evidence-specific fields.
fn crate_scope(krate: &CrateInfo, mut modules: Vec<String>) -> CodeScope {
    modules.sort();
    modules.dedup();
    CodeScope {
        krate: krate.name.clone(),
        modules,
    }
}

impl CorroboratedEvidence {
    /// Corroborated evidence with no additional (beyond primary/independent)
    /// signal yet — every `build_X_candidate` in this module starts here;
    /// some (e.g. [`boolean_state_cluster_candidates`]) push a further
    /// `Evidence` onto `additional` afterwards.
    fn new(primary: Evidence, independent: Evidence) -> Self {
        Self {
            primary,
            independent,
            additional: Vec::new(),
        }
    }
}

/// Evidence identities in the `"file:item_path"` shape
/// [`PatternCandidateId::compute`] hashes over, one per location.
fn location_identities(locations: &[EvidenceLocation]) -> Vec<String> {
    locations
        .iter()
        .map(|location| {
            format!(
                "{}:{}",
                location.file.display(),
                location.item_path.as_deref().unwrap_or("")
            )
        })
        .collect()
}

/// The qualified item path for a function found while visiting: `Self::name`
/// inside an `impl` block (using the block's resolved self type), or just
/// `name` for a free function. Shared by every pattern visitor that tracks
/// `self_type` while walking `impl` blocks (see
/// `visit_item_impl_with_self_type!`).
fn qualified_item_path(self_type: Option<&str>, name: &str) -> String {
    match self_type {
        Some(self_type) => format!("{self_type}::{name}"),
        None => name.to_string(),
    }
}

/// The `(name, type)` of `input` if it's a `pat: Type`-shaped typed argument
/// with a plain identifier pattern (not `self`, not a destructuring
/// pattern) — the common shape every pattern visitor here extracts function
/// parameters through, whether it goes on to check the type
/// ([`primitive_type_name`]/[`is_bool_type`]) or just needs the name.
fn typed_ident_arg(input: &syn::FnArg) -> Option<(String, &syn::Type)> {
    let syn::FnArg::Typed(pat_type) = input else {
        return None;
    };
    let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
        return None;
    };
    Some((pat_ident.ident.to_string(), &pat_type.ty))
}

/// Whether `node` is an `impl <trait> for ...` block whose trait path's last
/// segment is `ident` (matched structurally, no type resolution — same
/// caveat as [`primitive_type_name`]).
fn impl_trait_is(node: &syn::ItemImpl, ident: &str) -> bool {
    node.trait_.as_ref().is_some_and(|(_, path, _)| {
        path.segments
            .last()
            .is_some_and(|segment| segment.ident == ident)
    })
}

fn build_candidate(
    krate: &CrateInfo,
    crate_findings: &[&Finding],
    independent: Evidence,
) -> PatternCandidate {
    let mut related_findings: Vec<FindingId> = crate_findings
        .iter()
        .map(|finding| finding.id.clone())
        .collect();
    related_findings.sort_by(|a, b| a.as_str().cmp(b.as_str()));

    let modules: Vec<String> = crate_findings
        .iter()
        .map(|finding| finding.location.item_path.clone())
        .collect();
    let scope = crate_scope(krate, modules);

    let mut primary_locations: Vec<EvidenceLocation> = crate_findings
        .iter()
        .map(|finding| {
            EvidenceLocation::new(
                finding.location.file.clone(),
                finding.location.item_path.clone(),
            )
        })
        .collect();
    sort_evidence_locations(&mut primary_locations);

    let mut affected_paths: Vec<PathBuf> = crate_findings
        .iter()
        .map(|finding| finding.location.file.clone())
        .collect();
    affected_paths.sort();
    affected_paths.dedup();

    let primary = Evidence {
        description: format!(
            "{} `catch-all-error` finding(s) in crate `{}` convert concrete errors to \
             `String`/`Box<dyn Error>`/context-free collectors at public boundaries.",
            crate_findings.len(),
            krate.name
        ),
        locations: primary_locations,
    };

    let evidence_identities: Vec<String> = related_findings
        .iter()
        .map(|id| id.as_str().to_string())
        .collect();

    pattern_candidate! {
        pattern: RustPattern::DomainError,
        scope,
        evidence_identities,
        {
        evidence: CorroboratedEvidence::new(primary, independent),
        preconditions: vec![Precondition {
            description: format!(
                "Mehrere Boundary-Funktionen in Crate `{}` wandeln unterschiedliche \
                 Fehlerquellen an derselben Grenze in `anyhow`/`Box<dyn Error>`/`String` um.",
                krate.name
            ),
        }],
        contraindications: vec![
            Contraindication {
                description: "Die Grenze kann bewusst ein Kompatibilitäts-Shim sein, der \
                    verschiedene Fehlerquellen absichtlich vereinheitlicht."
                    .to_string(),
            },
            Contraindication {
                description: "Ein zusätzliches Domain-Error-Enum kann bei sehr wenigen \
                    Aufrufstellen mehr Boilerplate als Nutzen erzeugen."
                    .to_string(),
            },
        ],
        migration: vec![
            MigrationStep {
                step: 1,
                description: "Gemeinsame Fehlerquellen an dieser Grenze identifizieren."
                    .to_string(),
                affected_paths: affected_paths.clone(),
            },
            MigrationStep {
                step: 2,
                description: "Domain-Error-Enum mit einer Variante pro Quelle entwerfen."
                    .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 3,
                description: "`From`-Impls für die Quellfehler ergänzen.".to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 4,
                description: "Boundary-Funktionen auf das neue Enum umstellen und `?` statt \
                    manueller Konvertierung nutzen."
                    .to_string(),
                affected_paths,
            },
        ],
            related_findings: related_findings,
        }
    }
}

/// Whether `krate` already defines at least one typed error (see
/// [`stringly_error_boundary_candidates`]'s signal 2). Reads and parses every
/// source file in the crate with `syn`; a file that fails to read or parse
/// is silently skipped rather than surfaced as an analyzer error — this is a
/// best-effort corroborating signal, not the primary evidence, and skipping
/// an unreadable file just means one less place this signal could have come
/// from.
fn crate_defines_typed_error(krate: &CrateInfo) -> Option<Evidence> {
    let mut hits = Vec::new();
    for_each_parsed_source(krate, |file, ast| {
        let mut visitor = TypedErrorVisitor {
            file,
            path: Vec::new(),
            hits: Vec::new(),
        };
        visitor.visit_file(ast);
        hits.append(&mut visitor.hits);
    });
    if hits.is_empty() {
        return None;
    }
    hits.sort_by(|a, b| (&a.file, &a.item_path).cmp(&(&b.file, &b.item_path)));
    Some(Evidence {
        description: format!(
            "Crate `{}` already defines {} typed error item(s) in its own source (an enum with \
             `Error` in its name, an `Error`-deriving item, or an `impl ... Error for ...`) — \
             the raw material for a domain error already exists in this crate.",
            krate.name,
            hits.len()
        ),
        locations: hits,
    })
}

/// Collects candidate typed-error item locations: `enum`s named `*Error*`,
/// any item carrying a derive ending in `Error` (covers
/// `#[derive(thiserror::Error)]` without depending on the `thiserror` crate
/// itself), and `impl ... Error for ...` blocks.
struct TypedErrorVisitor<'a> {
    file: &'a Path,
    path: Vec<String>,
    hits: Vec<EvidenceLocation>,
}

impl TypedErrorVisitor<'_> {
    fn current_item_path(&self) -> String {
        crate::functions::qualified_item_path(self.file, &self.path)
    }

    fn record(&mut self) {
        self.hits.push(EvidenceLocation::new(
            self.file.to_path_buf(),
            self.current_item_path(),
        ));
    }
}

impl<'ast> Visit<'ast> for TypedErrorVisitor<'_> {
    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
        self.path.push(node.ident.to_string());
        if node.ident.to_string().contains("Error") || has_derive_ending_in(&node.attrs, "Error") {
            self.record();
        }
        syn::visit::visit_item_enum(self, node);
        self.path.pop();
    }

    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
        self.path.push(node.ident.to_string());
        if has_derive_ending_in(&node.attrs, "Error") {
            self.record();
        }
        syn::visit::visit_item_struct(self, node);
        self.path.pop();
    }

    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
        use quote::ToTokens;
        self.path.push(node.self_ty.to_token_stream().to_string());
        if impl_trait_is(node, "Error") {
            self.record();
        }
        syn::visit::visit_item_impl(self, node);
        self.path.pop();
    }
}

/// Whether any `#[derive(...)]` attribute in `attrs` lists a path ending in
/// `ident` (e.g. `#[derive(thiserror::Error)]` for `ident == "Error"`).
fn has_derive_ending_in(attrs: &[syn::Attribute], ident: &str) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("derive") {
            return false;
        }
        let syn::Meta::List(list) = &attr.meta else {
            return false;
        };
        list.parse_args_with(
            syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated,
        )
        .is_ok_and(|paths| {
            paths.iter().any(|path| {
                path.segments
                    .last()
                    .is_some_and(|segment| segment.ident == ident)
            })
        })
    })
}

/// `primitive-domain-value` (todo.md §16.3): the same primitive value is
/// validated identically at several boundaries, or only ever used within a
/// restricted range.
///
/// **This is a deliberately narrower, Fast-Tier-reachable subset of the full
/// rule from todo.md §16.3** (which is listed there as "Deep" tier). The
/// full rule can reason about validation performed anywhere a value flows,
/// across crates, and via non-syntactic evidence (e.g. Deep-Tier semantic
/// analysis of call sites). This implementation only looks at:
///
/// 1. **Primary** — the same (parameter name, type) pair appears as a
///    parameter in at least two *different* `pub fn` signatures within the
///    *same crate*. Types are restricted to `u8`/`u16`/`u32`/`u64`/`usize`/
///    `i8`/`i16`/`i32`/`i64`/`isize`/`f32`/`f64`/`String`/`&str` (`bool` is
///    deliberately excluded — that is [`boolean_state_cluster_candidates`]'s
///    domain, not this rule's).
/// 2. **Independent** — at least one of those signatures has a validation
///    guard referencing the parameter within the function body: an `if`
///    whose condition references the parameter and whose then-branch
///    returns `Err(...)` or calls `panic!(...)`, or an `assert!(...)` whose
///    arguments reference the parameter.
///
/// Only (crate, parameter name, type) tuples satisfying both produce a
/// candidate — exactly one per tuple, referencing every contributing
/// signature.
fn primitive_domain_value_candidates(workspace: &Workspace) -> Vec<PatternCandidate> {
    let mut candidates = Vec::new();
    for krate in &workspace.crates {
        let mut facts: Vec<SignatureParamFact> = Vec::new();
        for_each_parsed_source(krate, |file, ast| {
            let mut visitor = PrimitiveDomainValueVisitor {
                file,
                self_type: None,
                facts: Vec::new(),
            };
            visitor.visit_file(ast);
            facts.append(&mut visitor.facts);
        });

        let mut by_param: BTreeMap<(String, String), Vec<SignatureParamFact>> = BTreeMap::new();
        for fact in facts {
            by_param
                .entry((fact.param.clone(), fact.type_name.clone()))
                .or_default()
                .push(fact);
        }

        for ((param, type_name), group) in by_param {
            if group.len() < 2 {
                continue;
            }
            if !group.iter().any(|fact| fact.has_guard) {
                continue;
            }
            candidates.push(build_primitive_domain_value_candidate(
                krate, &param, &type_name, &group,
            ));
        }
    }
    candidates
}

/// One `pub fn` parameter matching [`primitive_domain_value_candidates`]'s
/// type restriction, plus whether the function body guards it.
struct SignatureParamFact {
    file: PathBuf,
    item_path: String,
    param: String,
    type_name: String,
    has_guard: bool,
}

fn build_primitive_domain_value_candidate(
    krate: &CrateInfo,
    param: &str,
    type_name: &str,
    group: &[SignatureParamFact],
) -> PatternCandidate {
    let modules: Vec<String> = group.iter().map(|fact| fact.item_path.clone()).collect();
    let scope = crate_scope(krate, modules);

    let mut primary_locations: Vec<EvidenceLocation> = group
        .iter()
        .map(|fact| EvidenceLocation::new(fact.file.clone(), fact.item_path.clone()))
        .collect();
    sort_evidence_locations(&mut primary_locations);

    let mut guard_locations: Vec<EvidenceLocation> = group
        .iter()
        .filter(|fact| fact.has_guard)
        .map(|fact| EvidenceLocation::new(fact.file.clone(), fact.item_path.clone()))
        .collect();
    sort_evidence_locations(&mut guard_locations);

    let primary = Evidence {
        description: format!(
            "Parameter `{param}: {type_name}` appears with the same name and type in {} `pub \
             fn` signature(s) in crate `{}`.",
            group.len(),
            krate.name
        ),
        locations: primary_locations,
    };
    let independent = Evidence {
        description: format!(
            "At least one of these signatures guards `{param}` with an early error/panic path \
             referencing the parameter (`if` + `return Err(...)`, `if` + `panic!(...)`, or \
             `assert!(...)`)."
        ),
        locations: guard_locations,
    };

    let evidence_identities: Vec<String> = location_identities(&primary.locations);
    let mut affected_paths: Vec<PathBuf> = group.iter().map(|fact| fact.file.clone()).collect();
    affected_paths.sort();
    affected_paths.dedup();

    pattern_candidate! {
        pattern: RustPattern::ValidatedNewtype,
        scope,
        evidence_identities,
        {
        evidence: CorroboratedEvidence::new(primary, independent),
        preconditions: vec![Precondition {
            description: format!(
                "Crate `{}` verwendet `{param}: {type_name}` wiederholt als Parametername/-typ, \
                 und mindestens eine Fundstelle validiert den Wertebereich explizit.",
                krate.name
            ),
        }],
        contraindications: vec![
            Contraindication {
                description: "Der Parametername kann in verschiedenen Funktionen tatsächlich \
                    unterschiedliche Bedeutungen haben, auch wenn Name und Typ übereinstimmen."
                    .to_string(),
            },
            Contraindication {
                description: "Bei nur einer Validierungsstelle könnte ein Newtype mehr \
                    Boilerplate als Nutzen erzeugen, falls die übrigen Aufrufstellen den Wert nie \
                    direkt validieren müssen."
                    .to_string(),
            },
        ],
        migration: vec![
            MigrationStep {
                step: 1,
                description: "Newtype für den Wertebereich definieren.".to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 2,
                description: "`TryFrom<...>` mit der gefundenen Validierungslogik implementieren."
                    .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 3,
                description: "Betroffene Signaturen schrittweise auf den Newtype umstellen."
                    .to_string(),
                affected_paths: affected_paths.clone(),
            },
            MigrationStep {
                step: 4,
                description: "Call-Sites anpassen.".to_string(),
                affected_paths,
            },
        ],
            related_findings: Vec::new(),
        }
    }
}

/// Whether `ty` is one of [`primitive_domain_value_candidates`]'s allowed
/// primitive types (`u8`.."f64"`, `String`, `&str`), matched structurally by
/// the type path's last segment — no type resolution, so a local type alias
/// named e.g. `type String = Foo;` would produce a false positive. This is
/// an accepted Fast-Tier limitation, same in spirit as `crate_for_file`'s
/// path-based crate matching above.
fn primitive_type_name(ty: &syn::Type) -> Option<String> {
    const NUMERIC: &[&str] = &[
        "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", "f32", "f64",
    ];
    match ty {
        syn::Type::Path(type_path) if type_path.qself.is_none() => {
            let segment = type_path.path.segments.last()?;
            if !matches!(segment.arguments, syn::PathArguments::None) {
                return None;
            }
            let name = segment.ident.to_string();
            if NUMERIC.contains(&name.as_str()) || name == "String" {
                Some(name)
            } else {
                None
            }
        }
        syn::Type::Reference(type_ref) => match &*type_ref.elem {
            syn::Type::Path(type_path) if type_path.qself.is_none() => {
                let segment = type_path.path.segments.last()?;
                if matches!(segment.arguments, syn::PathArguments::None) && segment.ident == "str" {
                    Some("&str".to_string())
                } else {
                    None
                }
            }
            _ => None,
        },
        _ => None,
    }
}

/// Collects [`SignatureParamFact`]s from `pub fn` items (free functions and
/// `impl` methods) in one source file.
struct PrimitiveDomainValueVisitor<'a> {
    file: &'a Path,
    self_type: Option<String>,
    facts: Vec<SignatureParamFact>,
}

/// Reuses the shared `self_type` stack discipline across pattern visitors
/// that need qualified inherent-method names.
macro_rules! visit_item_impl_with_self_type {
    () => {
        fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
            use quote::ToTokens;
            let previous = self
                .self_type
                .replace(node.self_ty.to_token_stream().to_string());
            syn::visit::visit_item_impl(self, node);
            self.self_type = previous;
        }
    };
}

/// Shared `visit_item_fn`/`visit_impl_item_fn` pair for pattern visitors
/// that only record `pub fn`s and delegate to a `record_fn(name, sig,
/// block)` method — used by [`PrimitiveDomainValueVisitor`] and
/// [`ConstructorVisitor`].
macro_rules! visit_pub_fns_via_record_fn {
    () => {
        fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
            if matches!(node.vis, syn::Visibility::Public(_)) {
                self.record_fn(&node.sig.ident.to_string(), &node.sig, &node.block);
            }
            syn::visit::visit_item_fn(self, node);
        }

        fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
            if matches!(node.vis, syn::Visibility::Public(_)) {
                self.record_fn(&node.sig.ident.to_string(), &node.sig, &node.block);
            }
            syn::visit::visit_impl_item_fn(self, node);
        }
    };
}

impl PrimitiveDomainValueVisitor<'_> {
    fn record_fn(&mut self, name: &str, sig: &syn::Signature, block: &syn::Block) {
        let item_path = qualified_item_path(self.self_type.as_deref(), name);
        for input in &sig.inputs {
            let Some((param, ty)) = typed_ident_arg(input) else {
                continue;
            };
            let Some(type_name) = primitive_type_name(ty) else {
                continue;
            };
            let has_guard = body_has_validation_guard_for(block, &param);
            self.facts.push(SignatureParamFact {
                file: self.file.to_path_buf(),
                item_path: item_path.clone(),
                param,
                type_name,
                has_guard,
            });
        }
    }
}

impl<'ast> Visit<'ast> for PrimitiveDomainValueVisitor<'_> {
    visit_pub_fns_via_record_fn!();
    visit_item_impl_with_self_type!();
}

/// Whether `expr` references identifier `ident` anywhere within it (used to
/// check that a validation guard's condition actually mentions the
/// parameter in question, not just any `if`/`assert!`).
fn expr_references_ident(expr: &syn::Expr, ident: &str) -> bool {
    struct Finder<'a> {
        ident: &'a str,
        found: bool,
    }
    impl<'ast> Visit<'ast> for Finder<'_> {
        fn visit_expr_path(&mut self, node: &'ast syn::ExprPath) {
            if node.path.is_ident(self.ident) {
                self.found = true;
            }
            syn::visit::visit_expr_path(self, node);
        }
    }
    let mut finder = Finder {
        ident,
        found: false,
    };
    finder.visit_expr(expr);
    finder.found
}

/// Whether `tokens` contains identifier `ident` as a token anywhere,
/// including inside nested groups (used for `assert!(...)` macro arguments,
/// which `syn` only exposes as an opaque `TokenStream`).
fn tokens_reference_ident(tokens: &proc_macro2::TokenStream, ident: &str) -> bool {
    tokens.clone().into_iter().any(|tree| match tree {
        proc_macro2::TokenTree::Ident(node) => node == ident,
        proc_macro2::TokenTree::Group(group) => tokens_reference_ident(&group.stream(), ident),
        _ => false,
    })
}

/// Whether `block` contains a `return Err(...)` or a `panic!(...)` call
/// anywhere within it (used as the then-branch check for an `if`-shaped
/// validation guard).
fn block_leads_to_error_path(block: &syn::Block) -> bool {
    struct Finder {
        found: bool,
    }
    impl<'ast> Visit<'ast> for Finder {
        fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
            if node.expr.as_deref().is_some_and(is_err_call) {
                self.found = true;
            }
            syn::visit::visit_expr_return(self, node);
        }

        fn visit_macro(&mut self, node: &'ast syn::Macro) {
            if node.path.is_ident("panic") {
                self.found = true;
            }
            syn::visit::visit_macro(self, node);
        }
    }
    let mut finder = Finder { found: false };
    finder.visit_block(block);
    finder.found
}

/// Whether `expr` is a call whose callee path ends in the segment `Err`
/// (covers both bare `Err(...)` and a qualified `Result::Err(...)`).
fn is_err_call(expr: &syn::Expr) -> bool {
    match expr {
        syn::Expr::Call(call) => matches!(
            call.func.as_ref(),
            syn::Expr::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "Err")
        ),
        _ => false,
    }
}

/// Whether `block` (a function body) contains a validation guard for
/// `param` — see [`primitive_domain_value_candidates`]'s signal 2.
fn body_has_validation_guard_for(block: &syn::Block, param: &str) -> bool {
    struct GuardVisitor<'a> {
        param: &'a str,
        found: bool,
    }
    impl<'ast> Visit<'ast> for GuardVisitor<'_> {
        fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
            if expr_references_ident(&node.cond, self.param)
                && block_leads_to_error_path(&node.then_branch)
            {
                self.found = true;
            }
            syn::visit::visit_expr_if(self, node);
        }

        fn visit_macro(&mut self, node: &'ast syn::Macro) {
            if node.path.is_ident("assert") && tokens_reference_ident(&node.tokens, self.param) {
                self.found = true;
            }
            syn::visit::visit_macro(self, node);
        }
    }
    let mut visitor = GuardVisitor {
        param,
        found: false,
    };
    visitor.visit_block(block);
    visitor.found
}

/// `boolean-state-cluster` (todo.md §16.3): several bool values are passed
/// around together; combinations of them are checked or guarded against
/// repeatedly.
///
/// **This is a deliberately narrower, Fast-Tier-reachable subset of the full
/// rule from todo.md §16.3** (which is listed there as "Deep" tier), and it
/// is scoped to a single function rather than cross-call-site — the full
/// rule can aggregate evidence about how bool parameters are combined
/// *across* call sites; this implementation only looks within one function
/// body:
///
/// 1. **Primary** — a `fn`/`pub fn` (including a `pub fn new` constructor)
///    has at least three `bool`-typed parameters.
/// 2. **Independent** — the function body contains a condition or `match`
///    that combines at least two of those bool parameters together in one
///    condition (e.g. `if a && b`, `if a && !b`, `match (a, b) { ... }`,
///    `if a || b`) — evidence that combinations are actually checked, not
///    just that several bools happen to be parameters.
///
/// Only functions satisfying both produce a candidate — exactly one per
/// function, scoped to that function rather than the whole crate (unlike
/// `primitive-domain-value`, since the finding here is local to one
/// function).
///
/// `clippy_hits` (optional, see [`crate::advisory::clippy_import`]) never creates a
/// candidate on its own — only the two signals above can do that. When a
/// function already produces a candidate and a
/// `clippy::fn_params_excessive_bools` hit independently matches the same
/// function (same file, overlapping line range — see
/// [`clippy_hit_matches_fact`]), it is added as a third, purely additive
/// [`Evidence`] entry (todo.md §16: "mehrere `fn_params_excessive_bools`-
/// Fundstellen als Signal").
fn boolean_state_cluster_candidates(
    workspace: &Workspace,
    clippy_hits: &[ClippyBoolParamsHit],
) -> Vec<PatternCandidate> {
    let mut candidates = Vec::new();
    for krate in &workspace.crates {
        for_each_parsed_source(krate, |file, ast| {
            let mut visitor = BooleanStateClusterVisitor {
                file,
                self_type: None,
                facts: Vec::new(),
            };
            visitor.visit_file(ast);
            for fact in visitor.facts {
                let mut candidate = build_boolean_state_cluster_candidate(krate, &fact);
                if let Some(hit) = clippy_hits
                    .iter()
                    .find(|hit| clippy_hit_matches_fact(&workspace.root, hit, &fact))
                {
                    candidate.evidence.additional.push(Evidence {
                        description: format!(
                            "`clippy::fn_params_excessive_bools` independently flagged \
                             `{}`'s parameter list (lines {}-{}), corroborating this from a \
                             separate tool.",
                            fact.item_path, hit.line_start, hit.line_end
                        ),
                        locations: vec![EvidenceLocation::new(
                            fact.file.clone(),
                            fact.item_path.clone(),
                        )],
                    });
                }
                candidates.push(candidate);
            }
        });
    }
    candidates
}

/// Whether a `clippy::fn_params_excessive_bools` hit corroborates `fact`:
/// same file, normalized relative to `workspace_root` (clippy's
/// `file_name` is relative to the directory `cargo clippy` was invoked in,
/// typically the workspace root, mirroring
/// [`crate::advisory::coverage::parse_lcov`]'s `SF:`-path normalization), and an
/// overlapping line range — clippy's span may cover just the parameter
/// list while `fact`'s span covers the whole item, so overlap (not
/// equality) is what proves they're the same function.
fn clippy_hit_matches_fact(
    workspace_root: &Path,
    hit: &ClippyBoolParamsHit,
    fact: &BoolClusterFact,
) -> bool {
    let fact_relative = fact.file.strip_prefix(workspace_root).unwrap_or(&fact.file);
    let hit_normalized: PathBuf = hit
        .file
        .components()
        .filter(|component| !matches!(component, std::path::Component::CurDir))
        .collect();
    fact_relative == hit_normalized
        && fact.line_start <= hit.line_end
        && hit.line_start <= fact.line_end
}

/// One function whose signature/body satisfy both
/// [`boolean_state_cluster_candidates`] signals.
struct BoolClusterFact {
    file: PathBuf,
    item_path: String,
    bool_params: BTreeSet<String>,
    combo_hits: Vec<String>,
    line_start: usize,
    line_end: usize,
}

fn build_boolean_state_cluster_candidate(
    krate: &CrateInfo,
    fact: &BoolClusterFact,
) -> PatternCandidate {
    let scope = crate_scope(krate, vec![fact.item_path.clone()]);

    let location = EvidenceLocation::new(fact.file.clone(), fact.item_path.clone());

    let bool_params: Vec<&String> = fact.bool_params.iter().collect();
    let primary = Evidence {
        description: format!(
            "`{}` has {} `bool`-typed parameters: {}.",
            fact.item_path,
            fact.bool_params.len(),
            bool_params
                .iter()
                .map(|name| name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ),
        locations: vec![location.clone()],
    };
    let independent = Evidence {
        description: format!(
            "The function body combines at least two of these bool parameters together in a \
             condition, e.g. `{}`.",
            fact.combo_hits.join("`, `")
        ),
        locations: vec![location],
    };

    let evidence_identities: Vec<String> = std::iter::once(fact.item_path.clone())
        .chain(fact.bool_params.iter().cloned())
        .chain(fact.combo_hits.iter().cloned())
        .collect();
    pattern_candidate! {
        pattern: RustPattern::OptionsStruct,
        scope,
        evidence_identities,
        {
        evidence: CorroboratedEvidence::new(primary, independent),
        preconditions: vec![Precondition {
            description: format!(
                "`{}` nimmt mehrere Bool-Parameter entgegen und prüft mindestens eine \
                 Kombination davon gemeinsam im Funktionskörper.",
                fact.item_path
            ),
        }],
        contraindications: vec![
            Contraindication {
                description: "Wenige, klar benannte, unabhängig verwendete Bool-Flags können \
                    lesbarer sein als ein zusätzlicher Enum-/Options-Typ."
                    .to_string(),
            },
            Contraindication {
                description: "Wenn die Kombinationsprüfung nur eine einmalige \
                    Eingabevalidierung ist (kein wiederholtes Muster), kann ein zusätzlicher Typ \
                    Overkill sein."
                    .to_string(),
            },
        ],
        migration: vec![
            MigrationStep {
                step: 1,
                description: "Gültige Optionen/Zustände benennen (Options-Struct vs. \
                    Zustands-Enum, je nach Anzahl gültiger Kombinationen)."
                    .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 2,
                description: "Den gewählten Typ definieren.".to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 3,
                description: "Konstruktor-/Funktionsparameterliste ersetzen.".to_string(),
                affected_paths: vec![fact.file.clone()],
            },
            MigrationStep {
                step: 4,
                description: "Call-Sites aktualisieren.".to_string(),
                affected_paths: vec![fact.file.clone()],
            },
        ],
            related_findings: Vec::new(),
        }
    }
}

/// Whether `ty` is `bool`, matched structurally (same caveat as
/// [`primitive_type_name`]: no type resolution).
fn is_bool_type(ty: &syn::Type) -> bool {
    matches!(
        ty,
        syn::Type::Path(type_path)
            if type_path.qself.is_none()
                && type_path.path.segments.last().is_some_and(|segment| {
                    segment.ident == "bool" && matches!(segment.arguments, syn::PathArguments::None)
                })
    )
}

/// Collects [`BoolClusterFact`]s from `fn` items (free functions and `impl`
/// methods, any visibility) in one source file.
struct BooleanStateClusterVisitor<'a> {
    file: &'a Path,
    self_type: Option<String>,
    facts: Vec<BoolClusterFact>,
}

impl BooleanStateClusterVisitor<'_> {
    fn record_fn(
        &mut self,
        name: &str,
        sig: &syn::Signature,
        block: &syn::Block,
        span: proc_macro2::Span,
    ) {
        let item_path = qualified_item_path(self.self_type.as_deref(), name);
        let bool_params: BTreeSet<String> = sig
            .inputs
            .iter()
            .filter_map(|input| {
                let (name, ty) = typed_ident_arg(input)?;
                is_bool_type(ty).then_some(name)
            })
            .collect();
        if bool_params.len() < 3 {
            return;
        }
        let combo_hits = body_boolean_combo_hits(block, &bool_params);
        if combo_hits.is_empty() {
            return;
        }
        self.facts.push(BoolClusterFact {
            file: self.file.to_path_buf(),
            item_path,
            bool_params,
            combo_hits,
            line_start: span.start().line,
            line_end: span.end().line,
        });
    }
}

impl<'ast> Visit<'ast> for BooleanStateClusterVisitor<'_> {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        self.record_fn(
            &node.sig.ident.to_string(),
            &node.sig,
            &node.block,
            node.span(),
        );
        syn::visit::visit_item_fn(self, node);
    }

    visit_item_impl_with_self_type!();

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        self.record_fn(
            &node.sig.ident.to_string(),
            &node.sig,
            &node.block,
            node.span(),
        );
        syn::visit::visit_impl_item_fn(self, node);
    }
}

/// The subset of `params` referenced anywhere within `expr` (used to check
/// how many distinct bool parameters a condition/match-scrutinee combines).
fn referenced_params_in_expr(expr: &syn::Expr, params: &BTreeSet<String>) -> BTreeSet<String> {
    struct Collector<'a> {
        params: &'a BTreeSet<String>,
        found: BTreeSet<String>,
    }
    impl<'ast> Visit<'ast> for Collector<'_> {
        fn visit_expr_path(&mut self, node: &'ast syn::ExprPath) {
            if let Some(ident) = node.path.get_ident() {
                let name = ident.to_string();
                if self.params.contains(&name) {
                    self.found.insert(name);
                }
            }
            syn::visit::visit_expr_path(self, node);
        }
    }
    let mut collector = Collector {
        params,
        found: BTreeSet::new(),
    };
    collector.visit_expr(expr);
    collector.found
}

/// Rendered source text of every `if`/`match` in `block` whose
/// condition/scrutinee combines at least two of `bool_params` — see
/// [`boolean_state_cluster_candidates`]'s signal 2.
fn body_boolean_combo_hits(block: &syn::Block, bool_params: &BTreeSet<String>) -> Vec<String> {
    use quote::ToTokens;

    struct ComboVisitor<'a> {
        bool_params: &'a BTreeSet<String>,
        hits: Vec<String>,
    }
    impl<'ast> Visit<'ast> for ComboVisitor<'_> {
        fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
            if referenced_params_in_expr(&node.cond, self.bool_params).len() >= 2 {
                self.hits.push(node.cond.to_token_stream().to_string());
            }
            syn::visit::visit_expr_if(self, node);
        }

        fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
            if referenced_params_in_expr(&node.expr, self.bool_params).len() >= 2 {
                self.hits.push(node.expr.to_token_stream().to_string());
            }
            syn::visit::visit_expr_match(self, node);
        }
    }
    let mut visitor = ComboVisitor {
        bool_params,
        hits: Vec::new(),
    };
    visitor.visit_block(block);
    visitor.hits
}

/// `public-invariant-bypass` (todo.md §16.3): public fields are freely
/// writable, but consumers assume a value range or a combination of fields
/// holds together.
///
/// **This is a deliberately narrower, Fast-Tier-reachable subset of the full
/// rule from todo.md §16.3** (which is listed there as "Deep" tier) —
/// deliberately *without* the full rule's consumer-side analysis. This
/// implementation only looks at:
///
/// 1. **Primary (structural)** — a `pub struct` with ≥2 `pub` fields, without
///    a `#[non_exhaustive]` attribute, in the same crate.
/// 2. **Independent (control flow, same crate)** — at least one
///    constructor-shaped function for that struct type (a `pub fn` whose
///    return type is `Self`/the struct name, optionally wrapped in
///    `Result<..>`) contains a condition that jointly validates ≥2 of the
///    struct's `pub` fields — matched via parameter names that equal field
///    names (same name-matching heuristic as `boolean-state-cluster`) — and
///    whose then-branch leads to `Err(...)`/`panic!(...)`, or an
///    `assert!(...)` referencing ≥2 of those parameters.
///
/// Only structs satisfying both produce a candidate — exactly one per
/// struct, referencing every contributing constructor.
fn public_invariant_bypass_candidates(workspace: &Workspace) -> Vec<PatternCandidate> {
    let mut candidates = Vec::new();
    for krate in &workspace.crates {
        let mut structs: BTreeMap<String, PubStructFact> = BTreeMap::new();
        for_each_parsed_source(krate, |file, ast| {
            let mut visitor = PubStructVisitor {
                file,
                structs: BTreeMap::new(),
            };
            visitor.visit_file(ast);
            structs.extend(visitor.structs);
        });
        if structs.is_empty() {
            continue;
        }

        let mut constructor_hits: BTreeMap<String, Vec<ConstructorFact>> = BTreeMap::new();
        for_each_parsed_source(krate, |file, ast| {
            let mut visitor = ConstructorVisitor {
                file,
                self_type: None,
                structs: &structs,
                hits: BTreeMap::new(),
            };
            visitor.visit_file(ast);
            for (name, mut facts) in visitor.hits {
                constructor_hits.entry(name).or_default().append(&mut facts);
            }
        });

        for (name, fact) in &structs {
            let Some(ctor_facts) = constructor_hits.get(name) else {
                continue;
            };
            if ctor_facts.is_empty() {
                continue;
            }
            candidates.push(build_public_invariant_bypass_candidate(
                krate, fact, ctor_facts,
            ));
        }
    }
    candidates
}

/// A crate-local `pub struct` with ≥2 `pub` fields and no `#[non_exhaustive]`
/// attribute (see [`public_invariant_bypass_candidates`]'s signal 1).
struct PubStructFact {
    file: PathBuf,
    name: String,
    fields: BTreeSet<String>,
}

/// Whether any attribute in `attrs` is `#[non_exhaustive]`.
fn has_non_exhaustive_attr(attrs: &[syn::Attribute]) -> bool {
    attrs
        .iter()
        .any(|attr| attr.path().is_ident("non_exhaustive"))
}

/// Collects [`PubStructFact`]s from `pub struct` items in one source file.
struct PubStructVisitor<'a> {
    file: &'a Path,
    structs: BTreeMap<String, PubStructFact>,
}

impl<'ast> Visit<'ast> for PubStructVisitor<'_> {
    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
        if matches!(node.vis, syn::Visibility::Public(_)) && !has_non_exhaustive_attr(&node.attrs) {
            let fields: BTreeSet<String> = node
                .fields
                .iter()
                .filter(|field| matches!(field.vis, syn::Visibility::Public(_)))
                .filter_map(|field| field.ident.as_ref().map(ToString::to_string))
                .collect();
            if fields.len() >= 2 {
                let name = node.ident.to_string();
                self.structs.insert(
                    name.clone(),
                    PubStructFact {
                        file: self.file.to_path_buf(),
                        name,
                        fields,
                    },
                );
            }
        }
        syn::visit::visit_item_struct(self, node);
    }
}

/// One constructor-shaped function corroborating a [`PubStructFact`] (see
/// [`public_invariant_bypass_candidates`]'s signal 2).
struct ConstructorFact {
    file: PathBuf,
    item_path: String,
    hits: Vec<String>,
}

/// Collects [`ConstructorFact`]s, keyed by struct name, from `pub fn` items
/// (free functions and `impl` methods) in one source file whose return type
/// resolves to a struct already recorded in `structs`.
struct ConstructorVisitor<'a> {
    file: &'a Path,
    self_type: Option<String>,
    structs: &'a BTreeMap<String, PubStructFact>,
    hits: BTreeMap<String, Vec<ConstructorFact>>,
}

impl ConstructorVisitor<'_> {
    fn record_fn(&mut self, name: &str, sig: &syn::Signature, block: &syn::Block) {
        let syn::ReturnType::Type(_, ty) = &sig.output else {
            return;
        };
        let Some(struct_name) = resolved_struct_name(ty, self.self_type.as_deref()) else {
            return;
        };
        let Some(fact) = self.structs.get(&struct_name) else {
            return;
        };
        let param_names: BTreeSet<String> = sig
            .inputs
            .iter()
            .filter_map(|input| typed_ident_arg(input).map(|(name, _)| name))
            .collect();
        let matching_params: BTreeSet<String> =
            param_names.intersection(&fact.fields).cloned().collect();
        if matching_params.len() < 2 {
            return;
        }
        let hits = constructor_combo_hits(block, &matching_params);
        if hits.is_empty() {
            return;
        }
        let item_path = qualified_item_path(self.self_type.as_deref(), name);
        self.hits
            .entry(struct_name)
            .or_default()
            .push(ConstructorFact {
                file: self.file.to_path_buf(),
                item_path,
                hits,
            });
    }
}

impl<'ast> Visit<'ast> for ConstructorVisitor<'_> {
    visit_pub_fns_via_record_fn!();
    visit_item_impl_with_self_type!();
}

/// The struct name `ty` resolves to, if any: `Self` (resolved via
/// `self_type`, i.e. only within an `impl` block), the struct name directly,
/// or one level of `Result<T, _>` unwrapped around either — matched
/// structurally, no type resolution (same caveat as [`primitive_type_name`]).
fn resolved_struct_name(ty: &syn::Type, self_type: Option<&str>) -> Option<String> {
    let syn::Type::Path(type_path) = ty else {
        return None;
    };
    let segment = type_path.path.segments.last()?;
    let name = segment.ident.to_string();
    if name == "Self" {
        return self_type.map(str::to_string);
    }
    if name == "Result"
        && let syn::PathArguments::AngleBracketed(generics) = &segment.arguments
        && let Some(syn::GenericArgument::Type(inner)) = generics.args.first()
    {
        return resolved_struct_name(inner, self_type);
    }
    Some(name)
}

/// Rendered source text of every `if`/`assert!` in `block` that jointly
/// validates ≥2 of `matching_params` — see
/// [`public_invariant_bypass_candidates`]'s signal 2.
fn constructor_combo_hits(block: &syn::Block, matching_params: &BTreeSet<String>) -> Vec<String> {
    use quote::ToTokens;

    struct ComboVisitor<'a> {
        matching_params: &'a BTreeSet<String>,
        hits: Vec<String>,
    }
    impl<'ast> Visit<'ast> for ComboVisitor<'_> {
        fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
            if referenced_params_in_expr(&node.cond, self.matching_params).len() >= 2
                && block_leads_to_error_path(&node.then_branch)
            {
                self.hits.push(node.cond.to_token_stream().to_string());
            }
            syn::visit::visit_expr_if(self, node);
        }

        fn visit_macro(&mut self, node: &'ast syn::Macro) {
            if node.path.is_ident("assert")
                && tokens_reference_at_least_two_idents(&node.tokens, self.matching_params)
            {
                self.hits.push(node.tokens.to_string());
            }
            syn::visit::visit_macro(self, node);
        }
    }
    let mut visitor = ComboVisitor {
        matching_params,
        hits: Vec::new(),
    };
    visitor.visit_block(block);
    visitor.hits
}

/// Whether `tokens` references at least two distinct identifiers from
/// `idents` anywhere, including inside nested groups (used for `assert!`
/// macro arguments, same rationale as [`tokens_reference_ident`]).
fn tokens_reference_at_least_two_idents(
    tokens: &proc_macro2::TokenStream,
    idents: &BTreeSet<String>,
) -> bool {
    fn collect(
        tokens: proc_macro2::TokenStream,
        idents: &BTreeSet<String>,
        found: &mut BTreeSet<String>,
    ) {
        for tree in tokens {
            match tree {
                proc_macro2::TokenTree::Ident(node) => {
                    let name = node.to_string();
                    if idents.contains(&name) {
                        found.insert(name);
                    }
                }
                proc_macro2::TokenTree::Group(group) => collect(group.stream(), idents, found),
                _ => {}
            }
        }
    }
    let mut found = BTreeSet::new();
    collect(tokens.clone(), idents, &mut found);
    found.len() >= 2
}

fn build_public_invariant_bypass_candidate(
    krate: &CrateInfo,
    fact: &PubStructFact,
    ctor_facts: &[ConstructorFact],
) -> PatternCandidate {
    let scope = crate_scope(krate, vec![fact.name.clone()]);

    let primary_locations: Vec<EvidenceLocation> = fact
        .fields
        .iter()
        .map(|field| EvidenceLocation::new(fact.file.clone(), format!("{}::{field}", fact.name)))
        .collect();
    let field_list: Vec<&str> = fact.fields.iter().map(String::as_str).collect();

    let primary = Evidence {
        description: format!(
            "`pub struct {}` in crate `{}` has {} `pub` field(s) ({}) and carries no \
             `#[non_exhaustive]` attribute.",
            fact.name,
            krate.name,
            fact.fields.len(),
            field_list.join(", ")
        ),
        locations: primary_locations,
    };

    let mut independent_locations: Vec<EvidenceLocation> = ctor_facts
        .iter()
        .map(|ctor| EvidenceLocation::new(ctor.file.clone(), ctor.item_path.clone()))
        .collect();
    sort_evidence_locations(&mut independent_locations);

    let combo_texts: Vec<&str> = ctor_facts
        .iter()
        .flat_map(|ctor| ctor.hits.iter())
        .map(String::as_str)
        .collect();
    let independent = Evidence {
        description: format!(
            "At least one constructor for `{}` already validates a combination of ≥2 of these \
             `pub` fields together, e.g. `{}`.",
            fact.name,
            combo_texts.join("`, `")
        ),
        locations: independent_locations,
    };

    let evidence_identities: Vec<String> = std::iter::once(fact.name.clone())
        .chain(fact.fields.iter().cloned())
        .chain(ctor_facts.iter().map(|ctor| ctor.item_path.clone()))
        .collect();
    let mut affected_paths: Vec<PathBuf> = std::iter::once(fact.file.clone())
        .chain(ctor_facts.iter().map(|ctor| ctor.file.clone()))
        .collect();
    affected_paths.sort();
    affected_paths.dedup();

    pattern_candidate! {
        pattern: RustPattern::SmartConstructor,
        scope,
        evidence_identities,
        {
        evidence: CorroboratedEvidence::new(primary, independent),
        preconditions: vec![Precondition {
            description: format!(
                "`{}` hat mindestens zwei öffentliche Felder und mindestens ein Konstruktor \
                 validiert bereits eine Kombination davon.",
                fact.name
            ),
        }],
        contraindications: vec![
            Contraindication {
                description: "Wenn der Struct primär als reine Datenhülle ohne Invarianten \
                    außerhalb des Konstruktors gedacht ist, kann öffentlicher Feldzugriff bewusst \
                    sein."
                    .to_string(),
            },
            Contraindication {
                description: "Private Felder erzwingen Getter-/Setter-Boilerplate, was bei \
                    internen/Test-only-Structs mehr kostet als nützt."
                    .to_string(),
            },
        ],
        migration: vec![
            MigrationStep {
                step: 1,
                description: "Felder privat machen.".to_string(),
                affected_paths: vec![fact.file.clone()],
            },
            MigrationStep {
                step: 2,
                description:
                    "Bestehenden Konstruktor als einzigen Erzeugungsweg belassen/ausbauen."
                        .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 3,
                description: "Falls Änderungen nach Konstruktion nötig sind, validierte Setter \
                    statt direkter Feldzuweisung ergänzen."
                    .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 4,
                description: "Call-Sites, die Struct-Update-Syntax nutzen, anpassen.".to_string(),
                affected_paths,
            },
        ],
            related_findings: Vec::new(),
        }
    }
}

/// `manual-resource-lifecycle` (todo.md §16.3): recurring acquire/release-,
/// register/unregister-, or setup/cleanup pairs on several control-flow
/// paths.
///
/// **This is a deliberately narrower, Fast-Tier-reachable subset of the full
/// rule from todo.md §16.3** (which is listed there as "Deep" tier), with
/// especially strong contraindications: todo.md §16.4 only allows this
/// recommendation "wenn Besitz und Lebensdauer der Ressource eindeutig an
/// einen Guard gebunden werden können" — this Fast-Tier heuristic cannot
/// prove that, and the contraindications say so explicitly. This
/// implementation only looks at:
///
/// 1. **Primary (structural)** — within one function, both a call whose
///    ident matches a fixed "acquire" name pattern (`register`, `acquire`,
///    `open`, `lock`, `begin`, `start`, `connect`, `subscribe`) and a call
///    matching the corresponding "release" pattern (`unregister`, `release`,
///    `close`, `unlock`, `end`, `stop`, `disconnect`, `unsubscribe`) appear —
///    detected purely by call identifier, no type resolution. This can
///    falsely couple unrelated calls that merely share a common name.
/// 2. **Independent (crate-wide)** — the entire crate contains no
///    `impl Drop for ...` block at all, i.e. no evidence this codebase
///    already uses RAII guards as a pattern.
///
/// Only when both signals hold does exactly one candidate per crate emerge,
/// referencing every contributing function.
fn manual_resource_lifecycle_candidates(workspace: &Workspace) -> Vec<PatternCandidate> {
    let mut candidates = Vec::new();
    for krate in &workspace.crates {
        let mut has_drop_impl = false;
        let mut hits: Vec<EvidenceLocation> = Vec::new();
        for_each_parsed_source(krate, |file, ast| {
            if file_has_drop_impl(ast) {
                has_drop_impl = true;
            }
            let mut visitor = ResourceLifecycleVisitor {
                file,
                self_type: None,
                hits: Vec::new(),
            };
            visitor.visit_file(ast);
            hits.append(&mut visitor.hits);
        });
        if has_drop_impl || hits.is_empty() {
            continue;
        }
        candidates.push(build_manual_resource_lifecycle_candidate(krate, &hits));
    }
    candidates
}

const ACQUIRE_CALL_NAMES: &[&str] = &[
    "register",
    "acquire",
    "open",
    "lock",
    "begin",
    "start",
    "connect",
    "subscribe",
];

const RELEASE_CALL_NAMES: &[&str] = &[
    "unregister",
    "release",
    "close",
    "unlock",
    "end",
    "stop",
    "disconnect",
    "unsubscribe",
];

/// Whether `ast` contains an `impl Drop for ...` block anywhere (see
/// [`manual_resource_lifecycle_candidates`]'s signal 2).
fn file_has_drop_impl(ast: &syn::File) -> bool {
    struct DropFinder {
        found: bool,
    }
    impl<'ast> Visit<'ast> for DropFinder {
        fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
            if impl_trait_is(node, "Drop") {
                self.found = true;
            }
            syn::visit::visit_item_impl(self, node);
        }
    }
    let mut finder = DropFinder { found: false };
    finder.visit_file(ast);
    finder.found
}

/// Whether `block` contains at least one call matching
/// [`ACQUIRE_CALL_NAMES`] and at least one call matching
/// [`RELEASE_CALL_NAMES`], by call identifier only.
fn acquire_and_release_calls(block: &syn::Block) -> (bool, bool) {
    struct Finder {
        acquire: bool,
        release: bool,
    }
    impl Finder {
        fn observe(&mut self, name: &str) {
            if ACQUIRE_CALL_NAMES.contains(&name) {
                self.acquire = true;
            }
            if RELEASE_CALL_NAMES.contains(&name) {
                self.release = true;
            }
        }
    }
    impl<'ast> Visit<'ast> for Finder {
        fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
            self.observe(&node.method.to_string());
            syn::visit::visit_expr_method_call(self, node);
        }

        fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
            if let syn::Expr::Path(path) = node.func.as_ref()
                && let Some(segment) = path.path.segments.last()
            {
                self.observe(&segment.ident.to_string());
            }
            syn::visit::visit_expr_call(self, node);
        }
    }
    let mut finder = Finder {
        acquire: false,
        release: false,
    };
    finder.visit_block(block);
    (finder.acquire, finder.release)
}

/// Collects one [`EvidenceLocation`] per function (free function or `impl`
/// method, any visibility) in one source file whose body contains both an
/// acquire- and a release-shaped call.
struct ResourceLifecycleVisitor<'a> {
    file: &'a Path,
    self_type: Option<String>,
    hits: Vec<EvidenceLocation>,
}

impl ResourceLifecycleVisitor<'_> {
    fn record_fn(&mut self, name: &str, block: &syn::Block) {
        let (has_acquire, has_release) = acquire_and_release_calls(block);
        if !has_acquire || !has_release {
            return;
        }
        let item_path = qualified_item_path(self.self_type.as_deref(), name);
        self.hits
            .push(EvidenceLocation::new(self.file.to_path_buf(), item_path));
    }
}

impl<'ast> Visit<'ast> for ResourceLifecycleVisitor<'_> {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        self.record_fn(&node.sig.ident.to_string(), &node.block);
        syn::visit::visit_item_fn(self, node);
    }

    visit_item_impl_with_self_type!();

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        self.record_fn(&node.sig.ident.to_string(), &node.block);
        syn::visit::visit_impl_item_fn(self, node);
    }
}

fn build_manual_resource_lifecycle_candidate(
    krate: &CrateInfo,
    hits: &[EvidenceLocation],
) -> PatternCandidate {
    let modules: Vec<String> = hits
        .iter()
        .filter_map(|hit| hit.item_path.clone())
        .collect();
    let scope = crate_scope(krate, modules);

    let mut primary_locations = hits.to_vec();
    sort_evidence_locations(&mut primary_locations);

    let primary = Evidence {
        description: format!(
            "{} function(s) in crate `{}` call both an acquire-shaped operation (e.g. \
             `register`/`acquire`/`open`/`lock`/`begin`/`start`/`connect`/`subscribe`) and a \
             release-shaped counterpart (e.g. \
             `unregister`/`release`/`close`/`unlock`/`end`/`stop`/`disconnect`/`unsubscribe`) by \
             call name.",
            hits.len(),
            krate.name
        ),
        locations: primary_locations,
    };
    let independent = Evidence {
        description: format!(
            "Crate `{}` contains no `impl Drop for ...` block anywhere — no evidence this \
             codebase already uses RAII guards as a pattern.",
            krate.name
        ),
        locations: Vec::new(),
    };

    let evidence_identities: Vec<String> = location_identities(hits);
    let mut affected_paths: Vec<PathBuf> = hits.iter().map(|hit| hit.file.clone()).collect();
    affected_paths.sort();
    affected_paths.dedup();

    pattern_candidate! {
        pattern: RustPattern::RaiiGuard,
        scope,
        evidence_identities,
        {
        evidence: CorroboratedEvidence::new(primary, independent),
        preconditions: vec![Precondition {
            description: format!(
                "Crate `{}` enthält mindestens ein Acquire-/Release-Aufrufpaar innerhalb einer \
                 Funktion, aber keine `Drop`-Implementierung.",
                krate.name
            ),
        }],
        contraindications: vec![
            Contraindication {
                description: "Diese Heuristik kann nicht belegen, dass Besitz und Lebensdauer \
                    der Ressource eindeutig an einen einzelnen Guard gebunden werden können — das \
                    ist Voraussetzung für einen sinnvollen RAII-Guard, nicht nur Namensähnlichkeit."
                    .to_string(),
            },
            Contraindication {
                description: "Acquire/Release könnten unabhängige, zufällig gleich benannte \
                    Operationen auf unterschiedlichen Objekten sein."
                    .to_string(),
            },
            Contraindication {
                description: "Bei seltener, einmaliger Nutzung kann der Boilerplate eines \
                    eigenen Guard-Typs mehr kosten als eine sorgfältige manuelle Passung."
                    .to_string(),
            },
        ],
        migration: vec![
            MigrationStep {
                step: 1,
                description: "Ressourcentyp und Lebensdauer-Bindung manuell bestätigen (nicht \
                    automatisierbar)."
                    .to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 2,
                description: "Guard-Struct mit dem Handle als Feld definieren.".to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 3,
                description: "`Drop::drop` mit der Release-Logik implementieren.".to_string(),
                affected_paths: Vec::new(),
            },
            MigrationStep {
                step: 4,
                description: "Acquire-Stelle so umbauen, dass sie den Guard statt des rohen \
                    Handles zurückgibt."
                    .to_string(),
                affected_paths,
            },
        ],
            related_findings: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::{EvidenceClass, Location, OneBasedLine, Origin, Severity};
    use crate::ingest::{SourceFile, SourceKind};
    use crate::test_util::TempDir;

    fn workspace_with_crate(root: PathBuf, files: Vec<PathBuf>) -> Workspace {
        Workspace {
            root: root.clone(),
            crates: vec![CrateInfo {
                name: "fixture".to_string(),
                version: "0.1.0".to_string(),
                manifest_path: root.join("Cargo.toml"),
                root,
                source_files: files
                    .into_iter()
                    .map(|path| SourceFile {
                        path,
                        kind: SourceKind::Authored,
                    })
                    .collect(),
                entry_points: Vec::new(),
                dependencies: Vec::new(),
            }],
        }
    }

    fn catch_all_error_finding(file: &Path, item_path: &str, line: usize) -> Finding {
        Finding::new(
            format!("catch-all-error:{}:{line}:1", file.display()),
            crate::rules::slop::CATCH_ALL_ERROR_RULE,
            Severity::Warn,
            Location {
                file: file.to_path_buf(),
                line: OneBasedLine::new(line).unwrap(),
                item_path: item_path.to_string(),
            },
            EvidenceClass::DerivedFact,
            Origin::Code,
            None,
        )
    }

    /// (a) Two `catch-all-error` findings plus a crate-local typed error ⇒
    /// exactly one candidate, referencing both findings, with both evidence
    /// slots populated.
    #[test]
    fn two_symptoms_plus_a_typed_error_produce_one_candidate() {
        let dir = TempDir::new("pattern-corroborated");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n\
             pub fn b() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();
        let errors = dir.join("errors.rs");
        std::fs::write(&errors, "enum FooError { Bad }\n").unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone(), errors]);
        let findings = vec![
            catch_all_error_finding(&boundary, "a", 1),
            catch_all_error_finding(&boundary, "b", 2),
        ];

        let candidates = analyze_workspace(&workspace, &findings);
        assert_eq!(candidates.len(), 1);
        let candidate = &candidates[0];
        assert_eq!(candidate.pattern, RustPattern::DomainError);
        assert_eq!(candidate.scope.krate, "fixture");
        assert_eq!(candidate.related_findings.len(), 2);
        assert!(!candidate.evidence.primary.locations.is_empty());
        assert!(!candidate.evidence.independent.locations.is_empty());
        assert!(candidate.evidence.primary.description.contains('2'));
        assert!(!candidate.contraindications.is_empty());
        assert!(candidate.migration.len() >= 2);
    }

    /// (b) Only one `catch-all-error` finding, even with a typed error
    /// present ⇒ no candidate (a single symptom is not a pattern).
    #[test]
    fn a_single_finding_is_below_threshold() {
        let dir = TempDir::new("pattern-single-finding");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();
        let errors = dir.join("errors.rs");
        std::fs::write(&errors, "enum FooError { Bad }\n").unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone(), errors]);
        let findings = vec![catch_all_error_finding(&boundary, "a", 1)];

        assert!(analyze_workspace(&workspace, &findings).is_empty());
    }

    /// (c) Two `catch-all-error` findings but no crate-local typed error ⇒
    /// no candidate (only one independent signal, not corroborated).
    #[test]
    fn two_findings_without_a_typed_error_are_not_corroborated() {
        let dir = TempDir::new("pattern-uncorroborated");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n\
             pub fn b() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone()]);
        let findings = vec![
            catch_all_error_finding(&boundary, "a", 1),
            catch_all_error_finding(&boundary, "b", 2),
        ];

        assert!(analyze_workspace(&workspace, &findings).is_empty());
    }

    /// `impl ... Error for ...` alone (no `Error`-named enum, no derive) is
    /// enough for the independent signal.
    #[test]
    fn a_manual_error_trait_impl_counts_as_the_independent_signal() {
        let dir = TempDir::new("pattern-manual-impl");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n\
             pub fn b() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();
        let errors = dir.join("errors.rs");
        std::fs::write(
            &errors,
            "struct Oops;\n\
             impl std::fmt::Display for Oops { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { Ok(()) } }\n\
             impl std::error::Error for Oops {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone(), errors]);
        let findings = vec![
            catch_all_error_finding(&boundary, "a", 1),
            catch_all_error_finding(&boundary, "b", 2),
        ];

        assert_eq!(analyze_workspace(&workspace, &findings).len(), 1);
    }

    /// The id is deterministic across repeated aggregation runs over the
    /// same inputs.
    #[test]
    fn candidate_id_is_deterministic() {
        let dir = TempDir::new("pattern-deterministic-id");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n\
             pub fn b() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();
        let errors = dir.join("errors.rs");
        std::fs::write(&errors, "enum FooError { Bad }\n").unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone(), errors]);
        let findings = vec![
            catch_all_error_finding(&boundary, "a", 1),
            catch_all_error_finding(&boundary, "b", 2),
        ];

        let first = analyze_workspace(&workspace, &findings);
        let second = analyze_workspace(&workspace, &findings);
        assert_eq!(first[0].id, second[0].id);
    }

    /// `primitive-domain-value` (a): two `pub fn` signatures sharing a
    /// (parameter name, type) pair, one of them guarding the parameter with
    /// an early `return Err(...)` ⇒ one candidate with both evidence slots
    /// populated by the correct fundstellen.
    #[test]
    fn primitive_domain_value_two_signatures_plus_a_guard_produce_one_candidate() {
        let dir = TempDir::new("pattern-primitive-corroborated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn set_a(threshold: u32) {}\n\
             pub fn set_b(threshold: u32) -> Result<(), String> {\n\
             \x20   if threshold > 100 {\n\
             \x20       return Err(\"too big\".to_string());\n\
             \x20   }\n\
             \x20   Ok(())\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        let candidate = &candidates[0];
        assert_eq!(candidate.pattern, RustPattern::ValidatedNewtype);
        assert_eq!(candidate.scope.krate, "fixture");
        assert_eq!(candidate.evidence.primary.locations.len(), 2);
        assert_eq!(candidate.evidence.independent.locations.len(), 1);
        assert_eq!(
            candidate.evidence.independent.locations[0]
                .item_path
                .as_deref(),
            Some("set_b")
        );
        assert!(!candidate.contraindications.is_empty());
        assert!(candidate.migration.len() >= 2);
    }

    /// `primitive-domain-value` (b): only one signature, even with a guard
    /// ⇒ no candidate (a single occurrence is not a pattern).
    #[test]
    fn primitive_domain_value_single_signature_is_below_threshold() {
        let dir = TempDir::new("pattern-primitive-single");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn set_a(threshold: u32) -> Result<(), String> {\n\
             \x20   if threshold > 100 {\n\
             \x20       return Err(\"too big\".to_string());\n\
             \x20   }\n\
             \x20   Ok(())\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `primitive-domain-value` (c): two signatures sharing the pair, but no
    /// validation guard anywhere ⇒ no candidate (only one signal).
    #[test]
    fn primitive_domain_value_without_any_guard_is_not_corroborated() {
        let dir = TempDir::new("pattern-primitive-unguarded");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn set_a(threshold: u32) {}\n\
             pub fn set_b(threshold: u32) {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `boolean-state-cluster` (a): a function with three bool parameters
    /// and a condition combining two of them ⇒ one candidate.
    #[test]
    fn boolean_cluster_three_bools_plus_a_combined_condition_produce_one_candidate() {
        let dir = TempDir::new("pattern-bool-corroborated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn configure(verbose: bool, strict: bool, dry_run: bool) {\n\
             \x20   if verbose && strict {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   let _ = dry_run;\n\
             }\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        let candidate = &candidates[0];
        assert_eq!(candidate.pattern, RustPattern::OptionsStruct);
        assert_eq!(candidate.scope.krate, "fixture");
        assert_eq!(candidate.scope.modules, vec!["configure".to_string()]);
        assert!(!candidate.contraindications.is_empty());
    }

    /// `boolean-state-cluster` (b): three bool parameters, but only
    /// independent single-flag checks, never combined ⇒ no candidate.
    #[test]
    fn boolean_cluster_without_a_combined_condition_is_not_corroborated() {
        let dir = TempDir::new("pattern-bool-independent-checks");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn configure(verbose: bool, strict: bool, dry_run: bool) {\n\
             \x20   if verbose {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   if strict {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   if dry_run {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             }\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `boolean-state-cluster` (c): only two bool parameters, even with a
    /// combined condition ⇒ no candidate (threshold of three not reached).
    #[test]
    fn boolean_cluster_with_only_two_bools_is_below_threshold() {
        let dir = TempDir::new("pattern-bool-below-threshold");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn configure(verbose: bool, strict: bool) {\n\
             \x20   if verbose && strict {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             }\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `boolean-state-cluster` + clippy corroboration (d): the same fixture
    /// as (a) already produces a candidate from the two AST signals alone.
    /// A matching `clippy::fn_params_excessive_bools` hit for the same
    /// function (same file, overlapping line range) adds a third
    /// `additional` evidence entry — purely additive, on top of the
    /// existing `primary`/`independent` pair.
    #[test]
    fn boolean_cluster_with_matching_clippy_hit_gains_a_third_evidence_entry() {
        let dir = TempDir::new("pattern-bool-clippy-corroborated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn configure(verbose: bool, strict: bool, dry_run: bool) {\n\
             \x20   if verbose && strict {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   let _ = dry_run;\n\
             }\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);

        // Without `--clippy-json`: unchanged, no `additional` evidence —
        // proves the feature is fully backward-compatible/opt-in.
        let without_clippy = analyze_workspace(&workspace, &[]);
        assert_eq!(without_clippy.len(), 1);
        assert!(without_clippy[0].evidence.additional.is_empty());

        // With a matching `--clippy-json` hit: a third evidence entry.
        let clippy_hits = vec![ClippyBoolParamsHit {
            file: PathBuf::from("lib.rs"),
            line_start: 1,
            line_end: 1,
        }];
        let with_clippy = analyze_workspace_with_clippy(&workspace, &[], &clippy_hits);
        assert_eq!(with_clippy.len(), 1);
        assert_eq!(with_clippy[0].evidence.additional.len(), 1);
        assert!(
            with_clippy[0].evidence.additional[0]
                .description
                .contains("fn_params_excessive_bools")
        );
    }

    /// `boolean-state-cluster` + clippy corroboration (e): a clippy hit
    /// alone, for a function that does *not* independently satisfy the
    /// existing 2-signal AST check (bool params never combined in a
    /// condition, same fixture as (b)), must not create a candidate —
    /// clippy can only corroborate a candidate the AST signals already
    /// found, never create one by itself.
    #[test]
    fn boolean_cluster_clippy_hit_alone_does_not_create_a_candidate() {
        let dir = TempDir::new("pattern-bool-clippy-alone");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn configure(verbose: bool, strict: bool, dry_run: bool) {\n\
             \x20   if verbose {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   if strict {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             \x20   if dry_run {\n\
             \x20       do_thing();\n\
             \x20   }\n\
             }\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let clippy_hits = vec![ClippyBoolParamsHit {
            file: PathBuf::from("lib.rs"),
            line_start: 1,
            line_end: 1,
        }];

        assert!(analyze_workspace_with_clippy(&workspace, &[], &clippy_hits).is_empty());
    }

    /// `public-invariant-bypass` (a): a `pub struct` with two `pub` fields
    /// and a constructor jointly validating both ⇒ one candidate.
    #[test]
    fn public_invariant_bypass_struct_plus_combo_validating_constructor_produce_one_candidate() {
        let dir = TempDir::new("pattern-invariant-corroborated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub struct Range {\n\
             \x20   pub low: u32,\n\
             \x20   pub high: u32,\n\
             }\n\
             impl Range {\n\
             \x20   pub fn new(low: u32, high: u32) -> Result<Self, String> {\n\
             \x20       if low >= high {\n\
             \x20           return Err(\"low must be less than high\".to_string());\n\
             \x20       }\n\
             \x20       Ok(Self { low, high })\n\
             \x20   }\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        let candidate = &candidates[0];
        assert_eq!(candidate.pattern, RustPattern::SmartConstructor);
        assert_eq!(candidate.scope.krate, "fixture");
        assert_eq!(candidate.evidence.primary.locations.len(), 2);
        assert!(!candidate.evidence.independent.locations.is_empty());
        assert!(!candidate.contraindications.is_empty());
        assert!(candidate.migration.len() >= 2);
    }

    /// `public-invariant-bypass` (b): the same struct/constructor, but
    /// `#[non_exhaustive]` on the struct ⇒ no candidate, regardless of what
    /// the constructor validates.
    #[test]
    fn public_invariant_bypass_non_exhaustive_struct_produces_no_candidate() {
        let dir = TempDir::new("pattern-invariant-non-exhaustive");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "#[non_exhaustive]\n\
             pub struct Range {\n\
             \x20   pub low: u32,\n\
             \x20   pub high: u32,\n\
             }\n\
             impl Range {\n\
             \x20   pub fn new(low: u32, high: u32) -> Result<Self, String> {\n\
             \x20       if low >= high {\n\
             \x20           return Err(\"low must be less than high\".to_string());\n\
             \x20       }\n\
             \x20       Ok(Self { low, high })\n\
             \x20   }\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `public-invariant-bypass` (c): two `pub` fields, but the constructor
    /// only validates one field at a time (never a combination) ⇒ no
    /// candidate.
    #[test]
    fn public_invariant_bypass_single_field_validation_is_not_corroborated() {
        let dir = TempDir::new("pattern-invariant-single-field");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub struct Range {\n\
             \x20   pub low: u32,\n\
             \x20   pub high: u32,\n\
             }\n\
             impl Range {\n\
             \x20   pub fn new(low: u32, high: u32) -> Result<Self, String> {\n\
             \x20       if low > 1000 {\n\
             \x20           return Err(\"too big\".to_string());\n\
             \x20       }\n\
             \x20       Ok(Self { low, high })\n\
             \x20   }\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `manual-resource-lifecycle` (a): a function calling `register(...)`
    /// and `unregister(...)`, and the crate has no `impl Drop` anywhere ⇒
    /// one candidate.
    #[test]
    fn manual_resource_lifecycle_register_unregister_without_drop_produces_one_candidate() {
        let dir = TempDir::new("pattern-resource-corroborated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn manage(handle: u32) {\n\
             \x20   register(handle);\n\
             \x20   unregister(handle);\n\
             }\n\
             fn register(_handle: u32) {}\n\
             fn unregister(_handle: u32) {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        let candidate = &candidates[0];
        assert_eq!(candidate.pattern, RustPattern::RaiiGuard);
        assert_eq!(candidate.scope.krate, "fixture");
        assert!(!candidate.evidence.primary.locations.is_empty());
        assert_eq!(candidate.contraindications.len(), 3);
        assert!(candidate.migration.len() >= 2);
    }

    /// `manual-resource-lifecycle` (b): the same acquire/release pair, but
    /// the crate has an `impl Drop for X` elsewhere ⇒ no candidate (the
    /// independent signal is missing).
    #[test]
    fn manual_resource_lifecycle_with_an_existing_drop_impl_is_not_corroborated() {
        let dir = TempDir::new("pattern-resource-has-drop");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn manage(handle: u32) {\n\
             \x20   register(handle);\n\
             \x20   unregister(handle);\n\
             }\n\
             fn register(_handle: u32) {}\n\
             fn unregister(_handle: u32) {}\n\
             struct X;\n\
             impl Drop for X {\n\
             \x20   fn drop(&mut self) {}\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `manual-resource-lifecycle` (c): only `register(...)` without a
    /// matching `unregister(...)` ⇒ no candidate.
    #[test]
    fn manual_resource_lifecycle_without_a_matching_release_call_produces_no_candidate() {
        let dir = TempDir::new("pattern-resource-unmatched");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn manage(handle: u32) {\n\
             \x20   register(handle);\n\
             }\n\
             fn register(_handle: u32) {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `stringly-error-boundary` (d) — unentscheidbar: the crate's only
    /// typed error lives behind `#[cfg(feature = "not-enabled-by-default")]`.
    /// A real build without that feature would never see `FooError` coexist
    /// with the two catch-all-error boundary functions, but
    /// `syn::parse_file` has no cfg resolution and parses every `cfg`
    /// branch regardless of actual feature activation (a documented,
    /// accepted Fast-Tier limitation, not a bug). This is a golden test of
    /// that honest, limited behavior: the candidate still fires, corroborated
    /// by evidence that might not actually coexist in any real build.
    #[test]
    fn stringly_error_boundary_cfg_gated_typed_error_still_corroborates() {
        let dir = TempDir::new("pattern-stringly-cfg-gated");
        let boundary = dir.join("boundary.rs");
        std::fs::write(
            &boundary,
            "pub fn a() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n\
             pub fn b() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
        )
        .unwrap();
        let errors = dir.join("errors.rs");
        std::fs::write(
            &errors,
            "#[cfg(feature = \"not-enabled-by-default\")]\n\
             enum FooError { Bad }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![boundary.clone(), errors]);
        let findings = vec![
            catch_all_error_finding(&boundary, "a", 1),
            catch_all_error_finding(&boundary, "b", 2),
        ];

        let candidates = analyze_workspace(&workspace, &findings);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::DomainError);
    }

    /// `primitive-domain-value` (d) — unentscheidbar: the guarding signature
    /// only exists behind `#[cfg(feature = "not-enabled-by-default")]`. In a
    /// real build without that feature, `set_b` (and its validation guard)
    /// would not exist alongside `set_a`, but `syn::parse_file` has no cfg
    /// resolution and parses both regardless. Golden test of that honest,
    /// limited behavior — not a bug.
    #[test]
    fn primitive_domain_value_cfg_gated_guard_still_corroborates() {
        let dir = TempDir::new("pattern-primitive-cfg-gated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "pub fn set_a(threshold: u32) {}\n\
             #[cfg(feature = \"not-enabled-by-default\")]\n\
             pub fn set_b(threshold: u32) -> Result<(), String> {\n\
             \x20   if threshold > 100 {\n\
             \x20       return Err(\"too big\".to_string());\n\
             \x20   }\n\
             \x20   Ok(())\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::ValidatedNewtype);
    }

    /// `boolean-state-cluster` (d) — unentscheidbar: the three-bool-parameter
    /// function that would trip this rule is produced entirely by a
    /// `macro_rules!` expansion, never written out in the source. `syn` sees
    /// the macro *definition* and the invocation `configure_impl!();` as an
    /// opaque `Item::Macro`, never the expanded `fn configure(...)` — the
    /// condition this rule looks for is structurally invisible to a
    /// `syn::parse_file`-based scanner. Proves the rule stays silent rather
    /// than guessing at what the expansion might contain.
    #[test]
    fn boolean_cluster_macro_generated_function_produces_no_candidate() {
        let dir = TempDir::new("pattern-bool-macro-generated");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "macro_rules! configure_impl {\n\
             \x20   () => {\n\
             \x20       pub fn configure(verbose: bool, strict: bool, dry_run: bool) {\n\
             \x20           if verbose && strict {\n\
             \x20               do_thing();\n\
             \x20           }\n\
             \x20           let _ = dry_run;\n\
             \x20       }\n\
             \x20   };\n\
             }\n\
             configure_impl!();\n\
             fn do_thing() {}\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `public-invariant-bypass` (d) — unentscheidbar: `Range` carries a
    /// `#[derive(Builder)]`-shaped attribute whose expansion would generate
    /// the real validating constructor, but that constructor is never
    /// written out as source `syn` can see — only the derive macro
    /// invocation is visible. No `pub fn` in this file returns `Self`/
    /// `Range`, so `ConstructorVisitor` finds nothing to corroborate the
    /// struct fact with. Proves the rule only acts on what is literally in
    /// the AST, not on macro-expanded validation it cannot observe.
    #[test]
    fn public_invariant_bypass_derive_macro_constructor_produces_no_candidate() {
        let dir = TempDir::new("pattern-invariant-derive-macro");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "#[derive(Builder)]\n\
             pub struct Range {\n\
             \x20   pub low: u32,\n\
             \x20   pub high: u32,\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        assert!(analyze_workspace(&workspace, &[]).is_empty());
    }

    /// `manual-resource-lifecycle` (d) — unentscheidbar: `register`/
    /// `unregister` are called on two unrelated types (`MetricRegistry`/
    /// `ListSubscription`) for two semantically unrelated operations that
    /// merely happen to share the acquire/release name pattern this rule
    /// matches on. The rule has no type resolution, so it cannot tell these
    /// apart from a genuine acquire/release pair on one resource — it fires
    /// anyway. This is not a bug to fix: it is the documented
    /// false-positive vector the rule's own contraindications warn about
    /// (see `build_manual_resource_lifecycle_candidate`'s second
    /// contraindication), and the reason the Gegenindikationen on this rule
    /// are mandatory.
    #[test]
    fn manual_resource_lifecycle_unrelated_types_sharing_call_names_still_fires() {
        let dir = TempDir::new("pattern-resource-coincidental-names");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "struct MetricRegistry;\n\
             impl MetricRegistry {\n\
             \x20   fn register(&self, _id: u32) {}\n\
             }\n\
             struct ListSubscription;\n\
             impl ListSubscription {\n\
             \x20   fn unregister(&self) {}\n\
             }\n\
             pub fn unrelated_operations(id: u32) {\n\
             \x20   let registry = MetricRegistry;\n\
             \x20   let subscription = ListSubscription;\n\
             \x20   registry.register(id);\n\
             \x20   subscription.unregister();\n\
             }\n",
        )
        .unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);

        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::RaiiGuard);
    }

    /// The registry's curated `example.before` for `stringly-error-boundary`
    /// (see `rule_registry::RULE_REGISTRY`) must itself still trigger the
    /// rule — this is what keeps a landing-page-facing example from
    /// silently drifting away from what judge actually flags. This rule
    /// produces a `PatternCandidate`, not a `Finding` (see this module's own
    /// doc comment for why the two are deliberately kept separate), so the
    /// check reruns `analyze_workspace` exactly like
    /// `two_symptoms_plus_a_typed_error_produce_one_candidate` above and
    /// asserts on `.pattern` rather than on a `Finding`'s rule id.
    #[test]
    fn stringly_error_boundary_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(STRINGLY_ERROR_BOUNDARY_RULE)
            .expect("stringly-error-boundary has a registry entry")
            .example
            .expect("stringly-error-boundary has a curated example")
            .before;

        let dir = TempDir::new("pattern-registry-example-stringly");
        let file = dir.join("lib.rs");
        std::fs::write(&file, example).unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file.clone()]);
        let findings = vec![
            catch_all_error_finding(&file, "fetch_user", 1),
            catch_all_error_finding(&file, "fetch_order", 5),
        ];

        let candidates = analyze_workspace(&workspace, &findings);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::DomainError);
    }

    /// The registry's curated `example.before` for `primitive-domain-value`
    /// must itself still trigger the rule — see the drift-guard doc comment
    /// on `stringly_error_boundary_registry_example_still_triggers_the_rule`
    /// above for why this reruns `analyze_workspace` and asserts on
    /// `.pattern` instead of using a `Finding`-based helper.
    #[test]
    fn primitive_domain_value_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(PRIMITIVE_DOMAIN_VALUE_RULE)
            .expect("primitive-domain-value has a registry entry")
            .example
            .expect("primitive-domain-value has a curated example")
            .before;

        let dir = TempDir::new("pattern-registry-example-primitive");
        let file = dir.join("lib.rs");
        std::fs::write(&file, example).unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::ValidatedNewtype);
    }

    /// The registry's curated `example.before` for `boolean-state-cluster`
    /// must itself still trigger the rule — see the drift-guard doc comment
    /// on `stringly_error_boundary_registry_example_still_triggers_the_rule`
    /// above for why this reruns `analyze_workspace` and asserts on
    /// `.pattern` instead of using a `Finding`-based helper.
    #[test]
    fn boolean_state_cluster_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(BOOLEAN_STATE_CLUSTER_RULE)
            .expect("boolean-state-cluster has a registry entry")
            .example
            .expect("boolean-state-cluster has a curated example")
            .before;

        let dir = TempDir::new("pattern-registry-example-boolean");
        let file = dir.join("lib.rs");
        std::fs::write(&file, example).unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::OptionsStruct);
    }

    /// The registry's curated `example.before` for `public-invariant-bypass`
    /// must itself still trigger the rule — see the drift-guard doc comment
    /// on `stringly_error_boundary_registry_example_still_triggers_the_rule`
    /// above for why this reruns `analyze_workspace` and asserts on
    /// `.pattern` instead of using a `Finding`-based helper.
    #[test]
    fn public_invariant_bypass_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(PUBLIC_INVARIANT_BYPASS_RULE)
            .expect("public-invariant-bypass has a registry entry")
            .example
            .expect("public-invariant-bypass has a curated example")
            .before;

        let dir = TempDir::new("pattern-registry-example-invariant");
        let file = dir.join("lib.rs");
        std::fs::write(&file, example).unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::SmartConstructor);
    }

    /// The registry's curated `example.before` for
    /// `manual-resource-lifecycle` must itself still trigger the rule — see
    /// the drift-guard doc comment on
    /// `stringly_error_boundary_registry_example_still_triggers_the_rule`
    /// above for why this reruns `analyze_workspace` and asserts on
    /// `.pattern` instead of using a `Finding`-based helper.
    #[test]
    fn manual_resource_lifecycle_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(MANUAL_RESOURCE_LIFECYCLE_RULE)
            .expect("manual-resource-lifecycle has a registry entry")
            .example
            .expect("manual-resource-lifecycle has a curated example")
            .before;

        let dir = TempDir::new("pattern-registry-example-resource");
        let file = dir.join("lib.rs");
        std::fs::write(&file, example).unwrap();

        let workspace = workspace_with_crate(dir.to_path_buf(), vec![file]);
        let candidates = analyze_workspace(&workspace, &[]);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].pattern, RustPattern::RaiiGuard);
    }
}