cuke-dedup 0.3.0

Static analysis for duplicate and reusable Cucumber step definitions
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
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
use super::pairs::{analyze_definition_pairs, definition_pair_candidates};
use super::similarity::{
    handler_similarity, is_near_matcher, matcher_similarity, ordered_common_subsequence_len,
};
use super::*;
use crate::config::{ConfigOverrides, SuppressionConfig};
use crate::discovery::{SourceFile, SourceLanguage};
use crate::gherkin;
use crate::model::{DuplicationThreshold, Rule};
use crate::typescript;
use std::path::{Path, PathBuf};

fn definitions(source: &str) -> Vec<StepDefinition> {
    typescript::extract(
        source,
        &SourceFile {
            path: PathBuf::from("steps.ts"),
            language: SourceLanguage::TypeScript,
        },
    )
    .unwrap()
}

fn config() -> (tempfile::TempDir, Config) {
    let directory = tempfile::tempdir().unwrap();
    let config = Config::load(directory.path(), ConfigOverrides::default()).unwrap();
    (directory, config)
}

#[test]
fn public_analysis_rejects_mutated_configs_above_hard_safety_ceilings() {
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 2_000_001;
    let error = analyze(Vec::new(), Vec::new(), &config).unwrap_err();
    assert!(error
        .to_string()
        .contains("maxCandidateComparisons must not exceed the hard safety limit of 2000000"));

    config.max_candidate_comparisons = 2_000_000;
    config.max_structural_class_comparisons = 250_001;
    let error = analyze_with_diagnostics(Vec::new(), Vec::new(), &config).unwrap_err();
    assert!(error
        .to_string()
        .contains("maxStructuralClassComparisons must not exceed the hard safety limit of 250000"));
}

#[test]
fn equivalent_assertion_factory_syntax_preserves_conflicting_values() {
    for (import, factory, trusted) in [
        ("import {default as check} from 'expect';", "check", true),
        ("const check = require('expect');", "(check)", true),
        (
            "import {expect as check} from '@playwright/test';",
            "(check as any)",
            true,
        ),
        (
            "import {expect as check} from '@playwright/test';",
            "check!",
            true,
        ),
        (
            "import {expect as check} from '@playwright/test';",
            "(check satisfies Function)",
            true,
        ),
        (
            "import * as api from '@playwright/test';",
            "((api as PW).expect)",
            true,
        ),
        (
            "import * as api from '@playwright/test';",
            "api['expect']",
            true,
        ),
        (
            "const api = require('@playwright/test');",
            "(api as PW)[\"expect\"]",
            true,
        ),
        (
            "import * as api from '@playwright/test';",
            r"api['ex\u0070ect']",
            true,
        ),
        (
            "import * as api from '@playwright/test';",
            "api[key]",
            false,
        ),
        ("import * as api from 'unrelated';", "api['expect']", false),
        (
            "const {expect: check = fallback} = require('@playwright/test');",
            "check",
            false,
        ),
        (
            "const {expect = fallback} = require('@playwright/test');",
            "expect",
            false,
        ),
        (
            "import {default as check} from '@playwright/test';",
            "check",
            false,
        ),
        (
            "import {default as check} from 'unrelated';",
            "(check)",
            false,
        ),
        (
            "import type {default as check} from 'expect';",
            "check",
            false,
        ),
    ] {
        let defs = definitions(&format!("{import} Then('parcel is ready', ({{state}}) => {factory}(state).toBe('ready')); Then('parcel is idle', ({{state}}) => {factory}(state).toBe('idle'));"));
        assert_eq!(defs.len(), 2, "{import} {factory}");
        assert_eq!(
            defs[0]
                .handler
                .behavior_signature
                .iter()
                .any(|e| e.starts_with("assert:")),
            trusted,
            "{import} {factory}"
        );
        if trusted {
            assert_ne!(
                defs[0].handler.behavior_signature,
                defs[1].handler.behavior_signature
            );
        }
    }
}

#[test]
fn future_local_declarations_do_not_expose_outer_assertion_values() {
    for (body, comparable) in [
        (
            "expect(state).toBe(expected); var expected = 'ready';",
            true,
        ),
        ("var expected; expect(state).toBe(expected);", true),
        (
            "var expected = external; expect(state).toBe(expected);",
            false,
        ),
        (
            "{ expect(state).toBe(expected); let expected = 'ready'; }",
            false,
        ),
        (
            "const expected = 'ready'; { expect(state).toBe(expected); class expected {} }",
            false,
        ),
        (
            "const expected = 'ready'; { expect(state).toBe(expected); function expected() {} }",
            false,
        ),
        (
            "const expected = 'ready'; { expect(state).toBe(expected); enum expected { value } }",
            false,
        ),
        (
            "const expected = 'ready'; try {} catch (expected) { expect(state).toBe(expected); }",
            false,
        ),
        (
            "const expected = 'ready'; { type expected = string; expect(state).toBe(expected); }",
            true,
        ),
    ] {
        let defs = definitions(&format!(
            "Then('state', ({{state, expected}}) => {{ {body} }});"
        ));
        assert_eq!(defs[0].handler.comparable, comparable, "{body}");
    }
    for (body, comparable) in [
        ("const expected = 'ready'; { expect(state).toBe(expected); const expected = 'idle'; }", false),
        ("const expected = 'ready'; { const copy = expected; const expected = 'idle'; expect(state).toBe(copy); }", false),
        ("const expected = 'ready'; { expect(state).toBe(expected); let expected; }", false),
        ("const expected = 'ready'; { expect(state).toBe(expected); const {expected} = external; }", false),
        ("const expected = 'ready'; { const [expected] = external; expect(state).toBe(expected); }", false),
        ("const {x} = (() => { const expected = 'ready'; expect(state).toBe(expected); return {}; })();", true),
        ("const expected = 'ready'; { const expected = 'idle'; expect(state).toBe(expected); }", true),
        ("const expected = 'ready'; { const copy = expected; expect(state).toBe(copy); }", true),
        ("{ expect(state).toBe(expected); const expected = 'idle'; }", false),
    ] {
        let defs = definitions(&format!("Then('parcel is ready', ({{state}}) => {{ {body} }});"));
        assert_eq!(defs[0].handler.comparable, comparable, "{body}");
    }
    for callback in ["function expected()", "function* expected()"] {
        let defs = definitions(&format!(
            "Then('state', ({{state}}) => {{ const expected = 'ready'; register({callback} {{ expect(state).toBe(expected); }}); }});"
        ));
        assert!(!defs[0].handler.comparable, "{callback}");
    }
    let defs = definitions("Then('state', ({state, expected}) => { const Box = class expected { static check = expect(state).toBe(expected); }; use(Box); });");
    assert_eq!(defs.len(), 1);
    assert!(!defs[0].handler.comparable);
}

#[test]
fn nested_assertion_builders_validate_their_origin_and_arguments() {
    for (prefix, expected, comparable) in [
        ("", "expect.objectContaining({role: 'admin'})", true),
        ("", "expect.not.objectContaining({role: 'admin'})", true),
        (
            "",
            "expect.arrayContaining([expect.stringContaining('admin')])",
            true,
        ),
        ("", "expect.objectContaining({role: external})", false),
        ("", "expect.unknownBuilder({role: 'admin'})", false),
        (
            "import {expect as check} from '@playwright/test';",
            "check.objectContaining({role: 'admin'})",
            true,
        ),
        (
            "import {expect as check} from 'unrelated';",
            "check.objectContaining({role: 'admin'})",
            false,
        ),
        (
            "const check = custom;",
            "check.objectContaining({role: 'admin'})",
            false,
        ),
    ] {
        let defs = definitions(&format!("{prefix} Then('parcel is ready', ({{state}}) => expect(state).toEqual({expected})); Then('shipment readiness confirmed', ({{state}}) => expect(state).toEqual({expected}));"));
        assert_eq!(
            defs[0].handler.comparable, comparable,
            "{prefix} {expected}"
        );
        let (_dir, cfg) = config();
        let result = analyze(defs, Vec::new(), &cfg).unwrap();
        assert_eq!(
            result
                .findings
                .iter()
                .any(|f| f.rule == Rule::DuplicateHandler),
            comparable,
            "{prefix} {expected}"
        );
    }
    let defs = definitions("Then('parcel is ready', ({state}) => expect(state).toEqual(expect.objectContaining({role: 'admin'}))); Then('parcel is now ready', ({state}) => expect(state).toEqual(expect.objectContaining({role: 'guest'})));");
    assert_ne!(
        defs[0].handler.behavior_signature,
        defs[1].handler.behavior_signature
    );

    let defs = definitions("import {expect as check} from '@playwright/test'; Then('parcel is ready', ({state}) => expect(state).toEqual(expect.objectContaining({role: 'admin'}))); Then('shipment readiness confirmed', ({state}) => check(state).toEqual((check as any).objectContaining({role: 'admin'})));");
    assert_eq!(
        defs[0].handler.behavior_signature,
        defs[1].handler.behavior_signature
    );
    let defs = definitions("Then('parcel is ready', ({state}) => expect(state).toEqual(expect.objectContaining({role: 'admin'}))); Then('shipment readiness confirmed', ({state}) => expect(state).toEqual(expect.not.objectContaining({role: 'admin'})));");
    assert_ne!(
        defs[0].handler.behavior_signature,
        defs[1].handler.behavior_signature
    );
}

#[test]
fn computed_nested_matchers_preserve_dotted_semantics() {
    for prefix in [
        "import * as api from '@playwright/test';",
        "const api = require('@playwright/test');",
    ] {
        for (dotted, computed) in [
            ("expect.objectContaining", "expect['objectContaining']"),
            (
                "expect.not.objectContaining",
                "expect['not']['objectContaining']",
            ),
            (
                "api.expect.objectContaining",
                "api['expect']['objectContaining']",
            ),
            (
                "api.expect.not.objectContaining",
                "(api['expect'] as any)['not']['objectContaining']",
            ),
            (
                "api.expect.objectContaining",
                r"api['expect']['object\u0043ontaining']",
            ),
        ] {
            let defs = definitions(&format!("{prefix} Then('parcel is ready', ({{state}}) => expect(state).toEqual({dotted}({{role: 'admin'}}))); Then('parcel is now ready', ({{state}}) => expect(state).toEqual({computed}({{role: 'admin'}})));"));
            assert!(defs.iter().all(|d| d.handler.comparable), "{computed}");
            assert_eq!(
                defs[0].handler.behavior_signature, defs[1].handler.behavior_signature,
                "{computed}"
            );
            let (_dir, cfg) = config();
            assert!(
                analyze(defs, Vec::new(), &cfg)
                    .unwrap()
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::NearDuplicateStep),
                "{computed}"
            );
        }
        for builder in [
            "api['expect'][key]",
            "api['expect']['unknownBuilder']",
            "local['objectContaining']",
        ] {
            let defs = definitions(&format!("{prefix} const local = custom; Then('state', ({{state}}) => expect(state).toEqual({builder}({{role: 'admin'}})));"));
            assert!(!defs[0].handler.comparable, "{builder}");
        }
    }
}

#[test]
fn unresolved_subject_shadows_do_not_collapse_to_empty_values() {
    for declarations in [
        "class First {} class Second {}",
        "function First() {} function Second() {}",
        "enum First { Ready } enum Second { Idle }",
    ] {
        let defs = definitions(&format!(
            "Then('subject', () => {{ {declarations} expect(First).toBe('ready'); expect(Second).toBe('ready'); }});"
        ));
        let events: Vec<_> = defs[0]
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .collect();
        assert_eq!(events.len(), 2, "{declarations}");
        assert_ne!(events[0], events[1], "{declarations}");
    }
}

#[test]
fn reassigned_asymmetric_matchers_lose_trust_without_changing_outer_factory() {
    for (prefix, factory) in [
        ("", "expect"),
        (
            "import { expect as check } from '@playwright/test';",
            "check",
        ),
        ("const api = require('@playwright/test');", "api.expect"),
        ("const api = require('@playwright/test');", "api['expect']"),
    ] {
        for (mutation, trusted) in [
            ("FACTORY.objectContaining = replacement;", false),
            ("FACTORY.not = replacement;", false),
            ("FACTORY.not.objectContaining = replacement;", false),
            ("FACTORY['not'].objectContaining = replacement;", false),
            ("FACTORY['objectContaining'] = replacement;", false),
            ("delete FACTORY.objectContaining;", false),
            (
                "const alias = FACTORY; alias.objectContaining = replacement;",
                false,
            ),
            ("FACTORY.unrelated = replacement;", true),
            (
                "function local(expect) { expect.objectContaining = replacement; }",
                true,
            ),
            ("", true),
        ] {
            let mutation = mutation.replace("FACTORY", factory);
            let defs = definitions(&format!(
                "{prefix} {mutation} Then('nested', ({{state}}) => {factory}(state).toEqual({factory}.objectContaining({{role: 'admin'}}))); Then('direct', ({{state}}) => {factory}(state).toBe('ready'));"
            ));
            assert_eq!(defs.len(), 2, "{factory} {mutation}");
            assert_eq!(defs[0].handler.comparable, trusted, "{factory} {mutation}");
            assert!(defs[1].handler.comparable, "{factory} {mutation}");
            assert!(
                defs[1]
                    .handler
                    .behavior_signature
                    .iter()
                    .any(|event| event.starts_with("assert:")),
                "{factory} {mutation}"
            );
        }
    }
}

#[test]
fn namespace_matcher_mutations_follow_computed_and_destructured_aliases() {
    for prefix in [
        "import * as api from '@playwright/test';",
        "const api = require('@playwright/test');",
    ] {
        for (alias, trusted) in [
            ("const check = api['expect'];", false),
            ("const check = (api as any)[\"expect\"];", false),
            ("const { expect: check } = api;", false),
            ("const { expect: check = fallback } = api;", false),
            ("let check; ({ expect: check = fallback } = api);", false),
            (
                "const {expect = fallback} = api; const check = expect;",
                false,
            ),
            ("const { 'expect': check } = api;", false),
            ("const { ['expect']: check } = api;", false),
            (r"const { 'ex\u0070ect': check } = api;", false),
            ("let check; ({ expect: check } = api);", false),
            ("const check = api.other;", true),
            ("const check = make(api.expect);", true),
            ("const check = (make(api['expect']) as any);", true),
            ("const check = { factory: api.expect };", true),
            ("const check = api[key];", false),
            ("const { other: check } = api;", true),
        ] {
            let defs = definitions(&format!("{prefix} {alias} check.objectContaining = replacement; Then('state', ({{state}}) => api.expect(state).toEqual(api.expect.objectContaining({{role: 'admin'}})));"));
            assert_eq!(defs[0].handler.comparable, trusted, "{prefix} {alias}");
        }
        let defs = definitions(&format!("{prefix} function local(api) {{ const {{ expect: check }} = api; check.objectContaining = replacement; }} Then('state', ({{state}}) => api.expect(state).toEqual(api.expect.objectContaining({{role: 'admin'}})));"));
        assert!(defs[0].handler.comparable, "{prefix}");
        let defs = definitions(&format!("{prefix} function local(api) {{ const {{expect: check = fallback}} = api; check.objectContaining = replacement; }} Then('state', ({{state}}) => api['expect'](state).toEqual(api.expect.objectContaining({{role: 'admin'}})));"));
        assert!(defs[0].handler.comparable, "{prefix}");
    }
}

#[test]
fn computed_destructuring_distinguishes_trust_from_possible_mutation() {
    let (_dir, cfg) = config();
    for (key, grants_trust, may_mutate) in [
        ("expect", true, true),
        ("'expect'", true, true),
        ("['expect']", true, true),
        (r"['ex\u0070ect']", true, true),
        ("[key]", false, true),
        ("[expect]", false, true),
        ("other", false, false),
        ("['other']", false, false),
    ] {
        for mutation in [false, true] {
            for prefix in [
                "import * as api from '@playwright/test';",
                "const api = require('@playwright/test');",
            ] {
                let setup = if mutation {
                    format!("{prefix} const {{{key}: check}} = api; check.objectContaining = replacement;")
                } else {
                    format!("const {{{key}: check}} = require('@playwright/test');")
                };
                let builder = if mutation { "api.expect" } else { "check" };
                let expected = if mutation { !may_mutate } else { grants_trust };
                let defs = definitions(&format!("{setup} Then('parcel is ready', ({{state}}) => expect(state).toEqual({builder}.objectContaining({{role:'admin'}}))); Then('parcel is now ready', ({{state}}) => expect(state).toEqual({builder}.objectContaining({{role:'admin'}})));"));
                assert!(
                    defs.iter().all(|d| d.handler.comparable == expected),
                    "{setup}"
                );
                let findings = analyze(defs, Vec::new(), &cfg).unwrap().findings;
                assert_eq!(
                    findings.iter().any(|f| matches!(
                        f.rule,
                        Rule::DuplicateHandler
                            | Rule::NearDuplicateStep
                            | Rule::ParameterizationCandidate
                    )),
                    expected,
                    "{setup}"
                );
            }
        }
    }
}

#[test]
fn parameterized_inline_calls_keep_execution_context_without_handler_findings() {
    let (_dir, cfg) = config();
    for function in [
        "(x) => save(x)",
        "function(x) { save(x); }",
        "function*(x) { yield x; }",
        "async function*(x) { yield x; }",
    ] {
        for deferred in [false, true] {
            let call = format!("({function})(prepare(), finish());");
            let body = if deferred {
                format!("register(() => {{ {call} }});")
            } else {
                call
            };
            let defs = definitions(&format!("Then('parcel is ready', () => {{ {body} }}); Then('parcel is now ready', () => {{ {body} }});"));
            let marker = if deferred {
                "deferred-assert:unresolved"
            } else {
                "assert:unresolved"
            };
            assert!(
                defs.iter().all(|d| !d.handler.comparable
                    && d.handler.behavior_signature.iter().any(|e| e == marker)),
                "{body}"
            );
            let mut expected_events = if deferred {
                vec!["call:register"]
            } else {
                Vec::new()
            };
            expected_events.extend([marker, "call:prepare", "call:finish"]);
            assert_eq!(
                defs[0].handler.behavior_signature, expected_events,
                "{body}"
            );
            let findings = analyze(defs, Vec::new(), &cfg).unwrap().findings;
            assert!(
                !findings.iter().any(|f| matches!(
                    f.rule,
                    Rule::DuplicateHandler
                        | Rule::NearDuplicateStep
                        | Rule::ParameterizationCandidate
                )),
                "{body}"
            );
        }
    }
}

#[test]
fn deferred_assertion_disagreement_cannot_be_outweighed_by_shared_calls() {
    let (_dir, cfg) = config();
    let mut limited_cfg = cfg.clone();
    limited_cfg.max_candidate_comparisons = 1;
    for callback in ["() =>", "function()", "async () =>"] {
        for (right_wrapper, shared_calls) in [
            ("register", ""),
            ("otherWrapper", ""),
            ("register", "load(); save(); render();"),
        ] {
            for (right_assertion, expected) in [
                ("expect(state).toBe('ready');", true),
                ("(expect as any)(state).toBe('ready');", true),
                ("expect(state).toBe('idle');", false),
                ("expect(state).not.toBe('ready');", false),
                ("expect(state).toBe(external);", false),
                (
                    "expect(state).toBe('ready'); expect(state).toBe('idle');",
                    false,
                ),
            ] {
                let defs = definitions(&format!("Then('parcel is ready', ({{state}}) => register({callback} {{ {shared_calls} expect(state).toBe('ready'); }})); Then('parcel is now ready', ({{state}}) => {right_wrapper}({callback} {{ {shared_calls} {right_assertion} }}));"));
                for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                    if !expected {
                        assert!(
                            definition_pair_candidates(&pair, &limited_cfg).is_empty(),
                            "{right_assertion}"
                        );
                    }
                    let findings = analyze(pair, Vec::new(), &cfg).unwrap().findings;
                    assert_eq!(
                        findings.iter().any(|f| matches!(
                            f.rule,
                            Rule::DuplicateHandler
                                | Rule::NearDuplicateStep
                                | Rule::ParameterizationCandidate
                        )),
                        expected,
                        "{callback} {shared_calls} {right_assertion}"
                    );
                }
            }
        }
    }
}

#[test]
fn repeated_commonjs_loads_share_only_guarded_mutation_provenance() {
    let (_dir, cfg) = config();
    for (binding, trusted) in [
        ("const {[key]: check} = require('@playwright/test'); check.objectContaining = replacement;", false),
        ("const {expect: check} = require('@playwright/test'); delete check.objectContaining;", false),
        ("let check; ({['expect']: check} = require('@playwright/test')); check.objectContaining = replacement;", false),
        ("const {expect: check = fallback} = require('@playwright/test'); check.objectContaining = replacement;", false),
        ("const other = require('@playwright/test'); other.expect.objectContaining = replacement;", false),
        ("const check = require('@playwright/test').expect; check.objectContaining = replacement;", false),
        ("function mutate() { const {expect: check} = require('@playwright/test'); check.objectContaining = replacement; }", false),
        ("const {[key]: check} = require('@jest/globals'); check.objectContaining = replacement;", true),
        ("function mutate(require) { const {expect: check} = require('@playwright/test'); check.objectContaining = replacement; }", true),
        ("{ const require = localLoader; const {expect: check} = require('@playwright/test'); check.objectContaining = replacement; }", true),
        ("const {[key]: check} = require('@playwright/test');", true),
        ("let {expect: check} = require('@playwright/test'); check = replacement;", true),
        ("const {other: check} = require('@playwright/test'); check.objectContaining = replacement;", true),
    ] {
        for before in [false, true] {
            let namespace = "const api = require('@playwright/test');";
            let setup = if before { format!("{binding} {namespace}") } else { format!("{namespace} {binding}") };
            let defs = definitions(&format!("{setup} Then('parcel is ready', ({{state}}) => api.expect(state).toEqual(api.expect.objectContaining({{role:'admin'}}))); Then('shipment readiness confirmed', ({{state}}) => api.expect(state).toEqual(api.expect.objectContaining({{role:'admin'}})));") );
            assert!(defs.iter().all(|d| d.handler.comparable == trusted), "{setup}");
            let result = analyze(defs, Vec::new(), &cfg).unwrap();
            assert_eq!(result.findings.iter().any(|f| matches!(f.rule, Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate)), trusted, "{setup}");
        }
    }
    // A module-level custom loader must not gain assertion provenance or contaminate imports.
    let defs = definitions("import * as api from '@playwright/test'; const require = loader; const {[key]: check} = require('@playwright/test'); check.objectContaining = replacement; Then('ready', ({state}) => api.expect(state).toEqual(api.expect.objectContaining({role:'admin'})));");
    assert!(defs[0].handler.comparable);
    let defs = definitions("const {[key]: check} = require('@playwright/test'); Then('ready', ({state}) => check(state).toBe('ready'));");
    assert!(defs[0]
        .handler
        .behavior_signature
        .iter()
        .all(|e| !e.starts_with("assert:")));
}

#[test]
fn destructured_negation_mutations_do_not_establish_handler_equivalence() {
    let (_dir, cfg) = config();
    for factory in ["expect", "api.expect", "api['expect']"] {
        for (alias, trusted) in [
            ("const {not: negated} = FACTORY; negated.objectContaining = replacement;", false),
            ("const {'not': negated} = FACTORY; negated.objectContaining = replacement;", false),
            ("const {['not']: negated} = FACTORY; negated.objectContaining = replacement;", false),
            (r"const {['n\u006ft']: negated} = FACTORY; delete negated.objectContaining;", false),
            ("const {not: negated = fallback} = FACTORY; negated.objectContaining = replacement;", false),
            ("const {not} = FACTORY; not.objectContaining = replacement;", false),
            ("const {not = fallback} = FACTORY; not.objectContaining = replacement;", false),
            ("let negated; ({not: negated} = FACTORY); negated.objectContaining = replacement;", false),
            ("const {other: negated} = FACTORY; negated.objectContaining = replacement;", true),
            ("function local(FACTORY) { const {not} = FACTORY; not.objectContaining = replacement; }", true),
        ] {
            // The shadowing control applies to a lexical identifier, not a namespace expression.
            if alias.starts_with("function") && factory != "expect" { continue; }
            let alias = alias.replace("FACTORY", factory);
            let source = format!("import {{expect}} from '@playwright/test'; import * as api from '@playwright/test'; {alias} Then('parcel is ready', ({{state}}) => {factory}(state).toEqual({factory}.not.objectContaining({{role:'admin'}}))); Then('shipment readiness confirmed', ({{state}}) => {factory}(state).toEqual({factory}.not.objectContaining({{role:'admin'}})));");
            let defs = definitions(&source);
            assert!(defs.iter().all(|d| d.handler.comparable == trusted), "{source}");
            let result = analyze(defs, Vec::new(), &cfg).unwrap();
            assert_eq!(result.findings.iter().any(|f| matches!(f.rule, Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate)), trusted, "{source}");
        }
    }
    let defs = definitions("const {not: check} = require('@playwright/test'); Then('step', ({state}) => check(state).toBe('ready'));");
    assert!(defs[0]
        .handler
        .behavior_signature
        .iter()
        .all(|e| !e.starts_with("assert:")));
}

#[test]
fn direct_generator_calls_do_not_contribute_suspended_body_events() {
    for generator in ["function*", "async function*"] {
        for wrapped in [
            format!("(<any>{generator} () {{ expect(state).toBe('ready'); }})"),
            format!("(({generator} <T>() {{ expect(state).toBe('ready'); }})<string>)"),
        ] {
            let defs = definitions(&format!(
                "Then('state', ({{state}}) => {{ {wrapped}(); }});"
            ));
            assert!(defs[0].handler.behavior_signature.is_empty(), "{wrapped}");
        }
        for body in ["expect(state).toBe('ready');", "save(state); yield state;"] {
            let defs = definitions(&format!(
                "Then('state', ({{state}}) => {{ ({generator} () {{ {body} }})(); }});"
            ));
            assert!(
                defs[0].handler.behavior_signature.is_empty(),
                "{generator} {body}"
            );
        }
        let defs = definitions(&format!("Then('state', () => {{ ({generator} (value = initialize()) {{ save(value); }})(prepare()); }});"));
        assert_eq!(
            defs[0].handler.behavior_signature,
            ["assert:unresolved", "call:prepare"]
        );
        assert!(!defs[0].handler.comparable);
        let defs = definitions(&format!("Then('state', () => register(() => {{ ({generator} (value = initialize()) {{ save(value); }})(prepare()); }}));"));
        assert_eq!(
            defs[0].handler.behavior_signature,
            [
                "call:register",
                "deferred-assert:unresolved",
                "call:prepare"
            ]
        );
        assert!(!defs[0].handler.comparable);
        let defs = definitions(&format!("Then('state', ({{state}}) => register({generator} () {{ expect(state).toBe('ready'); }}));"));
        assert!(
            defs[0]
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("deferred-assert:")),
            "{generator}"
        );
    }
}

#[test]
fn reports_exact_normalized_and_duplicate_handlers_even_when_unused() {
    let definitions = definitions(
        r#"
Given('a user {string}', async (name) => { await save(name); });
Given('a user {string}', async (name) => { await other(name); });
Given('a  user {string}', async (value) => { await third(value); });
Then('the user exists', async (name) => { await save(name); });
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let rules: Vec<_> = result.findings.iter().map(|finding| finding.rule).collect();
    assert!(rules.contains(&Rule::DuplicateMatcher));
    assert!(rules.contains(&Rule::NormalizedMatcher));
    assert!(rules.contains(&Rule::DuplicateHandler));
}

#[test]
fn exact_handlers_require_compatible_assertion_provenance_across_files() {
    let (_directory, config) = config();
    let mut extracted = Vec::new();
    for (index, module) in [
        "@playwright/test",
        "unrelated-assertions",
        "@playwright/test",
    ]
    .into_iter()
    .enumerate()
    {
        let source = format!("import {{ expect }} from '{module}'; Then('the current state is verified {index}', () => expect(state).toBe('ready'));");
        extracted.extend(
            typescript::extract(
                &source,
                &SourceFile {
                    path: PathBuf::from(format!("steps-{index}.ts")),
                    language: SourceLanguage::TypeScript,
                },
            )
            .unwrap(),
        );
    }
    for definitions in [extracted.clone(), extracted.into_iter().rev().collect()] {
        let result = analyze(definitions, Vec::new(), &config).unwrap();
        let findings: Vec<_> = result
            .findings
            .iter()
            .filter(|f| matches!(f.rule, Rule::DuplicateHandler | Rule::NearDuplicateStep))
            .collect();
        assert_eq!(
            findings
                .iter()
                .filter(|f| f.rule == Rule::DuplicateHandler)
                .count(),
            1
        );
        for finding in findings {
            assert_ne!(finding.primary.path, Path::new("steps-1.ts"));
            assert!(finding
                .related
                .iter()
                .all(|location| location.path != Path::new("steps-1.ts")));
        }
    }
}

#[test]
fn unresolved_external_assertion_values_cannot_establish_handler_equivalence() {
    let (_directory, config) = config();
    for (prefix, body, expected_duplicates) in [
        ("function getExpected() { return VALUE; }", "() => { const expected = getExpected(); expect(state).toBe(expected); }", 0),
        ("const external = VALUE;", "() => { const expected = external; expect(state).toBe(expected); }", 0),
        ("const expected = VALUE;", "() => { { const expected = 'local'; } expect(state).toBe(expected); }", 0),
        ("function getExpected() { return VALUE; }", "(expected) => { { var expected = getExpected(); } expect(state).toBe(expected); }", 0),
        ("", "() => expect(state).toSatisfy(actual => actual > 0)", 1),
        ("const external = VALUE;", "() => expect(state).toSatisfy(actual => actual === external)", 0),
        ("", "() => { const expected = 'ready'; const alias = expected; expect(state).toBe(alias); }", 1),
        (
            "const expected = VALUE;",
            "() => expect(state).toBe(expected)",
            0,
        ),
        (
            "",
            "() => { const expected = 'ready'; expect(state).toBe(expected); }",
            1,
        ),
        ("", "(expected) => expect(state).toBe(expected)", 1),
    ] {
        let mut extracted = Vec::new();
        for (index, value) in ["'ready'", "'idle'"].into_iter().enumerate() {
            let source = format!(
                "{} Then('the current state is verified {index}', {body});",
                prefix.replace("VALUE", value)
            );
            extracted.extend(
                typescript::extract(
                    &source,
                    &SourceFile {
                        path: PathBuf::from(format!("steps-{index}.ts")),
                        language: SourceLanguage::TypeScript,
                    },
                )
                .unwrap(),
            );
        }
        let result = analyze(extracted.clone(), Vec::new(), &config).unwrap();
        assert_eq!(
            result
                .findings
                .iter()
                .filter(|f| f.rule == Rule::DuplicateHandler)
                .count(),
            expected_duplicates,
            "{prefix} {body}"
        );
        if expected_duplicates == 0 {
            assert!(!result
                .findings
                .iter()
                .any(|f| f.rule == Rule::NearDuplicateStep));
        }
        extracted[1].matcher = extracted[0].matcher.clone();
        extracted[1].normalized_matcher = extracted[0].normalized_matcher.clone();
        assert!(analyze(extracted, Vec::new(), &config)
            .unwrap()
            .findings
            .iter()
            .any(|f| f.rule == Rule::DuplicateMatcher));
    }
}

#[test]
fn inline_and_local_assertion_values_share_behavior_without_losing_value_precision() {
    let (_directory, config) = config();
    for (declaration, inline, local, expected_match) in [
        ("const expected = 'ready';", "'ready'", "expected", true),
        ("const expected = 'idle';", "'ready'", "expected", false),
        (
            "const first = 'ready'; const expected = first;",
            "'ready'",
            "expected",
            true,
        ),
        ("const expected = 12;", "12", "expected", true),
        ("const expected = true;", "true", "expected", true),
        ("const expected = null;", "null", "expected", true),
        (
            "const expected = 'ready';",
            "{ status: 'ready' }",
            "{ status: expected }",
            true,
        ),
        (
            "const expected = 'ready';",
            "['ready', 'idle']",
            "['idle', expected]",
            false,
        ),
        (
            "let expected = 'ready'; expected = 'idle';",
            "'ready'",
            "expected",
            false,
        ),
        ("const expected = external;", "'ready'", "expected", false),
        (
            "{ const expected = 'ready'; }",
            "'ready'",
            "expected",
            false,
        ),
    ] {
        let source = format!("Then('the parcel status is verified', ({{ state }}) => {{ expect(state).toEqual({inline}); }}); Then('the parcel status is now verified', ({{ state }}) => {{ {declaration} expect(state).toEqual({local}); }});");
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2);
        if expected_match {
            assert_eq!(
                extracted[0].handler.behavior_signature, extracted[1].handler.behavior_signature,
                "{source}"
            );
        }
        for definitions in [extracted.clone(), extracted.into_iter().rev().collect()] {
            let result = analyze(definitions, Vec::new(), &config).unwrap();
            assert_eq!(
                result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::NearDuplicateStep),
                expected_match,
                "{source}"
            );
        }
    }
}

#[test]
fn assertion_trust_requires_real_facades_and_unmodified_namespace_factories() {
    let (_directory, config) = config();
    let valid = "import {Then} from '@cucumber/cucumber'; import * as api from '@playwright/test';";
    let cjs =
        "const {Then} = require('@cucumber/cucumber'); const api = require('@playwright/test');";
    for (prefix, mutation, trusted) in [
        (valid, "const other = api; delete other.expect;", false),
        (cjs, "delete api['expect'];", false),
        (valid, "const other = api; delete other.other;", true),
        (
            valid,
            "function local(api) { const other = api; delete other.expect; }",
            true,
        ),
        (
            valid,
            "const other = api; other.expect = replacement;",
            false,
        ),
        (cjs, "const other = api; other.expect = replacement;", false),
        (
            valid,
            "const other = (api as PW); const last = other; [last.expect] = replacements;",
            false,
        ),
        (valid, "let other; other = api; other['expect']++;", false),
        (
            valid,
            "function mutate() { const other = api; other.expect = replacement; }",
            false,
        ),
        (
            valid,
            "function mutate(other = api) { other.expect = replacement; }",
            false,
        ),
        (
            valid,
            "function local(api, other = api) { other.expect = replacement; }",
            true,
        ),
        (
            valid,
            "let other; other ||= api; other.expect = replacement;",
            false,
        ),
        (
            valid,
            "let other; other &&= api; other.expect = replacement;",
            false,
        ),
        (
            valid,
            "let other; other ??= api; other.expect = replacement;",
            false,
        ),
        (
            valid,
            "let other = ''; other += api; other.expect = replacement;",
            true,
        ),
        (
            valid,
            "const other = api; function mutate() { other.expect = replacement; }",
            false,
        ),
        (
            valid,
            "const other = api; function local(other) { other.expect = replacement; }",
            true,
        ),
        (
            valid,
            "function local(api) { const other = api; other.expect = replacement; }",
            true,
        ),
        (
            valid,
            "const other = api; { const other = local; other.expect = replacement; }",
            true,
        ),
        (
            valid,
            "let other = api; other = local; other.expect = replacement;",
            false,
        ),
        (
            valid,
            "let other = api; let last = other; other = last; last.expect = replacement;",
            false,
        ),
        (
            valid,
            "const other = api; other.unrelated = replacement;",
            true,
        ),
        (
            valid,
            "type other = unknown; const other = api; other.expect = replacement;",
            false,
        ),
        (valid, "", true),
        (valid, "(api).expect = replacement;", false),
        (valid, "(api as PW).expect = replacement;", false),
        (valid, "api!.expect = replacement;", false),
        (valid, "(api satisfies PW).expect = replacement;", false),
        (valid, "(<PW>api).expect = replacement;", false),
        (valid, "((api as PW)!).expect = replacement;", false),
        (valid, "(api as PW)['expect'] = replacement;", false),
        (valid, "[api!.expect] = replacement;", false),
        (valid, "(api as PW).expect++;", false),
        (valid, "(api as PW).other = replacement;", true),
        (
            valid,
            "function local(api) { (api as PW).expect = replacement; }",
            true,
        ),
        (cjs, "", true),
        (cjs, "api.expect = replacement;", false),
        (cjs, r#"api.ex\u0070ect = replacement;"#, false),
        (cjs, r#"api.ex\u{70}ect = replacement;"#, false),
        (cjs, r#"api["\145xpect"] = replacement;"#, false),
        (cjs, r#"api["\x65xpect"] = replacement;"#, false),
        (cjs, r#"api["\u0065xpect"] = replacement;"#, false),
        (cjs, r#"api["\u{65}xpect"] = replacement;"#, false),
        (cjs, r#"api["\x6fther"] = replacement;"#, true),
        (cjs, "api.expect++;", false),
        (cjs, "for (api.expect of replacements) {}", false),
        (cjs, "for (api.expect in replacements) {}", false),
        (cjs, "api.other++;", true),
        (cjs, "for (api.other of replacements) {}", true),
        (
            cjs,
            "function local(api) { api.expect++; for (api.expect of replacements) {} }",
            true,
        ),
        (valid, "api['expect'] = replacement;", false),
        (valid, "({ factory: api.expect } = replacement);", false),
        (valid, "[api.expect] = replacement;", false),
        (valid, "api.expect ||= replacement;", false),
        (valid, "api[key] = replacement;", false),
        (valid, "api.other = replacement;", true),
        (valid, "api['other'] = replacement;", true),
        (
            valid,
            "function unrelated(api) { api.expect = replacement; }",
            true,
        ),
        (
            valid,
            "function mutate() { api.expect = replacement; }",
            false,
        ),
    ] {
        let mut extracted = Vec::new();
        for (index, header) in [format!("{prefix} {mutation}"), valid.to_owned()]
            .iter()
            .enumerate()
        {
            extracted.extend(typescript::extract(
                &format!("{header} Then('the parcel status is verified {index}', ({{state}}) => api.expect(state).toBe('ready'));"),
                &SourceFile { path: PathBuf::from(format!("steps-{index}.ts")), language: SourceLanguage::TypeScript },
            ).unwrap());
        }
        assert_eq!(
            extracted[0]
                .handler
                .behavior_signature
                .iter()
                .any(|e| e.starts_with("assert:")),
            trusted,
            "{prefix} {mutation}"
        );
        for definitions in [extracted.clone(), extracted.into_iter().rev().collect()] {
            let result = analyze(definitions, Vec::new(), &config).unwrap();
            assert_eq!(
                result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::DuplicateHandler),
                trusted,
                "{prefix} {mutation}"
            );
            if !trusted {
                assert!(!result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::NearDuplicateStep));
            }
        }
    }
    for mutation in [
        "function mutate(other = api) { other.expect = replacement; }",
        "let other; other ||= api; other.expect = replacement;",
    ] {
        let source = format!(
            "const {{Then}} = require('@cucumber/cucumber'); const api = require('@playwright/test'); {mutation} Then('the parcel status is verified', ({{state}}) => api.expect(state).toBe('ready'));"
        );
        let extracted = typescript::extract(
            &source,
            &SourceFile {
                path: PathBuf::from("steps.js"),
                language: SourceLanguage::JavaScript,
            },
        )
        .unwrap();
        assert!(
            extracted[0]
                .handler
                .behavior_signature
                .iter()
                .all(|event| !event.starts_with("assert:")),
            "{mutation}"
        );
    }
    for write in [
        "require &&= replacement;",
        "require += replacement;",
        "require++;",
        "for (require of replacements) {}",
    ] {
        let source =
            format!("{write} {cjs} Then('state', ({{state}}) => api.expect(state).toBe('ready'));");
        assert!(
            definitions(&source)[0]
                .handler
                .behavior_signature
                .iter()
                .all(|e| !e.starts_with("assert:")),
            "{write}"
        );
        let source = format!("function local(require) {{ {write} }} {cjs} Then('state', ({{state}}) => api.expect(state).toBe('ready'));");
        assert!(
            definitions(&source)[0]
                .handler
                .behavior_signature
                .iter()
                .any(|e| e.starts_with("assert:")),
            "local {write}"
        );
    }
    for module in [
        "@cucumber/cucumber",
        "cucumber",
        "playwright-bdd",
        "@badeball/cypress-cucumber-preprocessor",
        "cypress-cucumber-preprocessor/steps",
    ] {
        let source = format!("import {{Then, expect as check}} from '{module}'; Then('state', ({{state}}) => check(state).toBe('ready'));");
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 1, "{module}");
        assert!(
            extracted[0]
                .handler
                .behavior_signature
                .iter()
                .all(|e| !e.starts_with("assert:")),
            "{module}"
        );
    }
    let extracted = definitions("import * as expect from '@playwright/test'; expect.expect = replacement; Then('state', ({state}) => expect(state).toBe('ready'));");
    assert!(extracted[0]
        .handler
        .behavior_signature
        .iter()
        .all(|e| !e.starts_with("assert:")));
}

#[test]
fn shorthand_assertions_preserve_property_keys_and_local_values() {
    let (_directory, config) = config();
    for (left, right, expected_duplicate) in [
        (
            "const expected = 'ready';",
            "const expected = 'idle';",
            false,
        ),
        (
            "const expected = 'ready';",
            "const expected = 'ready';",
            true,
        ),
        ("const expected = 'ready';", "const other = 'ready';", false),
        (
            "const expected = external;",
            "const expected = external;",
            false,
        ),
        ("let expected = 'ready';", "let expected = 'idle';", false),
        (
            "{ const expected = 'ready'; }",
            "{ const expected = 'idle'; }",
            false,
        ),
    ] {
        let right_key = if right.contains("other") {
            "other"
        } else {
            "expected"
        };
        let source = format!("Then('the parcel status is verified', ({{ state }}) => {{ {left} expect(state).toEqual({{ expected }}); }}); Then('the parcel status is now verified', ({{ state }}) => {{ {right} expect(state).toEqual({{ {right_key} }}); }});");
        let extracted = definitions(&source);
        for definitions in [extracted.clone(), extracted.into_iter().rev().collect()] {
            let result = analyze(definitions, Vec::new(), &config).unwrap();
            let findings: Vec<_> = result
                .findings
                .iter()
                .filter(|f| {
                    matches!(
                        f.rule,
                        Rule::DuplicateHandler
                            | Rule::NearDuplicateStep
                            | Rule::ParameterizationCandidate
                    )
                })
                .collect();
            assert_eq!(
                findings.len(),
                if expected_duplicate { 2 } else { 0 },
                "{source}: {findings:?}"
            );
            if expected_duplicate {
                assert_eq!(findings[0].rule, Rule::DuplicateHandler);
            }
        }
    }
}

#[test]
fn assertion_precision_covers_member_require_iifes_and_factory_options() {
    let (_directory, config) = config();
    for (prefix, body) in [
        (
            "const check = require('@playwright/test').expect;",
            "() => check(state).toBe(VALUE)",
        ),
        (
            "const check = require('@jest/globals').expect;",
            "() => check(state).toBe(VALUE)",
        ),
        (
            "const check = require('expect').expect;",
            "() => check(state).toBe(VALUE)",
        ),
        ("", "() => { (() => expect(state).toBe(VALUE))(); }"),
        (
            "",
            "() => { (function () { expect(state).toBe(VALUE); })(); }",
        ),
        (
            "",
            "async () => { await (async () => expect(state).toBe(VALUE))(); }",
        ),
        (
            "",
            "() => { ((() => expect(state).toBe(VALUE)) as (() => void))(); }",
        ),
        (
            "",
            "() => expect.poll(() => state, { timeout: VALUE }).toBe('ready')",
        ),
        (
            "",
            "() => expect.poll(() => state, { intervals: [VALUE] }).toBe('ready')",
        ),
    ] {
        for same in [false, true] {
            let source = format!(
                "{prefix} Then('the current state is verified', {}); Then('the current state is verified now', {});",
                body.replace("VALUE", "100"), body.replace("VALUE", if same { "100" } else { "5000" })
            );
            let extracted = definitions(&source);
            assert_eq!(extracted.len(), 2, "{source}");
            assert_eq!(
                extracted[0].handler.behavior_signature == extracted[1].handler.behavior_signature,
                same,
                "{source}"
            );
            let result = analyze(extracted, Vec::new(), &config).unwrap();
            assert_eq!(
                result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::DuplicateHandler),
                same,
                "{source}"
            );
            if !same {
                assert!(
                    !result.findings.iter().any(|f| matches!(
                        f.rule,
                        Rule::NearDuplicateStep | Rule::ParameterizationCandidate
                    )),
                    "{source}: {:?}",
                    result.findings
                );
            }
        }
    }
}

#[test]
fn assertion_precision_keeps_untrusted_bindings_and_callbacks_separate() {
    for (prefix, body) in [
        ("const check = require('unrelated').expect;", "() => check(state).toBe('ready')"),
        ("const check = require('@playwright/test').other;", "() => check(state).toBe('ready')"),
        ("const { expect: check } = require('@playwright/test').expect;", "() => check(state).toBe('ready')"),
        ("function require(name) { return custom; } const check = require('@playwright/test').expect;", "() => check(state).toBe('ready')"),
        ("const check = require('@playwright/test').expect;", "(check) => check(state).toBe('ready')"),
        ("", "() => { register(() => expect(state).toBe('ready')); }"),
        ("", "() => { const callback = () => expect(state).toBe('ready'); register(callback); }"),
        ("", "() => { (function* () { expect(state).toBe('ready'); })(); }"),
    ] {
        let source = format!("{prefix} Then('state', {body});");
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 1, "{source}");
        assert!(extracted[0].handler.behavior_signature.iter().all(|event| !event.starts_with("assert:")), "{source}");
    }
    for options in [
        "external",
        "{ timeout: external }",
        "{ intervals: [external] }",
    ] {
        let extracted = definitions(&format!(
            "Then('state', () => expect.poll(() => state, {options}).toBe('ready'));"
        ));
        assert!(!extracted[0].handler.comparable, "{options}");
    }
    for invocation in [
        "((value) => expect(state).toBe(value))(100)",
        "(value => expect(state).toBe(value))(100)",
        "((value = 100) => expect(state).toBe(value))()",
    ] {
        let extracted = definitions(&format!("Then('state', () => {{ {invocation}; }});"));
        assert!(!extracted[0].handler.comparable, "{invocation}");
    }
    let named = definitions("Then('one', () => { (function first() { expect(state).toBe('ready'); })(); }); Then('two', () => { (function second() { expect(state).toBe('ready'); })(); });");
    assert_eq!(
        named[0].handler.behavior_signature,
        named[1].handler.behavior_signature
    );
    let arguments =
        definitions("Then('state', () => { (() => expect(state).toBe('ready'))(prepare()); });");
    assert_eq!(arguments[0].handler.behavior_signature.len(), 2);
    assert_eq!(arguments[0].handler.behavior_signature[0], "call:prepare");
    assert!(arguments[0].handler.behavior_signature[1].starts_with("assert:"));
}

#[test]
fn nested_argument_callbacks_preserve_behavior_and_scope_boundaries() {
    let (_directory, config) = config();
    for container in [
        "CALLBACK",
        "{ callback: CALLBACK }",
        "[{ nested: [CALLBACK] }]",
        "enabled ? CALLBACK : undefined",
        "enabled && CALLBACK",
        "(undefined, CALLBACK)",
        "({ callback: CALLBACK } as Options)",
    ] {
        for callback in ["() =>", "async () =>", "function ()", "function* ()"] {
            for (left_body, right_body, expected) in [
                (
                    "load(); save(); render();",
                    "load(); save(); render();",
                    true,
                ),
                (
                    "load(); save(); render();",
                    "erase(); reset(); remove();",
                    false,
                ),
                (
                    "expect(state).toBe('ready');",
                    "expect(state).toBe('ready');",
                    true,
                ),
                (
                    "expect(state).toBe('ready');",
                    "expect(state).toBe('idle');",
                    false,
                ),
                (
                    "expect(state).toBe('ready');",
                    "expect(state).toBe(external);",
                    false,
                ),
            ] {
                let argument =
                    |body| container.replace("CALLBACK", &format!("{callback} {{ {body} }}"));
                let defs = definitions(&format!(
                    "Then('parcel is ready', ({{state}}) => register({})); Then('parcel is now ready', ({{state}}) => register({}));",
                    argument(left_body), argument(right_body)
                ));
                assert!(
                    defs[0].handler.behavior_signature.len() > 1,
                    "{container} {callback}"
                );
                assert!(defs.iter().all(|d| d
                    .handler
                    .behavior_signature
                    .iter()
                    .all(|e| !e.starts_with("assert:"))));
                for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                    let findings = analyze(pair, Vec::new(), &config).unwrap().findings;
                    assert_eq!(
                        findings.iter().any(|f| matches!(
                            f.rule,
                            Rule::DuplicateHandler
                                | Rule::NearDuplicateStep
                                | Rule::ParameterizationCandidate
                        )),
                        expected,
                        "{container} {callback} {right_body}"
                    );
                }
            }
        }
        for callback in ["value => save(value)", "function (value) { save(value); }"] {
            let argument = container.replace("CALLBACK", callback);
            let defs = definitions(&format!("Then('parcel is ready', () => register({argument})); Then('parcel is now ready', () => register({argument}));"));
            assert!(
                defs.iter().all(|d| !d.handler.comparable),
                "{container} {callback}"
            );
            let findings = analyze(defs, Vec::new(), &config).unwrap().findings;
            assert!(!findings.iter().any(|f| matches!(
                f.rule,
                Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate
            )));
        }
    }
    for body in [
        "register({callback: () => { const unused = () => erase(); load(); }});",
        "register({callback: () => { function unused() { erase(); } load(); }});",
        "register({callback: () => () => erase()});",
        "register(class { method() { erase(); } });",
        "const unused = {callback: () => erase()}; load();",
    ] {
        let defs = definitions(&format!("Then('scope control', () => {{ {body} }});"));
        assert!(
            !defs[0]
                .handler
                .behavior_signature
                .iter()
                .any(|e| e == "call:erase"),
            "{body}"
        );
    }
}

#[test]
fn callback_calls_retain_discriminating_behavior_without_assertion_promotion() {
    let (_directory, config) = config();
    for callback in ["async () =>", "async function ()", "function* ()"] {
        for (left_wrapper, right_wrapper, right_calls, expected) in [
            (
                "withTransaction",
                "withTransaction",
                "loadOrder(); applyShipping(); commit();",
                false,
            ),
            (
                "alpha",
                "beta",
                "loadCart(); applyDiscount(); save();",
                true,
            ),
        ] {
            let defs = definitions(&format!(
                "When('the admin applies the discount rule', () => {{ {left_wrapper}({callback} {{ loadCart(); applyDiscount(); save(); }}); }});\nWhen('the admin applies the shipping rule', () => {{ {right_wrapper}({callback} {{ {right_calls} }}); }});"
            ));
            assert_eq!(defs[0].handler.behavior_signature.len(), 4);
            assert_eq!(defs[1].handler.behavior_signature.len(), 4);
            for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                let result = analyze(pair, Vec::new(), &config).unwrap();
                assert_eq!(
                    result
                        .findings
                        .iter()
                        .any(|f| f.rule == Rule::NearDuplicateStep),
                    expected,
                    "{callback} {left_wrapper} {right_wrapper} {right_calls}"
                );
                assert!(!result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::DuplicateHandler));
            }
        }
    }
    for body in [
        "register(() => { (() => expect(state).toBe('ready'))(); });",
        "register(((function () { load(); render(); }) as Callback));",
        "register(() => nested(() => load()));",
    ] {
        let defs = definitions(&format!("Then('callback example', () => {{ {body} }});"));
        assert!(defs[0].handler.behavior_signature.len() > 1, "{body}");
        assert!(
            defs[0]
                .handler
                .behavior_signature
                .iter()
                .all(|e| !e.starts_with("assert:")),
            "{body}"
        );
    }
    let conflicting = definitions(
        "Then('callback expects ready', ({state}) => register(() => expect(state).toBe('ready'))); Then('callback expects idle', ({state}) => register(() => expect(state).toBe('idle')));",
    );
    assert_ne!(
        conflicting[0].handler.behavior_signature,
        conflicting[1].handler.behavior_signature
    );
    assert!(conflicting.iter().all(|definition| definition
        .handler
        .behavior_signature
        .iter()
        .any(|event| event.starts_with("deferred-assert:"))));
    let unresolved = definitions(
        "Then('callback unresolved', ({state}) => register(() => expect(state).toBe(external)));",
    );
    assert!(!unresolved[0].handler.comparable);
    for callback in ["value =>", "function (value)", "function* (value)"] {
        let unresolved = definitions(&format!(
            "Then('parameterized callback', ({{state}}) => register({callback} {{ expect(state).toBe(value); }}, externalValue));"
        ));
        assert!(!unresolved[0].handler.comparable, "{callback}");
        assert!(
            unresolved[0]
                .handler
                .behavior_signature
                .iter()
                .any(|event| event == "deferred-assert:unresolved"),
            "{callback}"
        );
    }
    let unresolved_without_assertion = definitions(
        "Then('parameterized callback', () => register(value => save(value), externalValue));",
    );
    assert!(!unresolved_without_assertion[0].handler.comparable);
    assert!(unresolved_without_assertion[0]
        .handler
        .behavior_signature
        .iter()
        .any(|event| event == "deferred-assert:unresolved"));
}

#[test]
fn candidate_buckets_skip_unrelated_pairs_and_keep_exact_groups() {
    let mut unrelated_source = String::new();
    for index in 0..100 {
        unrelated_source.push_str(&format!(
            "Given('unique step {index}', () => action_{index}());\n"
        ));
    }
    let unrelated = definitions(&unrelated_source);
    let (_directory, config) = config();
    assert!(definition_pair_candidates(&unrelated, &config).is_empty());

    let exact = definitions(
        "Given('same', () => one());\nGiven('same', () => two());\nGiven('same', () => three());",
    );
    assert_eq!(definition_pair_candidates(&exact, &config).len(), 2);
}

#[test]
fn candidate_limits_preserve_partial_analysis_and_report_skipped_work() {
    let mut source = String::new();
    for index in 0..143 {
        source.push_str(&format!(
            "Given('operation label {index}', () => perform({index}));\n"
        ));
    }
    let class_definitions = definitions(&source);
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 100;
    config.max_structural_class_comparisons = 20;

    let generated = definition_pair_candidates(&class_definitions, &config);
    assert!(generated.census.truncated);
    assert!(generated.len() <= 100);
    assert_eq!(generated.census.truncated_structural_classes, 1);
    assert!(generated.census.skipped_candidate_comparisons > 0);
    assert!(generated.census.candidate_sources["structuralHandler"].skipped > 0);

    let (outcome, census, _) = analyze_for_cli(class_definitions, Vec::new(), &config).unwrap();
    assert!(!outcome.result.findings.is_empty());
    assert_eq!(outcome.incomplete.len(), 1);
    assert!(outcome.incomplete[0].contains("partial findings are available"));
    let mut expected_census = generated.census;
    expected_census.candidate_sources.insert(
        "matcherOverlap".to_owned(),
        CandidateSourceCensus::default(),
    );
    assert_eq!(census, expected_census);
}

#[test]
fn similarity_work_limits_fail_closed_before_quadratic_pair_verification() {
    let mut long_matchers = definitions(
        "Given('left', () => sharedImplementation());\nGiven('right', () => sharedImplementation());",
    );
    // Just past the matrix budget: `matrix_work` charges `l * r + l + r`, so this many characters
    // costs slightly more than the ceiling. Sizing to the boundary rather than far beyond it keeps
    // the computation finite when the budget is removed, so a regression fails these assertions
    // instead of running long enough to look like a hang.
    let over_budget = "a".repeat(1_010);
    long_matchers[0].matcher = format!("{over_budget}b");
    long_matchers[0].normalized_matcher = long_matchers[0].matcher.clone();
    long_matchers[1].matcher = format!("{over_budget}c");
    long_matchers[1].normalized_matcher = long_matchers[1].matcher.clone();

    let (_directory, config) = config();
    let mut findings = Vec::new();
    let suppressions = super::suppression::SuppressionIndex::new(&config, &long_matchers);
    let pair_analysis =
        analyze_definition_pairs(&long_matchers, &config, &suppressions, &mut findings);
    assert!(pair_analysis.census.truncated);
    assert_eq!(pair_analysis.census.candidate_comparisons_evaluated, 0);
    assert_eq!(pair_analysis.census.skipped_candidate_comparisons, 1);
    assert_eq!(
        pair_analysis.census.candidate_sources["identicalHandler"].evaluated,
        0
    );
    assert_eq!(
        pair_analysis.census.candidate_sources["identicalHandler"].skipped,
        1
    );
    assert!(pair_analysis
        .incomplete
        .as_deref()
        .is_some_and(|error| error.contains("after safety limits")));
    assert!(!findings.iter().any(|finding| matches!(
        finding.rule,
        Rule::DuplicateHandler | Rule::NearDuplicateStep
    )));

    let mut long_handlers = definitions(
        "Given('the account is enabled', () => first());\nGiven('the accounts are enabled', () => second());",
    );
    for (index, definition) in long_handlers.iter_mut().enumerate() {
        definition.handler.alpha_normalized = format!("alpha-{index}");
        definition.handler.structural = format!("structure-{index}");
        definition.handler.behavior_signature = vec!["call:shared-event".to_owned(); 10_000];
    }
    let mut findings = Vec::new();
    let suppressions = super::suppression::SuppressionIndex::new(&config, &long_handlers);
    let pair_analysis =
        analyze_definition_pairs(&long_handlers, &config, &suppressions, &mut findings);
    assert!(pair_analysis.census.truncated);
    assert_eq!(pair_analysis.census.candidate_comparisons_evaluated, 0);
    assert_eq!(pair_analysis.census.skipped_candidate_comparisons, 1);
    assert_eq!(
        pair_analysis.census.candidate_sources["matcherBlocking"].evaluated,
        0
    );
    assert_eq!(
        pair_analysis.census.candidate_sources["matcherBlocking"].skipped,
        1
    );
    assert!(pair_analysis.incomplete.is_some());
}

#[test]
fn suppression_globs_compile_once_and_pair_lookups_share_the_work_budget() {
    let base = definitions("Given('base', () => sharedImplementation());").remove(0);
    let (directory, mut config) = config();
    let long_directory = "nested/".repeat(30);
    let definitions = (0..700)
        .map(|index| {
            let mut definition = base.clone();
            definition.matcher = format!("operation label {index:04}");
            definition.normalized_matcher = definition.matcher.clone();
            definition.location.path = directory
                .path()
                .join(format!("{long_directory}steps-{index}.ts"));
            definition.location.line = index + 1;
            definition
        })
        .collect::<Vec<_>>();
    config.suppressions = (0..1_000)
        .map(|index| SuppressionConfig {
            rule: Rule::DuplicateHandler,
            reason: format!("legacy exception {index}"),
            path: Some(format!("missing-{index}/**")),
            matcher: None,
        })
        .collect();

    let suppressions = super::suppression::SuppressionIndex::new(&config, &definitions);
    assert_eq!(suppressions.compiled_path_count(), 1_000);
    for _ in 0..10 {
        assert!(suppressions
            .find_reason(Rule::DuplicateHandler, &[0, 1])
            .is_none());
    }
    assert_eq!(suppressions.compiled_path_count(), 1_000);
    let unmatched = suppressions.unmatched();
    assert!(unmatched.truncated);
    assert!(unmatched.indices.len() < config.suppressions.len());

    let mut findings = Vec::new();
    let pair_analysis =
        analyze_definition_pairs(&definitions, &config, &suppressions, &mut findings);
    assert!(pair_analysis.census.truncated);
    assert!(pair_analysis.census.candidate_comparisons_evaluated < definitions.len() - 1);
    assert!(pair_analysis
        .incomplete
        .as_deref()
        .is_some_and(|error| error.contains("after safety limits")));
}

#[test]
fn suppression_lookup_borrows_and_bounds_large_reasons_until_a_finding_is_retained() {
    let definitions = definitions("Given('left', () => work()); Given('right', () => work());");
    let (_directory, mut config) = config();
    config.suppressions.push(SuppressionConfig {
        rule: Rule::DuplicateHandler,
        reason: "accepted because migration is in progress ".repeat(10_000),
        path: Some("**".to_owned()),
        matcher: None,
    });

    let suppressions = super::suppression::SuppressionIndex::new(&config, &definitions);
    let reason = suppressions
        .find_reason(Rule::DuplicateHandler, &[0, 1])
        .expect("matching suppression");
    assert!(std::ptr::eq(
        reason.as_ptr(),
        config.suppressions[0].reason.as_ptr()
    ));
    assert_eq!(
        reason.chars().count(),
        crate::resource_limits::MAX_SUPPRESSION_REASON_CHARS
    );

    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let finding = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .expect("duplicate handler finding");
    assert_eq!(
        finding.suppression.as_ref().unwrap().reason.chars().count(),
        crate::resource_limits::MAX_SUPPRESSION_REASON_CHARS
    );
}

#[test]
fn structural_class_limit_preserves_work_from_later_classes() {
    let mut source = String::new();
    for prefix in ["account", "invoice"] {
        for index in 0..6 {
            source.push_str(&format!(
                "Given('{prefix} operation {index}', () => {prefix}Action({index}));\n"
            ));
        }
    }
    let class_definitions = definitions(&source);
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 100;
    config.max_structural_class_comparisons = 2;

    let generated = definition_pair_candidates(&class_definitions, &config);
    assert_eq!(generated.census.truncated_structural_classes, 2);
    assert_eq!(
        generated.census.candidate_sources["structuralHandler"].evaluated,
        4
    );
    assert!((0..6).any(|left| (left + 1..6).any(|right| generated.contains_pair(left, right))));
    assert!((6..12).any(|left| (left + 1..12).any(|right| generated.contains_pair(left, right))));
}

#[test]
fn global_candidate_limit_reports_the_source_that_was_truncated() {
    let definitions = definitions(
        "Given('same', () => one());\nGiven('same', () => two());\nGiven('same', () => three());\nGiven('same', () => four());\nGiven('same', () => five());",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 2;
    config.max_structural_class_comparisons = 100;

    let generated = definition_pair_candidates(&definitions, &config);
    assert_eq!(generated.len(), 2);
    assert!(generated.census.truncated);
    assert_eq!(
        generated.census.candidate_sources["normalizedMatcher"].skipped,
        2
    );
    assert_eq!(
        generated
            .census
            .candidate_sources
            .values()
            .map(|source| source.evaluated)
            .sum::<usize>(),
        generated.len()
    );
}

#[test]
fn candidate_limits_are_inclusive_at_the_exact_boundary() {
    let structural = definitions(
        "Given('operation one', () => perform(1));\nGiven('operation two', () => perform(2));\nGiven('operation three', () => perform(3));",
    );
    let exact = definitions(
        "Given('same', () => one());\nGiven('same', () => two());\nGiven('same', () => three());",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 3;
    config.max_structural_class_comparisons = 3;

    let structural = definition_pair_candidates(&structural, &config);
    assert_eq!(structural.len(), 3);
    assert!(!structural.census.truncated);
    assert_eq!(structural.census.skipped_candidate_comparisons, 0);
    assert_eq!(structural.census.truncated_structural_classes, 0);

    config.max_candidate_comparisons = 2;
    let exact = definition_pair_candidates(&exact, &config);
    assert_eq!(exact.len(), 2);
    assert!(!exact.census.truncated);
    assert_eq!(exact.census.skipped_candidate_comparisons, 0);
}

#[test]
fn candidate_limits_do_not_count_structural_pairs_that_cannot_reach_a_rule() {
    let definitions = definitions(
        "Given('same', () => action(1));\nGiven('same', () => action(2));\nGiven('same', () => action(3));",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 1;
    config.max_structural_class_comparisons = 10;

    let generated = definition_pair_candidates(&definitions, &config);
    assert!(generated.census.truncated);
    assert_eq!(generated.len(), 1);
    assert_eq!(generated.census.skipped_candidate_comparisons, 1);
    assert_eq!(
        generated.census.candidate_sources["normalizedMatcher"].skipped,
        1
    );
    assert_eq!(
        generated.census.candidate_sources["structuralHandler"].skipped,
        0
    );
}

#[test]
fn same_normalized_pairs_do_not_consume_the_structural_limit() {
    let definitions = definitions(
        "Given('same', () => action(1));\nGiven('same', () => action(2));\nGiven('same', () => action(3));",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 3;
    config.max_structural_class_comparisons = 1;

    let generated = definition_pair_candidates(&definitions, &config);
    assert_eq!(generated.len(), 2);
    assert!(!generated.census.truncated);
    assert_eq!(generated.census.skipped_candidate_comparisons, 0);
    assert_eq!(generated.census.truncated_structural_classes, 0);
    assert_eq!(
        generated.census.candidate_sources["normalizedMatcher"].evaluated,
        2
    );
    assert_eq!(
        generated.census.candidate_sources["structuralHandler"].evaluated,
        0
    );
}

#[test]
fn same_normalized_class_does_not_report_false_structural_truncation() {
    let definitions = definitions(
        "Given('same', () => action(1));\nGiven('same', () => action(2));\nGiven('same', () => action(3));\nGiven('same', () => action(4));",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 10;
    config.max_structural_class_comparisons = 1;

    let generated = definition_pair_candidates(&definitions, &config);
    assert!(!generated.census.truncated);
    assert_eq!(generated.census.skipped_candidate_comparisons, 0);
    assert_eq!(
        generated.census.candidate_sources["normalizedMatcher"].evaluated,
        3
    );
    assert_eq!(
        generated.census.candidate_sources["structuralHandler"].evaluated,
        0
    );
}

#[test]
fn structural_overlap_ignores_existing_pairs_within_one_handler_group() {
    let definitions = definitions(
        "Given('first', () => action('same'));\nGiven('second', () => action('same'));\nGiven('third', () => action('third'));\nGiven('fourth', () => action('fourth'));",
    );
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 10;
    config.max_structural_class_comparisons = 1;

    let generated = definition_pair_candidates(&definitions, &config);
    assert!(generated.census.truncated);
    assert_eq!(generated.census.skipped_candidate_comparisons, 4);
    assert_eq!(
        generated.census.candidate_sources["identicalHandler"].evaluated,
        1
    );
}

#[test]
fn trivial_and_unresolved_handlers_do_not_consume_candidate_budgets() {
    for definitions in [
        definitions("Given('one', () => {});\nGiven('two', () => {});"),
        definitions("Given('one', importedHandler);\nGiven('two', anotherImportedHandler);"),
    ] {
        let (_directory, config) = config();
        let generated = definition_pair_candidates(&definitions, &config);
        assert!(generated.is_empty());
        assert_eq!(generated.census.candidate_comparisons_evaluated, 0);
        assert!(!generated.census.truncated);
    }
}

#[test]
fn candidate_limit_diagnostic_bounds_affected_class_locations() {
    let mut source = String::new();
    for class in 0..5 {
        for index in 0..3 {
            source.push_str(&format!(
                "Given('class {class} operation {index}', () => action{class}({index}));\n"
            ));
        }
    }
    let class_definitions = definitions(&source);
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 100;
    config.max_structural_class_comparisons = 1;

    let (outcome, census, _) = analyze_for_cli(class_definitions, Vec::new(), &config).unwrap();
    assert_eq!(census.truncated_structural_classes, 5);
    assert_eq!(outcome.incomplete.len(), 1);
    assert!(outcome.incomplete[0].contains("and 2 more"));

    let definitions = definitions(
        "Given('one', () => action(1));\nGiven('two', () => action(2));\nGiven('three', () => action(3));",
    );
    let (outcome, census, _) = analyze_for_cli(definitions, Vec::new(), &config).unwrap();
    assert_eq!(census.truncated_structural_classes, 1);
    assert!(!outcome.incomplete[0].contains("and 0 more"));
}

#[test]
fn regex_resource_errors_are_preserved_for_cli_reporting_and_library_callers() {
    let definitions = definitions("Given(/a{1000000}/, () => work());");
    let (_directory, config) = config();

    let error = analyze(definitions.clone(), Vec::new(), &config).unwrap_err();
    assert!(error.to_string().contains("regex resource limit"));

    let outcome = analyze_with_diagnostics(definitions, Vec::new(), &config).unwrap();
    assert_eq!(outcome.result.definitions.len(), 1);
    assert_eq!(outcome.incomplete.len(), 1);
}

#[test]
fn equivalence_classes_report_a_spanning_set_instead_of_every_pair() {
    let definitions = definitions(
        "Given('same', () => one());\nGiven('same', () => two());\nGiven('same', () => three());\nGiven('same', () => four());",
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert_eq!(
        result
            .findings
            .iter()
            .filter(|finding| finding.rule == Rule::DuplicateMatcher)
            .count(),
        3
    );
}

#[test]
fn large_equivalence_classes_report_one_stable_cluster() {
    let definitions = definitions(
        "Given('same', () => one());\nGiven('same', () => two());\nGiven('same', () => three());\nGiven('same', () => four());\nGiven('same', () => five());",
    );
    let (_directory, config) = config();
    let result = analyze(definitions.clone(), Vec::new(), &config).unwrap();
    let duplicate_matcher = result
        .findings
        .iter()
        .filter(|finding| finding.rule == Rule::DuplicateMatcher)
        .collect::<Vec<_>>();

    assert_eq!(duplicate_matcher.len(), 1);
    let finding = duplicate_matcher[0];
    assert_eq!(finding.related.len(), 4);
    assert!(finding.evidence.comparison.is_none());
    let cluster = finding.evidence.cluster.as_ref().unwrap();
    assert_eq!(cluster.member_count, 5);
    assert_eq!(cluster.definition_fingerprints.len(), 5);
    assert_eq!(cluster.pair_findings_collapsed, 4);
    assert!(!cluster.members_truncated);

    let duplication = DuplicationThreshold::from_result(&result, 100.0);
    assert_eq!(duplication.duplicated_definitions, 5);
    assert_eq!(duplication.percentage, 100.0);

    let mut reversed = definitions;
    reversed.reverse();
    let reordered = analyze(reversed, Vec::new(), &config).unwrap();
    let reordered_finding = reordered
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateMatcher)
        .unwrap();
    assert_eq!(
        crate::modes::finding_fingerprint(finding),
        crate::modes::finding_fingerprint(reordered_finding)
    );
}

#[test]
fn inline_suppression_applies_to_pair_findings() {
    let definitions = definitions(
        r#"
// cuke-dedup:ignore duplicate-matcher -- intentionally split setup paths
Given('same step', () => first());
Given('same step', () => second());
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let duplicate = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateMatcher)
        .unwrap();
    assert_eq!(
        duplicate
            .suppression
            .as_ref()
            .map(|value| value.reason.as_str()),
        Some("intentionally split setup paths")
    );
}

#[test]
fn wording_drift_with_same_handler_is_near_duplicate() {
    let definitions = definitions(
        r#"
Then('the item is visible', async () => { await expect(item).toBeVisible(); });
Then('the items are visible', async () => { await expect(item).toBeVisible(); });
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::DuplicateHandler));
}

#[test]
fn matcher_blocking_finds_near_wording_across_related_handler_shapes() {
    let definitions = definitions(
        r##"
Given("I am on login page", async function () {
  await this.page.goto("/login");
  await this.page.fill("#email", "user@example.test");
});
Given("I am on the login page", async function () {
  await this.page.goto("/login");
  await this.page.fill("#email", "user@example.test");
  await this.page.waitForLoadState();
});
"##,
    );
    assert_ne!(
        definitions[0].handler.structural,
        definitions[1].handler.structural
    );
    assert!(handler_similarity(&definitions[0], &definitions[1]) >= 0.6);
    let (_directory, config) = config();
    let candidates = definition_pair_candidates(&definitions, &config);
    assert!(candidates.contains_pair(0, 1));
    assert_eq!(
        candidates.census.candidate_sources["matcherBlocking"].evaluated,
        1
    );

    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn matcher_blocking_rejects_similar_wording_without_handler_agreement() {
    let definitions = definitions(
        r##"
Given("I am on login page", async function () {
  await this.page.goto("/login");
  await this.page.fill("#email", "user@example.test");
});
Given("I am on the login page", async function () {
  await unrelatedAudit();
  await unrelatedNotification();
});
"##,
    );
    let (_directory, config) = config();
    assert!(definition_pair_candidates(&definitions, &config).is_empty());
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn matcher_blocking_semantic_boundary_is_table_driven() {
    struct Case {
        name: &'static str,
        left_handler: &'static str,
        right_handler: &'static str,
        expected_near: bool,
        expected_similarity: f64,
    }

    let cases = [
        Case {
            name: "one shared action out of two reaches the boundary",
            left_handler: "async function () { await this.page.goto('/login'); }",
            right_handler: "async function () { await this.page.goto('/login'); await this.page.waitForLoadState(); }",
            expected_near: true,
            expected_similarity: 0.5,
        },
        Case {
            name: "direct and fluent calls share their terminal action",
            left_handler: "async ({ page }) => { await page.click('#save'); }",
            right_handler: "async ({ page }) => { await page.locator('#save').click(); }",
            expected_near: true,
            expected_similarity: 0.5,
        },
        Case {
            name: "unrelated awaited calls do not share synthetic behavior",
            left_handler: "async () => { await loadAccount(); }",
            right_handler: "async () => { await writeAudit(); }",
            expected_near: false,
            expected_similarity: 0.0,
        },
        Case {
            name: "receiver names remain semantically distinct",
            left_handler: "async () => { await page.click('#save'); }",
            right_handler: "async () => { await audit.click('#save'); }",
            expected_near: false,
            expected_similarity: 0.0,
        },
        Case {
            name: "control flow alone cannot establish handler agreement",
            left_handler: "() => { if (ready) return first; return second; }",
            right_handler: "() => { if (active) return third; }",
            expected_near: false,
            expected_similarity: 2.0 / 3.0,
        },
        Case {
            name: "one shared action out of three remains below the boundary",
            left_handler: "async ({ page }) => { await page.goto('/'); await page.fill('#x', 'x'); await page.click('#save'); }",
            right_handler: "async ({ page }) => { await page.goto('/'); await page.reload(); await page.screenshot(); }",
            expected_near: false,
            expected_similarity: 1.0 / 3.0,
        },
        Case {
            name: "different terminal operations do not collide",
            left_handler: "async ({ page }) => { await page.click('#save'); }",
            right_handler: "async ({ page }) => { await page.fill('#save', 'value'); }",
            expected_near: false,
            expected_similarity: 0.0,
        },
    ];

    let (_directory, config) = config();
    for case in cases {
        let definitions = definitions(&format!(
            "Given('I am on login page', {}); Given('I am on the login page', {});",
            case.left_handler, case.right_handler
        ));
        let similarity = handler_similarity(&definitions[0], &definitions[1]);
        assert!(
            (similarity - case.expected_similarity).abs() < f64::EPSILON,
            "{}: {similarity}",
            case.name
        );
        let result = analyze(definitions, Vec::new(), &config).unwrap();
        assert_eq!(
            result
                .findings
                .iter()
                .any(|finding| finding.rule == Rule::NearDuplicateStep),
            case.expected_near,
            "{}",
            case.name
        );
    }
}

#[test]
fn matcher_blocking_finds_near_members_outside_an_identical_handler_spanning_tree() {
    let definitions = definitions(
        r#"
Given('completely unrelated setup', () => sharedImplementation());
Given('the account is enabled', () => sharedImplementation());
Given('the accounts are enabled', () => sharedImplementation());
"#,
    );
    let (_directory, config) = config();
    let candidates = definition_pair_candidates(&definitions, &config);
    assert!(candidates.contains_pair(1, 2));
    assert!(candidates.census.candidate_sources["matcherBlocking"].evaluated >= 1);

    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let near = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::NearDuplicateStep)
        .expect("near wording pair");
    let comparison = near.evidence.comparison.as_ref().unwrap();
    assert_eq!(
        [
            comparison.left_matcher.as_str(),
            comparison.right_matcher.as_str()
        ],
        ["the account is enabled", "the accounts are enabled"]
    );
}

#[test]
fn matcher_blocking_keeps_alpha_identical_handlers_with_empty_behavior_signatures() {
    let definitions = definitions(
        r#"
Given('completely unrelated setup', () => world.value);
Given('the account is enabled', () => world.value);
Given('the accounts are enabled', () => world.value);
"#,
    );
    assert!(definitions
        .iter()
        .all(|definition| definition.handler.behavior_signature.is_empty()));
    assert!(definitions
        .iter()
        .all(|definition| definition.handler.comparable && !definition.handler.trivial));

    let (_directory, config) = config();
    let candidates = definition_pair_candidates(&definitions, &config);
    assert!(candidates.contains_pair(1, 2));
    assert!(candidates.census.candidate_sources["matcherBlocking"].evaluated >= 1);

    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn matcher_blocking_respects_the_global_candidate_limit() {
    let mut definitions = definitions(
        r#"
Given('account operation one', () => first());
Given('account operation two', () => second());
Given('account operation three', () => third());
Given('account operation four', () => fourth());
"#,
    );
    for (index, definition) in definitions.iter_mut().enumerate() {
        definition.handler.alpha_normalized = format!("alpha-{index}");
        definition.handler.structural = format!("structure-{index}");
        definition.handler.behavior_signature =
            vec!["call:open".to_owned(), "call:fill".to_owned()];
    }
    let (_directory, mut config) = config();
    config.max_candidate_comparisons = 2;
    let generated = definition_pair_candidates(&definitions, &config);
    assert_eq!(generated.len(), 2);
    assert!(generated.census.truncated);
    assert_eq!(
        generated.census.candidate_sources["matcherBlocking"].evaluated,
        2
    );
    assert_eq!(
        generated.census.candidate_sources["matcherBlocking"].skipped,
        1
    );
}

#[test]
fn homogeneous_handler_groups_generate_linear_candidates() {
    let mut source = String::new();
    for index in 0..2_000 {
        source.push_str(&format!(
            "Given('homogeneous handler wording {index}', () => sharedImplementation());\n"
        ));
    }
    let definitions = definitions(&source);
    let (_directory, config) = config();
    assert!(definition_pair_candidates(&definitions, &config).len() <= definitions.len() * 2);
}

#[test]
fn literal_handler_differences_prefer_parameterization_over_near_wording() {
    let definitions = definitions(
        r#"
Then('the save button is shown', async ({ page }) => { await expect(page.locator('#save')).toBeVisible(); });
Then('the save buttons are shown', async ({ page }) => { await expect(page.locator('#saves')).toBeVisible(); });
When('再生ボタンを押す', async ({ page }) => { await page.click('#play'); });
When('停止ボタンを押す', async ({ page }) => { await page.click('#stop'); });
"#,
    );
    assert_eq!(
        definitions[0].handler.structural,
        definitions[1].handler.structural
    );
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    let similarity = matcher_similarity(&definitions[0], &definitions[1]);
    assert!(is_near_matcher(
        &definitions[0],
        &definitions[1],
        similarity
    ));
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::ParameterizationCandidate));
}

#[test]
fn empty_handlers_and_disjoint_placeholder_types_do_not_fail_analysis() {
    let definitions = definitions(
        r#"
Given('an integer {int}', () => {});
Given('a string {string}', () => {});
Given('another empty step', () => {});
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result.findings.iter().any(|finding| matches!(
        finding.rule,
        Rule::DuplicateHandler | Rule::NormalizedMatcher
    )));
}

#[test]
fn semantically_distinct_matchers_do_not_become_error_equivalent() {
    let definitions = definitions(
        r#"
Given(/^I wait (\d+) seconds$/, () => first());
Given(/^I wait (a few|several) seconds$/, () => second());
Given('custom {int}', () => third());
Given('custom {INT}', () => fourth());
Given(/^literal collision$/i, () => fifth());
Given('literal collision /i', () => sixth());
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NormalizedMatcher));
}

#[test]
fn awaited_stub_handlers_do_not_create_duplicate_handler_storms() {
    let definitions = definitions(
        r#"
async function notImplemented() { await pending(); }
Given('stub one', notImplemented);
Given('stub two', notImplemented);
Given('stub three', notImplemented);
Given('stub four', notImplemented);
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::DuplicateHandler));
}

#[test]
fn similarity_rejects_opposite_or_different_actions() {
    for (left, right) in [
        ("the account is active", "the account is inactive"),
        ("the user can log in", "the user cannot log in"),
    ] {
        let definitions = definitions(&format!(
            "Then('{left}', () => work()); Then('{right}', () => work());"
        ));
        let similarity = matcher_similarity(&definitions[0], &definitions[1]);
        assert!(!is_near_matcher(
            &definitions[0],
            &definitions[1],
            similarity
        ));
    }
}

#[test]
fn matcher_similarity_gates_are_pinned_at_short_and_long_boundaries() {
    struct Case {
        name: &'static str,
        left: &'static str,
        right: &'static str,
        similarity: f64,
        expected: bool,
    }

    for case in [
        Case {
            name: "twelve characters accept the short boundary",
            left: "abcdefghijkl",
            right: "abcdefghijkx",
            similarity: 0.92,
            expected: true,
        },
        Case {
            name: "twelve characters reject below the short boundary",
            left: "abcdefghijkl",
            right: "abcdefghijkx",
            similarity: 0.919,
            expected: false,
        },
        Case {
            name: "thirteen characters accept the long boundary",
            left: "abcdefghijklm",
            right: "abcdefghijklz",
            similarity: 0.90,
            expected: true,
        },
        Case {
            name: "thirteen characters reject below the long boundary",
            left: "abcdefghijklm",
            right: "abcdefghijklz",
            similarity: 0.899,
            expected: false,
        },
        Case {
            name: "negation wins over a high similarity score",
            left: "user is active",
            right: "user is not active",
            similarity: 0.99,
            expected: false,
        },
    ] {
        let definitions = definitions(&format!(
            "Then('{}', () => work()); Then('{}', () => work());",
            case.left, case.right
        ));
        assert_eq!(
            is_near_matcher(&definitions[0], &definitions[1], case.similarity),
            case.expected,
            "{}",
            case.name
        );
    }
}

#[test]
fn matcher_similarity_reports_the_stronger_normalized_score() {
    let mut pair = definitions("Given('left', () => first()); Given('right', () => second());");
    for (left, right) in [("", ""), ("kitten", "sitting"), ("account", "accounts")] {
        pair[0].normalized_matcher = left.to_owned();
        pair[1].normalized_matcher = right.to_owned();
        let expected = if left.is_empty() && right.is_empty() {
            1.0
        } else {
            let longest = left.chars().count().max(right.chars().count());
            let edit = 1.0 - strsim::levenshtein(left, right) as f64 / longest as f64;
            edit.max(strsim::jaro_winkler(left, right))
        };
        assert!(
            (matcher_similarity(&pair[0], &pair[1]) - expected).abs() < f64::EPSILON,
            "{left:?} and {right:?}"
        );
    }
}

#[test]
fn handler_similarity_contract_is_table_driven() {
    let mut base = definitions("Given('left', () => first()); Given('right', () => second());");
    base[0].handler.alpha_normalized = "alpha-left".to_owned();
    base[1].handler.alpha_normalized = "alpha-right".to_owned();
    base[0].handler.structural = "structure-left".to_owned();
    base[1].handler.structural = "structure-right".to_owned();

    let cases = [
        (
            "alpha equivalence",
            "same",
            "same",
            "left",
            "right",
            vec!["open"],
            vec!["open"],
            1.0,
        ),
        (
            "alpha equivalence with conflicting behavior",
            "same",
            "same",
            "left",
            "right",
            vec!["open"],
            vec!["close"],
            0.0,
        ),
        (
            "structural and behavioral equivalence",
            "left",
            "right",
            "same",
            "same",
            vec!["open"],
            vec!["open"],
            0.95,
        ),
        (
            "structural equivalence with conflicting behavior",
            "left",
            "right",
            "same",
            "same",
            vec!["open"],
            vec!["close"],
            0.0,
        ),
        (
            "ordered behavior overlap",
            "left",
            "right",
            "left",
            "right",
            vec!["open", "fill", "save"],
            vec!["open", "save", "notify"],
            2.0 / 3.0,
        ),
        (
            "no behavior",
            "left",
            "right",
            "left",
            "right",
            vec![],
            vec![],
            0.0,
        ),
    ];

    for (
        name,
        left_alpha,
        right_alpha,
        left_structure,
        right_structure,
        left_events,
        right_events,
        expected,
    ) in cases
    {
        let mut pair = base.clone();
        pair[0].handler.alpha_normalized = left_alpha.to_owned();
        pair[1].handler.alpha_normalized = right_alpha.to_owned();
        pair[0].handler.structural = left_structure.to_owned();
        pair[1].handler.structural = right_structure.to_owned();
        pair[0].handler.behavior_signature = left_events.into_iter().map(str::to_owned).collect();
        pair[1].handler.behavior_signature = right_events.into_iter().map(str::to_owned).collect();
        assert!(
            (handler_similarity(&pair[0], &pair[1]) - expected).abs() < f64::EPSILON,
            "{name}"
        );
    }
}

#[test]
fn duplicate_matcher_components_are_invariant_to_definition_input_order() {
    let mut ordered = definitions(
        "Given('same', () => first());\nGiven('same', () => second());\nGiven('same', () => third());",
    );
    for (index, definition) in ordered.iter_mut().enumerate() {
        definition.location.path = PathBuf::from(format!("definition-{index}.ts"));
    }
    let (_directory, config) = config();

    fn component_members(result: &AnalysisResult) -> Vec<String> {
        let mut paths = result
            .findings
            .iter()
            .filter(|finding| finding.rule == Rule::DuplicateMatcher)
            .flat_map(|finding| std::iter::once(&finding.primary).chain(&finding.related))
            .map(|location| location.path.to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        paths.sort();
        paths.dedup();
        paths
    }

    let expected = [
        "definition-0.ts".to_owned(),
        "definition-1.ts".to_owned(),
        "definition-2.ts".to_owned(),
    ];
    for permutation in [[0, 1, 2], [2, 1, 0], [0, 2, 1], [1, 0, 2]] {
        let definitions = permutation
            .into_iter()
            .map(|index| ordered[index].clone())
            .collect();
        let result = analyze(definitions, Vec::new(), &config).unwrap();
        assert_eq!(component_members(&result), expected);
        assert_eq!(
            result
                .findings
                .iter()
                .filter(|finding| finding.rule == Rule::DuplicateMatcher)
                .count(),
            2
        );
    }
}

#[test]
fn shared_context_does_not_override_parameterization_evidence() {
    for (left, right) in [
        (
            "I click the save button on the checkout summary page",
            "I click the cancel button on the checkout summary page",
        ),
        (
            "I select the first row of the table",
            "I select the last row of the table",
        ),
        (
            "the advanced reporting feature is enabled for this account",
            "the advanced reporting feature is disabled for this account",
        ),
    ] {
        let definitions = definitions(&format!(
            "Then('{left}', () => choose('left')); Then('{right}', () => choose('right'));"
        ));
        let (_directory, config) = config();
        let result = analyze(definitions, Vec::new(), &config).unwrap();
        assert!(result
            .findings
            .iter()
            .any(|finding| finding.rule == Rule::ParameterizationCandidate));
        assert!(!result
            .findings
            .iter()
            .any(|finding| finding.rule == Rule::NearDuplicateStep));
    }
}

#[test]
fn path_and_matcher_suppression_must_select_the_same_definition() {
    let mut definitions =
        definitions("Given('left matcher', () => work()); Given('right matcher', () => work());");
    let (directory, mut config) = config();
    definitions[0].location.path = directory.path().join("left.ts");
    definitions[1].location.path = directory.path().join("right.ts");
    config.suppressions.push(SuppressionConfig {
        rule: Rule::DuplicateHandler,
        reason: "must not span definitions".to_owned(),
        path: Some("left.ts".to_owned()),
        matcher: Some("right matcher".to_owned()),
    });
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let finding = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap();
    assert!(finding.suppression.is_none());

    config.suppressions[0].path = Some("*.ts".to_owned());
    config.suppressions[0].matcher = Some("missing matcher".to_owned());
    let result = analyze(result.definitions, Vec::new(), &config).unwrap();
    let finding = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap();
    assert!(finding.suppression.is_none());
}

#[test]
fn suppression_path_globs_remain_root_relative() {
    let mut definitions =
        definitions("Given('left matcher', () => work()); Given('right matcher', () => work());");
    let (_directory, mut config) = config();
    definitions[0].location.path = config.root.join("root.ts");
    definitions[1].location.path = config.root.join("nested/steps.ts");
    config.suppressions.push(SuppressionConfig {
        rule: Rule::DuplicateHandler,
        reason: "root files only".to_owned(),
        path: Some("*.ts".to_owned()),
        matcher: None,
    });
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let finding = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap();
    assert!(finding.suppression.is_some());

    config.suppressions[0].path = Some("steps.ts".to_owned());
    let result = analyze(result.definitions, Vec::new(), &config).unwrap();
    let finding = result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap();
    assert!(finding.suppression.is_none());
}

#[test]
fn path_suppression_requires_every_definition_in_a_pair_to_be_in_scope() {
    let mut definitions =
        definitions("Given('left matcher', () => work()); Given('right matcher', () => work());");
    let (_directory, mut config) = config();
    definitions[0].location.path = config.root.join("legacy/left.ts");
    definitions[1].location.path = config.root.join("current/right.ts");
    config.suppressions.push(SuppressionConfig {
        rule: Rule::DuplicateHandler,
        reason: "legacy directory only".to_owned(),
        path: Some("legacy/**".to_owned()),
        matcher: None,
    });

    let result = analyze(definitions.clone(), Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap()
        .suppression
        .is_none());

    definitions[1].location.path = config.root.join("legacy/right.ts");
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .find(|finding| finding.rule == Rule::DuplicateHandler)
        .unwrap()
        .suppression
        .is_some());
}

#[test]
fn suppression_directory_patterns_and_unmatched_detection_share_semantics() {
    let mut definitions = definitions("Given('legacy', () => work());");
    let (_directory, mut config) = config();
    definitions[0].location.path = config.root.join("legacy/nested/steps.ts");
    config.suppressions.push(SuppressionConfig {
        rule: Rule::DuplicateHandler,
        reason: "legacy tree".to_owned(),
        path: Some("legacy/".to_owned()),
        matcher: None,
    });
    assert!(
        super::suppression::SuppressionIndex::new(&config, &definitions)
            .unmatched()
            .indices
            .is_empty()
    );

    config.suppressions[0].path = Some("missing/**".to_owned());
    assert_eq!(
        super::suppression::SuppressionIndex::new(&config, &definitions)
            .unmatched()
            .indices,
        [0]
    );
}

#[test]
fn opposite_assertions_are_not_duplicate_handlers() {
    let definitions = definitions(
        r#"
Then('the item is visible', async () => { await expect(item).toBeVisible(); });
Then('the item is hidden', async () => { await expect(item).not.toBeVisible(); });
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::DuplicateHandler));
}

#[test]
fn similar_matchers_on_different_assertion_subjects_are_not_near_duplicates() {
    let definitions = definitions(
        r#"
Then('the settings panel shows the primary account field', async ({ page }, expected) => {
  await expect(new AccountForm(page).primaryInput).toHaveValue(expected);
});
Then('the settings panel shows the secondary account field', async ({ page }, expected) => {
  await expect(new AccountForm(page).secondaryInput).toHaveValue(expected);
});
"#,
    );
    assert!(matcher_similarity(&definitions[0], &definitions[1]) >= 0.9);
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn similar_matchers_with_opposite_assertion_chains_are_not_near_duplicates() {
    let definitions = definitions(
        r#"
Then('the navigation drawer state indicator is collapsed', async ({ page }) => {
  await expect(new Navigation(page).drawer).toHaveClass(/collapsed/);
});
Then('the navigation drawer state indicator is expanded', async ({ page }) => {
  await expect(new Navigation(page).drawer).not.toHaveClass(/collapsed/);
});
"#,
    );
    assert!(matcher_similarity(&definitions[0], &definitions[1]) >= 0.9);
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn assertion_only_handlers_reach_near_duplicate_verification() {
    let definitions = definitions(
        r#"
Then('the account badge is visible', async ({ page }) => {
  await expect(new AccountPage(page).badge).toBeVisible();
});
Then('the account badge is now visible', async ({ page }) =>
  expect(new AccountPage(page).badge).toBeVisible()
);
"#,
    );
    assert_ne!(
        definitions[0].handler.structural,
        definitions[1].handler.structural
    );
    let (_directory, config) = config();
    let candidates = definition_pair_candidates(&definitions, &config);
    assert_eq!(
        candidates.census.candidate_sources["matcherBlocking"].evaluated,
        1
    );
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn conflicting_assertion_values_are_not_near_duplicates() {
    let definitions = definitions(
        r#"
Then('the account status indicator shows the first condition', async ({ page }) => {
  await expect(new AccountPage(page).status).toBe('ready');
});
Then('the account status indicator shows the final condition', async ({ page }) => {
  await expect(new AccountPage(page).status).toBe('idle');
});
"#,
    );
    assert!(matcher_similarity(&definitions[0], &definitions[1]) >= 0.9);
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn mostly_matching_ordered_behavior_remains_a_near_duplicate_candidate() {
    let assertions = |last| {
        (0..10)
            .map(|index| {
                let expected = if index == 9 { last } else { "shared" };
                format!("expect(state.field{index}).toBe('{expected}');")
            })
            .collect::<String>()
    };
    let definitions = definitions(&format!(
        "Then('the account workflow is ready', ({{state}}) => {{ {} }}); Then('the account workflow is nearly ready', ({{state}}) => {{ {} }});",
        assertions("first"),
        assertions("second")
    ));
    assert_eq!(
        definitions[0].handler.structural,
        definitions[1].handler.structural
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn decorated_method_metadata_does_not_create_near_duplicate_findings() {
    let definitions = definitions(
        r#"
import { Then } from 'playwright-bdd/decorators';
import { expect } from '@playwright/test';
class StatusSteps {
  @Then('the account status indicator shows the first condition')
  first({ state }) { expect(state).toBe('ready'); }

  @Then('the account status indicator shows the final condition')
  second({ state }) { expect(state).toBe('idle'); }
}
"#,
    );
    assert_eq!(definitions.len(), 2);
    assert!(matcher_similarity(&definitions[0], &definitions[1]) >= 0.9);
    assert_eq!(handler_similarity(&definitions[0], &definitions[1]), 0.0);

    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn incompatible_decorated_method_semantics_veto_near_duplicate_findings() {
    let definitions = definitions(
        r#"
import { Then } from 'playwright-bdd/decorators';
import { expect } from '@playwright/test';
class StatusSteps {
  @Then('the account status indicator is visible')
  first({ state }) { expect(state).toBeVisible(); }

  @Then('the account status indicator is now visible')
  async second({ state }) { expect(state).toBeVisible(); }
}
"#,
    );
    assert_eq!(definitions.len(), 2);
    assert!(matcher_similarity(&definitions[0], &definitions[1]) >= 0.9);
    assert_eq!(handler_similarity(&definitions[0], &definitions[1]), 0.0);

    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::NearDuplicateStep));
}

#[test]
fn pair_evidence_retains_source_and_unicode_safe_matcher_delta() {
    let definitions = definitions(
        r#"
Then('the item is visible', async () => { await expect(item).toBeVisible(); });
Then('the items are visible', async () => { await expect(item).toBeVisible(); });
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    let comparison = result
        .findings
        .iter()
        .find_map(|finding| finding.evidence.comparison.as_ref())
        .expect("pair comparison");
    assert_eq!(comparison.matcher_diff.prefix, "the item");
    assert_eq!(comparison.matcher_diff.left_change, " is");
    assert_eq!(comparison.matcher_diff.right_change, "s are");
    assert_eq!(comparison.matcher_diff.suffix, " visible");
    assert!(comparison.left_handler.contains("toBeVisible"));
}

#[test]
fn concrete_feature_step_detects_ambiguity_and_usage() {
    let definitions = definitions(
        r#"
Given('a user named {word}', () => { makeUser(); });
Given(/^a user named .+$/, () => { makeOtherUser(); });
"#,
    );
    let steps = gherkin::extract(
        "Feature: Users\n  Scenario: Create\n    Given a user named Ada",
        Path::new("test.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert!(result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::AmbiguousStep));
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::UnusedDefinition));
}

#[test]
fn scenario_outline_rows_and_case_insensitive_regexes_count_as_usage() {
    let definitions = definitions(
        r#"
Given('I have {int} items', () => { count(); });
Then(/^THE USER EXISTS$/i, () => { verify(); });
"#,
    );
    let steps = gherkin::extract(
        r#"
Feature: Outline
  Scenario Outline: Count
Given I have <count> items
Then the user exists
Examples:
  | count |
  | 2     |
"#,
        Path::new("outline.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::UnusedDefinition));
}

#[test]
fn supports_optional_and_alternative_cucumber_expression_syntax() {
    let definitions = definitions(
        r#"
Given('I have {int} cucumber(s)', () => { count(); });
Then('they are in my belly/stomach', () => { verify(); });
"#,
    );
    let steps = gherkin::extract(
        "Feature: Food\n  Scenario: Eat\n    Given I have 2 cucumbers\n    Then they are in my stomach",
        Path::new("food.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::UnusedDefinition));
}

#[test]
fn fallback_for_custom_parameters_preserves_optional_and_alternative_syntax() {
    let definitions = definitions(
        r#"
Given('I have {quantity} cucumber(s)', () => { count(); });
Then('they are in my belly/stomach with {mood}', () => { verify(); });
"#,
    );
    let steps = gherkin::extract(
        "Feature: Food\n  Scenario: Eat\n    Given I have several cucumbers\n    Then they are in my belly with joy",
        Path::new("food.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::UnusedDefinition));
}

#[test]
fn named_handlers_with_different_bodies_and_stub_handlers_do_not_duplicate() {
    let mut extracted = Vec::new();
    for (path, source) in [
        (
            "steps/a.ts",
            "function handler() { doAlpha(); } Given('alpha step', handler);",
        ),
        (
            "steps/b.ts",
            "function handler() { doBeta(); } Given('bravo step', handler);",
        ),
        (
            "steps/pending.ts",
            "function pendingStep() { throw new Error('pending'); } Given('pending one', pendingStep); Given('pending two', pendingStep);",
        ),
    ] {
        extracted.extend(
            typescript::extract(
                source,
                &SourceFile {
                    path: PathBuf::from(path),
                    language: SourceLanguage::TypeScript,
                },
            )
            .unwrap(),
        );
    }
    let (_directory, config) = config();
    let result = analyze(extracted, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::DuplicateHandler));
}

#[test]
fn differently_bound_arguments_do_not_report_duplicate_handlers() {
    let definitions = definitions(
        r#"
function handler(value) { process(value); }
Given('first binding', handler.bind(null, 1));
Given('second binding', handler.bind(null, 2));
"#,
    );
    let (_directory, config) = config();
    let result = analyze(definitions, Vec::new(), &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| finding.rule == Rule::DuplicateHandler));
}

#[test]
fn outline_ambiguities_are_deduplicated_by_template_location_and_matches() {
    let definitions = definitions(
        r#"
Given('I have {int} items', () => { first(); });
Given(/^I have \d+ items$/, () => { second(); });
"#,
    );
    let steps = gherkin::extract(
        r#"
Feature: Repeated rows
  Scenario Outline: Counts
Given I have <count> items
Examples:
  | count |
  | 1     |
  | 2     |
  | 3     |
"#,
        Path::new("outline.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert_eq!(
        result
            .findings
            .iter()
            .filter(|finding| finding.rule == Rule::AmbiguousStep)
            .count(),
        1
    );
}

#[test]
fn outline_ambiguities_keep_disjoint_match_sets_separate() {
    let definitions = definitions(
        r#"
Given('value {int}', () => first());
Given(/^value \d+$/, () => second());
Given(/^value 1$/, () => third());
"#,
    );
    let steps = gherkin::extract(
        r#"
Feature: Different sets
  Scenario Outline: Values
    Given value <value>
    Examples:
      | value |
      | 1     |
      | 2     |
"#,
        Path::new("outline.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    let ambiguities = result
        .findings
        .iter()
        .filter(|finding| finding.rule == Rule::AmbiguousStep)
        .collect::<Vec<_>>();
    assert_eq!(ambiguities.len(), 2);
    assert!(ambiguities.iter().all(|finding| finding.related.len() >= 2));
}

#[test]
fn custom_parameter_fallback_marks_usage_but_cannot_prove_ambiguity() {
    let definitions = definitions(
        r#"
Given('I wait {duration}', () => waitDuration());
Given('I wait for the page', () => waitForPage());
"#,
    );
    let steps = gherkin::extract(
        "Feature: Wait\nScenario: custom\nGiven I wait for the page\nGiven I wait 3 seconds\n",
        Path::new("wait.feature"),
    )
    .unwrap();
    let (_directory, config) = config();
    let result = analyze(definitions, steps, &config).unwrap();
    assert!(!result
        .findings
        .iter()
        .any(|finding| { matches!(finding.rule, Rule::AmbiguousStep | Rule::UnusedDefinition) }));
}

#[test]
fn ordered_behavior_similarity_uses_longest_common_subsequence() {
    for (left, right, expected) in [
        (
            vec!["open", "fill", "save"],
            vec!["open", "save", "notify"],
            2,
        ),
        (vec!["open"], vec!["close"], 0),
        (vec!["open", "save"], vec!["open", "save"], 2),
        (vec![], vec!["open"], 0),
    ] {
        let left = left.into_iter().map(str::to_owned).collect::<Vec<_>>();
        let right = right.into_iter().map(str::to_owned).collect::<Vec<_>>();
        assert_eq!(ordered_common_subsequence_len(&left, &right), expected);
        assert_eq!(ordered_common_subsequence_len(&right, &left), expected);
    }
}

#[test]
fn reported_similarity_scores_round_to_three_decimal_places() {
    for (input, expected) in [
        (0.0, 0.0),
        (0.123_4, 0.123),
        (0.123_5, 0.124),
        (0.999_9, 1.0),
    ] {
        assert_eq!(super::similarity::round_score(input), expected);
    }
}

/// Supporting invariants for OPEN-2 / R5190030268-S2, stated on dot access where an assertion is a
/// single atomic event.
///
/// An assertion is identified by its subject, its modifier chain and its expected value, and a
/// change that dropped any one of them would still emit one plausible-looking event. Each part is
/// pinned separately here: erase the subject, the modifier, or the value and this test fails.
#[test]
fn dotted_assertion_events_distinguish_subject_modifier_and_value() {
    let (_directory, config) = config();

    let events = |subject: &str, access: &str, value: &str| {
        let source =
            format!("Then('alpha holds', () => {{ expect({subject}){access}.toBe({value}); }});");
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 1, "{source}");
        extracted[0].handler.behavior_signature.clone()
    };

    let reference = events("alpha", ".not", "'ready'");
    assert!(
        reference
            .iter()
            .any(|event| event.starts_with("assert:expect.not#toBe:")),
        "dot access must record the negation modifier: {reference:?}"
    );
    assert_eq!(
        reference.len(),
        1,
        "an assertion is one atomic event: {reference:?}"
    );

    assert_ne!(
        reference,
        events("beta", ".not", "'ready'"),
        "assertions on different subjects must not share an assertion event"
    );
    assert_ne!(
        reference,
        events("alpha", "", "'ready'"),
        "a negated assertion must not match the same assertion without the modifier"
    );
    assert_ne!(
        reference,
        events("alpha", ".not", "'idle'"),
        "assertions expecting different values must not share an assertion event"
    );

    // Final outcome, not only event inequality: close wording must not equate assertions that
    // differ only in their subject. A change erasing the subject would report a near duplicate.
    let extracted = definitions(
        "Then('the alpha row is aligned', () => { expect(alpha).not.toBe('ready'); }); \
         Then('the beta row is aligned', () => { expect(beta).not.toBe('ready'); });",
    );
    assert_eq!(extracted.len(), 2);
    let result = analyze(extracted, Vec::new(), &config).unwrap();
    assert!(
        !result.findings.iter().any(|finding| matches!(
            finding.rule,
            Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate
        )),
        "close wording must not equate assertions on different subjects: {:?}",
        result.findings
    );
}

/// Shared by the OPEN-1 tests below. Returns, per handler, whether it stayed comparable and its
/// behavior signature, plus the handler rules the pair produced. `write` is inserted between the
/// alias and the two identical step definitions.
///
/// Per handler rather than aggregated: revoking trust for only one of a pair must not be able to
/// match a fully revoked baseline.
fn aliased_matcher_outcome(
    alias: &str,
    write: &str,
    config: &Config,
) -> (Vec<bool>, Vec<Vec<String>>, Vec<Rule>) {
    let usage = "api.expect(state).toEqual(api.expect.not.objectContaining({ role: 'admin' }));";
    let source = format!(
        "const api = require('@playwright/test'); {alias} {write} \
         Then('the parcel is ready', async ({{ state }}) => {{ {usage} }}); \
         Then('the parcel is now ready', async ({{ state }}) => {{ {usage} }});"
    );
    let extracted = definitions(&source);
    assert_eq!(extracted.len(), 2, "{source}");
    let comparable: Vec<bool> = extracted
        .iter()
        .map(|definition| definition.handler.comparable)
        .collect();
    let events: Vec<Vec<String>> = extracted
        .iter()
        .map(|definition| definition.handler.behavior_signature.clone())
        .collect();
    let result = analyze(extracted, Vec::new(), config).unwrap();
    let mut rules: Vec<Rule> = result
        .findings
        .iter()
        .map(|finding| finding.rule)
        .filter(|rule| {
            matches!(
                rule,
                Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate
            )
        })
        .collect();
    rules.sort();
    rules.dedup();
    (comparable, events, rules)
}

const FLAT_MATCHER_ALIAS: &str = "const negated = api.expect.not;";
const MATCHER_WRITE: &str = "negated.objectContaining = replacement;";

/// Reference behaviour for OPEN-1 / R5190030268-S1, stated on the flat alias.
///
/// A write through an alias of a matcher builder revokes assertion trust, and the handler becomes
/// non-comparable rather than silently keeping a stale result. Both sides of that decision are
/// pinned: a write under a path that is not a matcher path must leave trust intact, so a collector
/// that followed any property would fail here.
#[test]
fn flat_matcher_aliases_revoke_trust_only_for_matcher_paths() {
    let (_directory, config) = config();

    let mutated = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, MATCHER_WRITE, &config);
    assert!(
        mutated.0.iter().all(|comparable| !comparable),
        "a write through a flat alias must revoke trust for every handler: {mutated:?}"
    );
    assert!(
        mutated
            .1
            .iter()
            .all(|events| events.iter().any(|event| event == "assert:unresolved")),
        "revoked trust is reported as the unresolved sentinel: {:?}",
        mutated.1
    );
    assert!(
        mutated.2.is_empty(),
        "a non-comparable handler yields no handler finding: {:?}",
        mutated.2
    );

    // Without the write the same alias stays trusted and still reports, so a change that simply
    // suppressed every aliased assertion would fail here.
    let clean = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, "", &config);
    assert!(
        clean.0.iter().all(|comparable| *comparable),
        "an unmutated alias must leave every handler comparable"
    );
    assert!(
        clean.2.contains(&Rule::DuplicateHandler),
        "an unmutated alias must still report identical handlers: {:?}",
        clean.2
    );

    // The other side of the provenance decision: a write under a path that is not a matcher path
    // must not revoke trust, so a collector that followed *any* property would fail here.
    for alias in [
        // A sibling of the trusted factory: the walk stops before the matcher allowlist.
        "const negated = api.other.not;",
        // A member *under* the trusted factory that is not a matcher: this is what pins the
        // allowlist itself, since a change treating every `api.expect.<property>` as a matcher
        // path would revoke trust here while leaving the sibling case untouched.
        "const negated = api.expect.unknownProperty;",
    ] {
        let other = aliased_matcher_outcome(alias, MATCHER_WRITE, &config);
        assert!(
            other.2.contains(&Rule::DuplicateHandler),
            "a write under `{alias}` is not a matcher path and must not revoke trust: {other:?}"
        );
    }
}

/// Every position of an assertion chain, as `label, dotted, dynamic, event prefix`.
///
/// `VALUE` is substituted per definition. `dynamic` selects the property at runtime and must
/// never gain assertion trust. The prefix is the trusted event dot access produces, and pins the
/// factory, modifier and matcher identity so a row cannot be satisfied by an event that lost one
/// of them.
const ASSERTION_CHAIN_POSITIONS: [(&str, &str, &str, &str); 6] = [
    (
        "factory",
        "api.expect(state).not.toBe(VALUE)",
        "api[factoryKey](state).not.toBe(VALUE)",
        "assert:expect.not#toBe:",
    ),
    (
        "modifier",
        "api.expect(state).not.toBe(VALUE)",
        "api.expect(state)[modifierKey].toBe(VALUE)",
        "assert:expect.not#toBe:",
    ),
    (
        "terminal matcher",
        "api.expect(state).not.toBe(VALUE)",
        "api.expect(state).not[matcherKey](VALUE)",
        "assert:expect.not#toBe:",
    ),
    (
        "factory option",
        "api.expect.soft(state).toBe(VALUE)",
        "api.expect[optionKey](state).toBe(VALUE)",
        "assert:expect.soft#toBe:",
    ),
    (
        "nested builder",
        "api.expect(state).toEqual(api.expect.not.objectContaining({ r: VALUE }))",
        "api.expect(state).toEqual(api.expect[modifierKey].objectContaining({ r: VALUE }))",
        "assert:expect#toEqual:",
    ),
    (
        "wrapped modifier",
        "(api.expect(state) as any).not.toBe(VALUE)",
        "(api.expect(state) as any)[modifierKey].toBe(VALUE)",
        "assert:expect.not#toBe:",
    ),
];

/// Two definitions asserting `expression` with `left` and `right` expected values. Returns each
/// handler's behavior signature and the handler rules the pair produced.
///
/// Per handler rather than first-only: resolving one handler correctly while losing trust on the
/// other must not be able to match a fully resolved baseline.
fn assertion_position_outcome(
    expression: &str,
    (left, right): (&str, &str),
    config: &Config,
) -> (Vec<Vec<String>>, Vec<Rule>) {
    let source = format!(
        "const api = require('@playwright/test'); \
         Then('alpha holds', async ({{ state }}) => {{ {}; }}); \
         Then('alpha stands', async ({{ state }}) => {{ {}; }});",
        expression.replace("VALUE", left),
        expression.replace("VALUE", right)
    );
    let extracted = definitions(&source);
    assert_eq!(extracted.len(), 2, "{source}");
    let events: Vec<Vec<String>> = extracted
        .iter()
        .map(|definition| definition.handler.behavior_signature.clone())
        .collect();
    let result = analyze(extracted, Vec::new(), config).unwrap();
    let mut rules: Vec<Rule> = result
        .findings
        .iter()
        .map(|finding| finding.rule)
        .filter(|rule| {
            matches!(
                rule,
                Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate
            )
        })
        .collect();
    rules.sort();
    rules.dedup();
    (events, rules)
}

const CONFLICTING: (&str, &str) = ("'ready'", "'idle'");
const EQUAL: (&str, &str) = ("'ready'", "'ready'");

/// Dot access must resolve every position of an assertion chain to a trusted event that names its
/// factory, modifier and matcher, keep conflicting expected values apart, and still report equal
/// ones. Each position is pinned separately, since resolving one says nothing about the others.
#[test]
fn dotted_access_resolves_every_assertion_position() {
    let (_directory, config) = config();
    for (label, dotted, _, prefix) in ASSERTION_CHAIN_POSITIONS {
        let (events, rules) = assertion_position_outcome(dotted, CONFLICTING, &config);
        for handler in &events {
            assert_eq!(
                handler.len(),
                1,
                "dot access at the {label} position is one atomic event: {handler:?}"
            );
            assert!(
                handler[0].starts_with(prefix),
                "dot access at the {label} position must produce `{prefix}…`: {handler:?}"
            );
        }
        assert!(
            rules.is_empty(),
            "dot access at the {label} position must keep conflicting values apart: {rules:?}"
        );

        // Equal values are a genuine duplicate, so a change that merely stopped comparing this
        // position would fail here rather than satisfy the contract test.
        let (_, equal_rules) = assertion_position_outcome(dotted, EQUAL, &config);
        assert!(
            equal_rules.contains(&Rule::DuplicateHandler),
            "dot access at the {label} position must still report equal values: {equal_rules:?}"
        );

        // The subject is part of the assertion at every position.
        let (other_subject, _) =
            assertion_position_outcome(&dotted.replace("state", "other"), CONFLICTING, &config);
        assert_ne!(
            other_subject[0], events[0],
            "the {label} position must distinguish the asserted subject"
        );
    }
}

/// A property selected at runtime is not provably the factory, modifier, option or matcher it
/// happens to hold, so it must not gain assertion trust at any position. Returning the existing
/// `assert:unresolved` sentinel is an acceptable conservative answer; inventing a trusted event is
/// not, so a resolver that trusted whatever a bracket expression happened to name would fail here.
#[test]
fn dynamic_access_gains_no_assertion_trust_at_any_position() {
    let (_directory, config) = config();
    for (label, _, dynamic, _) in ASSERTION_CHAIN_POSITIONS {
        let (events, _) = assertion_position_outcome(dynamic, CONFLICTING, &config);
        for handler in &events {
            assert!(
                !handler
                    .iter()
                    .any(|event| event.starts_with("assert:") && event != "assert:unresolved"),
                "a runtime-selected property at the {label} position must not gain trust: {handler:?}"
            );
        }
    }
}

/// A modifier chain is ordered and semantic: `not`, the promise modifiers, and the supported
/// factory options each change what an assertion means, and `not.resolves` is not `resolves.not`.
/// A change that sorted, deduplicated or folded the chain would leave every existing test passing.
///
/// Transparent TypeScript wrappers and `await` are the opposite: they carry no meaning and must
/// leave the assertion unchanged.
#[test]
fn modifier_chains_are_ordered_and_semantic() {
    let (_directory, config) = config();

    let events = |expression: &str| {
        let (events, _) = assertion_position_outcome(expression, EQUAL, &config);
        events[0].clone()
    };
    let chain_events = |chain: &str| events(&format!("api.expect(state){chain}.toBe(VALUE)"));

    // Every distinct chain is a distinct trusted assertion. Collected rather than compared
    // pairwise so a collision names both chains.
    let mut seen: Vec<(&str, Vec<String>)> = Vec::new();
    for chain in [
        "",
        ".not",
        ".not.not",
        ".resolves",
        ".rejects",
        ".not.resolves",
        ".resolves.not",
    ] {
        let produced = chain_events(chain);
        assert_eq!(
            produced.len(),
            1,
            "`expect(state){chain}` is one atomic event: {produced:?}"
        );
        assert!(
            produced[0].starts_with("assert:expect"),
            "`expect(state){chain}` must be a trusted assertion: {produced:?}"
        );
        if let Some((other, _)) = seen.iter().find(|(_, events)| *events == produced) {
            panic!(
                "`expect(state){chain}` and `expect(state){other}` share an event: {produced:?}"
            );
        }
        seen.push((chain, produced));
    }

    // A nested asymmetric builder contributes to the expected value, so its own modifier must be
    // part of the assertion. The outer `assert:expect#toEqual:` prefix carries no information about
    // it, so dropping the nested `not` would otherwise go unnoticed.
    assert_ne!(
        events("api.expect(state).toEqual(api.expect.not.objectContaining({ r: VALUE }))"),
        events("api.expect(state).toEqual(api.expect.objectContaining({ r: VALUE }))"),
        "a negated nested builder must not match the same builder without the modifier"
    );

    // `poll` is a supported factory option and names itself in the chain.
    let polled = events("api.expect.poll(() => state, { timeout: 1 }).toBe(VALUE)");
    assert!(
        polled[0].starts_with("assert:expect.poll#"),
        "a polled assertion must record the option: {polled:?}"
    );

    // Final outcome, not only event inequality: near-identical wording must not equate two steps
    // whose only difference is the modifier chain.
    for (left, right) in [
        (".not", ".resolves"),
        (".not.resolves", ".resolves.not"),
        (".not", ".not.not"),
    ] {
        let source = format!(
            "const api = require('@playwright/test'); \
             Then('the alpha row is aligned', async ({{ state }}) => {{ api.expect(state){left}.toBe('ready'); }}); \
             Then('the beta row is aligned', async ({{ state }}) => {{ api.expect(state){right}.toBe('ready'); }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        let result = analyze(extracted, Vec::new(), &config).unwrap();
        assert!(
            !result.findings.iter().any(|finding| matches!(
                finding.rule,
                Rule::DuplicateHandler | Rule::NearDuplicateStep | Rule::ParameterizationCandidate
            )),
            "`{left}` and `{right}` differ in meaning and must not be equated: {:?}",
            result.findings
        );
    }

    // Transparent wrappers and `await` carry no meaning, so they must not change the assertion.
    let plain = chain_events(".not");
    for equivalent in [
        "(api.expect(state) as any).not.toBe(VALUE)",
        "(api.expect(state))!.not.toBe(VALUE)",
        "((api.expect(state) as any)! satisfies Function).not.toBe(VALUE)",
        "await api.expect(state).not.toBe(VALUE)",
    ] {
        assert_eq!(
            events(equivalent),
            plain,
            "`{equivalent}` must resolve to the same assertion as dot access"
        );
    }
}