cuke-dedup 0.12.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
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
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 contract_steps(text: &str) -> Vec<FeatureStep> {
    vec![FeatureStep {
        keyword: "Given".into(),
        text: text.into(),
        location: crate::model::SourceLocation::new("test.feature", 1, 1, 1, 20),
    }]
}

fn contract_finding(defs: Vec<StepDefinition>, config: &Config, rule: Rule) -> bool {
    let outcome = analyze_with_step_usage(defs, vec![], config, &Default::default()).unwrap();
    assert!(outcome.incomplete.is_empty());
    outcome.result.findings.iter().any(|f| f.rule == rule)
}

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 adapter_contracts_preserve_global_and_positional_outcomes() {
    use crate::model::Framework::*;
    let (_directory, config) = config();
    for framework in [
        CucumberJs,
        PlaywrightBdd,
        CypressCucumber,
        JestCucumber,
        VitestCucumber,
        Unknown,
        CucumberRuby,
    ] {
        for matching in [true, false] {
            let mut defs = definitions("Given(/^a user exists$/, () => { load(); save(); }); Given(/^a user exists$/, () => { create(); save(); });");
            for def in &mut defs {
                def.framework = framework;
            }
            let steps = contract_steps(if matching {
                "a user exists"
            } else {
                "a cart exists"
            });
            for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                let outcome =
                    analyze_with_step_usage(pair, steps.clone(), &config, &Default::default())
                        .unwrap();
                assert!(outcome.incomplete.is_empty(), "{framework:?}");
                let count = |rule| {
                    outcome
                        .result
                        .findings
                        .iter()
                        .filter(|f| f.rule == rule)
                        .count()
                };
                assert_eq!(
                    count(Rule::DuplicateMatcher),
                    usize::from(framework != JestCucumber),
                    "{framework:?}"
                );
                assert_eq!(
                    count(Rule::AmbiguousStep),
                    usize::from(framework != JestCucumber && matching),
                    "{framework:?}"
                );
                assert_eq!(
                    count(Rule::UnusedDefinition),
                    if framework != JestCucumber && !matching {
                        2
                    } else {
                        0
                    },
                    "{framework:?}"
                );
            }
        }
    }
}

#[test]
fn adapter_contracts_preserve_handler_domains_and_capture_context() {
    use crate::model::Framework::*;
    let (_directory, config) = config();
    for (left, right, marker, different_file, expected) in [
        (CucumberJs, PlaywrightBdd, "", true, true),
        (Unknown, CypressCucumber, "", true, true),
        (JestCucumber, JestCucumber, "", true, true),
        (VitestCucumber, VitestCucumber, "", true, true),
        (JestCucumber, CucumberJs, "", false, false),
        (VitestCucumber, CucumberJs, "", false, false),
        (JestCucumber, VitestCucumber, "", false, false),
        (CucumberRuby, CucumberRuby, "", true, true),
        (CucumberRuby, CucumberRuby, "ruby:lexical-file", false, true),
        (CucumberRuby, CucumberRuby, "ruby:lexical-file", true, false),
    ] {
        let mut defs = definitions("Given('a user exists', () => { load(); save(); }); Given('the basket is empty', () => { load(); save(); });");
        defs[0].framework = left;
        defs[1].framework = right;
        if different_file {
            defs[1].location.path = "other.ts".into();
        }
        if !marker.is_empty() {
            for def in &mut defs {
                def.handler
                    .behavior_signature
                    .insert(0, format!("method:{marker}"));
            }
        }
        let mut one_capture = defs.clone();
        if !marker.is_empty() {
            one_capture[1].handler.behavior_signature.remove(0);
        }
        for (defs, expected) in [
            (defs, expected),
            (one_capture, expected && marker.is_empty()),
        ] {
            for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                assert_eq!(
                    contract_finding(pair, &config, Rule::DuplicateHandler),
                    expected,
                    "{left:?}/{right:?}/{marker}/{different_file}"
                );
            }
        }
    }
    let mut mixed = definitions("Given('a user exists', () => { load(); save(); }); Given('a cart exists', () => { load(); save(); });");
    mixed[0].framework = CucumberRuby;
    assert!(analyze(mixed, vec![], &config)
        .unwrap_err()
        .to_string()
        .contains("separate analysis runs"));
}

#[test]
fn adapter_contracts_preserve_regex_execution_and_identity() {
    use crate::model::Framework::*;
    let (_directory, config) = config();
    for (framework, pattern, flags, text, matched) in [
        (CucumberJs, "^alice$", "", "before\nalice\nafter", false),
        (CucumberJs, "^alice$", "m", "before\nalice\nafter", true),
        (CucumberRuby, "^alice$", "", "before\nalice\nafter", true),
        (CucumberJs, "^a.b$", "m", "a\nb", false),
        (CucumberJs, "^a.b$", "s", "a\nb", true),
        (CucumberRuby, "^a.b$", "m", "a\nb", true),
        (CucumberRuby, "^alice$", "n", "alice", true),
    ] {
        let mut defs = definitions("Given(/^placeholder$/, () => { load(); save(); });");
        defs[0].framework = framework;
        defs[0].matcher = pattern.into();
        defs[0].matcher_flags = flags.into();
        let steps = contract_steps(text);
        let outcome = analyze_with_step_usage(defs, steps, &config, &Default::default()).unwrap();
        assert!(outcome.incomplete.is_empty());
        assert_eq!(
            outcome
                .result
                .findings
                .iter()
                .any(|f| f.rule == Rule::UnusedDefinition),
            !matched,
            "{framework:?}/{flags}/{text}"
        );
    }
    for (framework, flags, normalized) in [
        (CucumberJs, "gyd", true),
        (CucumberJs, "i", false),
        (CucumberRuby, "n", false),
        (CucumberRuby, "u", false),
    ] {
        let mut defs = definitions("Given(/^alice$/, () => { load(); save(); }); Given(/^alice$/, () => { load(); save(); });");
        for def in &mut defs {
            def.framework = framework;
        }
        defs[1].matcher_flags = flags.into();
        if framework != CucumberRuby && flags == "i" {
            defs[1].normalized_matcher = "[regex-flags:i] ^alice$".into();
        }
        for pair in [defs.clone(), defs.into_iter().rev().collect()] {
            let outcome =
                analyze_with_step_usage(pair, vec![], &config, &Default::default()).unwrap();
            if normalized {
                assert!(outcome
                    .result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::DuplicateMatcher));
            }
            assert_eq!(
                outcome
                    .result
                    .findings
                    .iter()
                    .any(|f| matches!(f.rule, Rule::DuplicateMatcher | Rule::NormalizedMatcher)),
                normalized,
                "{framework:?}/{flags}"
            );
        }
    }
}

#[test]
fn adapter_contracts_preserve_near_handler_and_uncertain_regex_controls() {
    use crate::model::Framework::*;
    let (_directory, config) = config_with_near_floor(0.5);
    for framework in [CucumberJs, CucumberRuby] {
        for same in [true, false] {
            for flags in ["", "n"] {
                let extra = if same { "" } else { "save();" };
                let mut defs = definitions(&format!("Given('I am on login page', () => {{ load(); }}); Given('I am on the login page', () => {{ load(); {extra} }});"));
                for def in &mut defs {
                    def.framework = framework;
                }
                defs[1].matcher_flags = flags.into();
                assert!(definition_pair_candidates(&defs, &config).contains_pair(0, 1));
                for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                    assert_eq!(
                        contract_finding(pair, &config, Rule::NearDuplicateStep),
                        framework == CucumberJs || (same && flags.is_empty()),
                        "{framework:?}/{same}"
                    );
                }
            }
        }
        for flags in [if framework == CucumberJs { "v" } else { "x" }] {
            let mut defs = definitions(
                "Given(/^alpha$/, () => { load(); }); Given(/^beta$/, () => { save(); });",
            );
            for def in &mut defs {
                def.framework = framework;
                def.matcher_flags = flags.into();
            }
            let steps = contract_steps("alpha");
            let outcome =
                analyze_with_step_usage(defs, steps, &config, &Default::default()).unwrap();
            assert!(!outcome.result.findings.iter().any(|f| matches!(
                f.rule,
                Rule::AmbiguousStep | Rule::OverlappingMatcher | Rule::UnusedDefinition
            )));
        }
    }
}

// A config whose `near-duplicate-step` handler-similarity floor is lowered, for tests that exercise
// near-duplicate mechanics at handler shapes below the 0.70 default.
fn config_with_near_floor(floor: f64) -> (tempfile::TempDir, Config) {
    let (directory, mut config) = config();
    config.near_duplicate_handler_similarity = floor;
    (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_with_near_floor(0.5);
    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).is_empty(), "{write}");
        let source = format!("import {{Then}} from '@cucumber/cucumber'; {write} const api = require('@playwright/test'); 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();
    let immediate =
        definitions("When('immediate calls', () => { loadCart(); applyDiscount(); save(); });");
    for callback in [
        "() =>",
        "function ()",
        "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,
                [
                    format!("call:{left_wrapper}"),
                    "call:loadCart".to_owned(),
                    "call:applyDiscount".to_owned(),
                    "call:save".to_owned()
                ],
                "{callback}"
            );
            assert_eq!(
                &defs[0].handler.behavior_signature[1..],
                immediate[0].handler.behavior_signature
            );
            assert_eq!(defs[1].handler.behavior_signature.len(), 4);
            for pair in [defs.clone(), defs.into_iter().rev().collect()] {
                assert_eq!(
                    definition_pair_candidates(&pair, &config).is_empty(),
                    !expected,
                    "{callback}"
                );
                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 direct = definitions("Then('direct assertion', ({state}) => expect(state).toBe('ready'));");
    let deferred = conflicting[0].handler.behavior_signature.last().unwrap();
    assert_eq!(
        deferred.strip_prefix("deferred-"),
        Some(direct[0].handler.behavior_signature[0].as_str())
    );
    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 assertion_factories_are_trusted_by_provenance_across_runners() {
    let (_directory, config) = config();
    let conflicting = |import: &str, assertion: &str| {
        let extracted = definitions(&format!(
            "{import}\nThen('the alpha gauge is settled', () => {{ {assertion}(1); }});\n\
             Then('the beta gauge is settled', () => {{ {assertion}(2); }});"
        ));
        assert_eq!(extracted.len(), 2, "{import}");
        analyze(extracted, Vec::new(), &config)
            .unwrap()
            .findings
            .iter()
            .any(|finding| finding.rule == Rule::ParameterizationCandidate)
    };

    // A trusted factory makes the expected value behaviour, so conflicting values are genuinely
    // different assertions rather than one step waiting to be parameterized. Recognition is
    // shape-based, so Chai's `.to.equal` chain is read exactly as Jest's `.toBe` is; only the
    // provenance of the factory differs between these runners.
    for (import, assertion) in [
        (
            "import { expect } from '@playwright/test';",
            "expect(gauge()).toBe",
        ),
        ("import { expect } from 'vitest';", "expect(gauge()).toBe"),
        ("import { expect } from 'bun:test';", "expect(gauge()).toBe"),
        ("import { expect } from 'chai';", "expect(gauge()).to.equal"),
    ] {
        assert!(
            !conflicting(import, assertion),
            "{import} must be trusted, so conflicting values are not a parameterization candidate"
        );
    }

    // An unrecognized module is not trusted, and importing from one must stay weaker than the
    // ambient global it shadows. Declaring the module is the supported way to restore trust.
    assert!(conflicting(
        "import { expect } from 'some-unknown-assertion-lib';",
        "expect(gauge()).toBe"
    ));
}

#[test]
fn module_scoped_constants_reach_the_handler_fingerprint() {
    let (_directory, config) = config();
    let rules = |module: &str, left: &str, right: &str| {
        let extracted = definitions(&format!(
            "{module}\nThen('the alpha gauge is settled', () => {{ {left} }});\n\
             Then('the beta gauge is settled', () => {{ {right} }});"
        ));
        assert_eq!(extracted.len(), 2, "{module} | {left} | {right}");
        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();
        rules
    };

    // A module constant is a fixed value every handler in the file reads, so two handlers spelling
    // the same value through differently named constants are the same handler. Renaming cannot
    // express this: both constants are visible to both handlers and therefore hold distinct alpha
    // names, so the value itself has to reach the fingerprint.
    for declarations in [
        "const A = 1; const B = 1;",
        "const A = 'ready'; const B = 'ready';",
    ] {
        assert_eq!(
            rules(
                declarations,
                "expect(gauge()).toBe(A);",
                "expect(gauge()).toBe(B);"
            ),
            vec![Rule::DuplicateHandler],
            "{declarations}"
        );
    }

    // Conflicting values stay distinct, exactly as the literal spelling does.
    assert!(rules(
        "const A = 1; const B = 2;",
        "expect(gauge()).toBe(A);",
        "expect(gauge()).toBe(B);"
    )
    .is_empty());

    // `let` can be reassigned between registration and execution, so its value is never proven.
    assert!(rules(
        "let A = 1; let B = 1;",
        "expect(gauge()).toBe(A);",
        "expect(gauge()).toBe(B);"
    )
    .is_empty());

    // A handler-local binding shadows the module constant and keeps its own value.
    assert!(rules(
        "const A = 1;",
        "const A = 2; expect(gauge()).toBe(A);",
        "expect(gauge()).toBe(A);"
    )
    .is_empty());

    // Seeding the walk with a module declaration also reaches constants inside its initializer.
    // Those are not in scope for any handler, so they must never substitute: here `A` and `B` are
    // unresolved module references and the handlers are not the same handler.
    assert!(rules(
        "const helper = () => { const A = 1; const B = 1; };",
        "expect(gauge()).toBe(A);",
        "expect(gauge()).toBe(B);"
    )
    .iter()
    .all(|rule| *rule != Rule::DuplicateHandler));

    // A handler can close over a binding in an enclosing scope. That name is neither
    // handler-local nor module-scoped, so a module constant of the same name must not substitute
    // over the captured value: doing so fused two handlers that read different values. Every form
    // an enclosing scope can introduce is covered, because fixing one at a time left the next as a
    // latent false duplicate.
    for (label, first, second) in [
        (
            "parameter",
            "function buildOne(SHARED) { Then('the alpha gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
            "function buildTwo(SHARED) { Then('the beta gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
        ),
        (
            "declaration",
            "function buildOne() { const SHARED = 7; Then('the alpha gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
            "function buildTwo() { const SHARED = 8; Then('the beta gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
        ),
        (
            "catch binding",
            "try { work(); } catch (SHARED) { Then('the alpha gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
            "try { work(); } catch (SHARED) { Then('the beta gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
        ),
        (
            "loop head",
            "for (const SHARED of [7]) { Then('the alpha gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
            "for (const SHARED of [8]) { Then('the beta gauge is settled', () => expect(gauge()).toBe(SHARED)); }",
        ),
    ] {
        let captured = definitions(&format!("const SHARED = 1;\n{first}\n{second}"));
        assert_eq!(captured.len(), 2, "{label}");
        // The handler bodies are textually identical, so the fingerprints match; what keeps them
        // apart is that the captured value stays unresolved and the handlers are not comparable.
        // The protection is exclusion rather than distinction, which is the conservative direction:
        // a substituted module value made them comparable *and* equal, which is the false duplicate.
        assert!(
            !captured[0].handler.comparable && !captured[1].handler.comparable,
            "{label}: a captured binding must leave the handler non-comparable"
        );
        let result = analyze(captured, Vec::new(), &config).unwrap();
        assert!(
            !result
                .findings
                .iter()
                .any(|finding| finding.rule == Rule::DuplicateHandler),
            "{label}: {:?}",
            result
                .findings
                .iter()
                .map(|finding| finding.rule)
                .collect::<Vec<_>>()
        );
    }

    // Handler-local constants keep their existing alpha renaming, and the parameterization signal
    // that depends on a value-insensitive alpha fingerprint still fires.
    assert_eq!(
        rules(
            "",
            "const A = 1; expect(gauge()).toBe(A);",
            "const B = 1; expect(gauge()).toBe(B);"
        ),
        vec![Rule::DuplicateHandler]
    );
    assert_eq!(
        rules("", "clickButton('save');", "clickButton('cancel');"),
        vec![Rule::ParameterizationCandidate]
    );
}

/// A module constant declared after the registrations that read it still resolves.
///
/// A handler is a deferred callback: by the time it runs, the module has finished initializing, so
/// a later-declared module constant holds its value. Declaration order is a temporal-dead-zone rule
/// for a synchronous handler body, not for a value read from an enclosing scope. Same-value
/// later-declared constants therefore collapse into one handler; conflicting later-declared values
/// stay distinct, exactly as a declared-before pair does. Reverting the enclosing-scope exemption
/// in `LocalConstants::binding` drops the same-value finding, which is the mutation this pins.
#[test]
fn module_constants_declared_after_the_registrations_still_resolve() {
    let (_directory, config) = config();
    let rules = |left_name: &str, right_name: &str, declarations: &str| {
        let extracted = definitions(&format!(
            "Then('the fore gauge is settled', () => {{ expect(gauge()).toBe({left_name}); }});\n\
             Then('the aft gauge is settled', () => {{ expect(gauge()).toBe({right_name}); }});\n\
             {declarations}"
        ));
        assert_eq!(extracted.len(), 2);
        let mut rules: Vec<Rule> = analyze(extracted, Vec::new(), &config)
            .unwrap()
            .findings
            .iter()
            .map(|finding| finding.rule)
            .filter(|rule| matches!(rule, Rule::DuplicateHandler))
            .collect();
        rules.sort();
        rules.dedup();
        rules
    };

    assert_eq!(
        rules("AFT_A", "AFT_B", "const AFT_A = 1;\nconst AFT_B = 1;"),
        vec![Rule::DuplicateHandler]
    );
    // Opposite-answer control: conflicting later-declared values must not collapse.
    assert_eq!(
        rules("DIF_A", "DIF_B", "const DIF_A = 1;\nconst DIF_B = 2;"),
        Vec::<Rule>::new()
    );
}

/// A constant does not resolve into a member property that shares its name.
///
/// `foo` and `bar` are module constants of the same value, but `obj.foo` and `obj.bar` are member
/// accesses, not references to those bindings, so neither constant's value substitutes into the
/// property. The two assertion subjects therefore stay distinct — resolving the property through
/// the constant would collapse them and invent an equivalence between handlers reading different
/// properties. The observable is `behavior_signature`, whose assert subject carries the structural
/// property; the constant values never reach `alpha_normalized`, which is why an earlier probe that
/// watched a `duplicate-handler` finding was invalid. Adding `property_identifier` to the
/// constant-substitution gate in `serialize_ast` collapses the two subjects, which is the
/// conflation this pins against.
#[test]
fn a_constant_does_not_resolve_into_a_same_named_member_property() {
    let extracted = definitions(
        "const foo = 1;\nconst bar = 1;\n\
         Then('the fore probe reads foo', () => { expect(obj.foo).toBe('ready'); });\n\
         Then('the aft probe reads bar', () => { expect(obj.bar).toBe('ready'); });",
    );
    assert_eq!(extracted.len(), 2);
    // Both assertions resolved with a member subject.
    assert!(extracted.iter().all(|definition| {
        definition.handler.behavior_signature.len() == 1
            && definition.handler.behavior_signature[0].starts_with("assert:expect#toBe:")
    }));
    // Distinct properties despite equal-valued same-named constants: the value is not substituted.
    assert_ne!(
        extracted[0].handler.behavior_signature,
        extracted[1].handler.behavior_signature,
    );
}

#[test]
fn called_local_functions_contribute_their_assertions_to_the_handler() {
    let (_directory, config) = config();
    let rules = |left: &str, right: &str| {
        let extracted = definitions(&format!(
            "Then('the alpha gauge is settled', () => {{ {left} }});\n\
             Then('the beta gauge is settled', () => {{ {right} }});"
        ));
        assert_eq!(extracted.len(), 2, "{left} | {right}");
        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();
        rules
    };

    // A function declared in the handler and then called does execute, so its expected values are
    // the handler's behaviour and conflicting ones keep the handlers apart. Before this, the
    // assertion was dropped at the declaration and the difference resurfaced as a spurious
    // parameterization candidate, which the direct spelling never produces.
    let direct = rules("expect(gauge()).toBe(1);", "expect(gauge()).toBe(2);");
    let called = rules(
        "function check() { expect(gauge()).toBe(1); } check();",
        "function check() { expect(gauge()).toBe(2); } check();",
    );
    assert_eq!(
        called, direct,
        "a called local function must match the direct spelling"
    );
    assert!(called.is_empty(), "{called:?}");

    // Identical bodies still share behaviour through the same expansion.
    assert_eq!(
        rules(
            "function check() { expect(gauge()).toBe(1); } check();",
            "function check() { expect(gauge()).toBe(1); } check();",
        ),
        vec![Rule::DuplicateHandler]
    );

    // Declared and never called: nothing executes, so the values are not behaviour and must not be
    // absorbed. The handlers differ only in an unproven value, which is a parameterization
    // candidate exactly as it was before.
    assert_eq!(
        rules(
            "function check() { expect(gauge()).toBe(1); }",
            "function check() { expect(gauge()).toBe(2); }",
        ),
        vec![Rule::ParameterizationCandidate]
    );

    // Parameters are not substituted at the call, so the body's values stay unproven.
    assert!(rules(
        "function check(value) { expect(gauge()).toBe(value); } check(1);",
        "function check(value) { expect(gauge()).toBe(value); } check(2);",
    )
    .is_empty());

    // Expansion is single level, so self-recursion terminates instead of walking forever.
    assert!(rules(
        "function loop() { expect(gauge()).toBe(1); loop(); } loop();",
        "function loop() { expect(gauge()).toBe(2); loop(); } loop();",
    )
    .is_empty());

    // A name declared more than once cannot be resolved to one body by name alone, so no expansion
    // happens. Expanding the wrong declaration would attribute assertions the handler never runs:
    // here the executed bodies are identical and only the unused shadows differ, so fabricating a
    // conflict from them would wrongly separate two handlers that behave the same.
    let shadowed = rules(
        "function check() { expect(gauge()).toBe(1); } check();          { function check() { expect(gauge()).toBe(111); } }",
        "function check() { expect(gauge()).toBe(1); } check();          { function check() { expect(gauge()).toBe(222); } }",
    );
    assert!(!shadowed.contains(&Rule::DuplicateHandler), "{shadowed:?}");

    // A declaration nested inside another function is not visible at this call site, so it must not
    // be expanded either.
    let invisible = rules(
        "function outer() { function check() { expect(gauge()).toBe(1); } } check();",
        "function outer() { function check() { expect(gauge()).toBe(2); } } check();",
    );
    assert!(
        !invisible.contains(&Rule::DuplicateHandler),
        "{invisible:?}"
    );

    // A variable binding shadows the declaration at some position, and a name-keyed lookup cannot
    // tell where. `const check = () => ...` over an outer `function check()` is the common
    // spelling; expanding the outer body there attributes assertions the call never reaches.
    let variable_shadow = rules(
        "function check() { expect(gauge()).toBe(9); } \
         { const check = () => { expect(gauge()).toBe(1); }; check(); }",
        "function check() { expect(gauge()).toBe(9); } \
         { const check = () => { expect(gauge()).toBe(2); }; check(); }",
    );
    assert!(
        !variable_shadow.contains(&Rule::DuplicateHandler),
        "{variable_shadow:?}"
    );

    // Any named binding disqualifies the name, so a new declaration form does not have to be
    // enumerated to be handled. `enum` is covered by the same rule as `class` without naming it.
    for shadow in ["class check {}", "enum check { A }"] {
        let shadowed_by_declaration = rules(
            &format!("function check() {{ expect(gauge()).toBe(1); }} {{ {shadow} check(); }}"),
            &format!("function check() {{ expect(gauge()).toBe(2); }} {{ {shadow} check(); }}"),
        );
        assert!(
            !shadowed_by_declaration.is_empty(),
            "{shadow} must decline expansion, leaving the values unproven"
        );
        assert!(
            !shadowed_by_declaration.contains(&Rule::DuplicateHandler),
            "{shadow}: {shadowed_by_declaration:?}"
        );
    }

    // A parameterized local function called inside a callback is deferred as well as unproven, so
    // the handler records the deferred marker rather than the immediate one.
    let deferred = definitions(
        "Then('a deferred parameterized call', () => {          register(() => { function act(value) { expect(gauge()).toBe(value); } act(1); }); });",
    );
    assert_eq!(deferred.len(), 1);
    assert!(
        deferred[0]
            .handler
            .behavior_signature
            .iter()
            .any(|event| event == "deferred-assert:unresolved"),
        "{:?}",
        deferred[0].handler.behavior_signature
    );

    // A transparent wrapper resolves the same declaration a bare call does. Reading the original
    // callee instead of the unwrapped one silently skipped every parenthesised spelling.
    assert_eq!(
        rules(
            "function check() { expect(gauge()).toBe(1); } (check)();",
            "function check() { expect(gauge()).toBe(2); } (check)();",
        ),
        rules(
            "function check() { expect(gauge()).toBe(1); } check();",
            "function check() { expect(gauge()).toBe(2); } check();",
        ),
        "a wrapped call must expand like a bare call"
    );
}

#[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(
        &crate::source_adapter::IndirectStepUsage::default(),
        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(
        &crate::source_adapter::IndirectStepUsage::default(),
        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(
        &crate::source_adapter::IndirectStepUsage::default(),
        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_with_near_floor(0.5);
    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_with_near_floor(0.5);
    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 parameterization_requires_a_bounded_value_like_matcher_difference() {
    // The handlers are structurally identical (both `locator(<string>).toBeVisible()`), differing
    // only in an erased literal, so the matcher shape is the sole decider. Literal erasure collapses
    // unrelated one-call handlers into one class, so without a matcher guard the corpus flagged pairs
    // that merely share a prefix (kiali: "the AI chatbot toggle button should be visible" vs
    // "…window should be open") or conflict in polarity. A real parameterization differs in a single
    // value. Reverting the gate to `matcher_similarity >= 0.6` makes both negatives fire.
    let fires = |left_matcher: &str, right_matcher: &str| {
        let source = format!(
            "Then('{left_matcher}', async ({{ page }}) => {{ await expect(page.locator('#a')).toBeVisible(); }});\n\
             Then('{right_matcher}', async ({{ page }}) => {{ await expect(page.locator('#b')).toBeVisible(); }});"
        );
        let definitions = definitions(&source);
        assert_eq!(
            definitions[0].handler.structural, definitions[1].handler.structural,
            "handlers must be structurally equal so only the matcher shape decides"
        );
        let (_directory, config) = config();
        analyze(definitions, Vec::new(), &config)
            .unwrap()
            .findings
            .iter()
            .any(|finding| finding.rule == Rule::ParameterizationCandidate)
    };
    // Single value word differs -> a genuine parameterization candidate (positive control).
    assert!(fires(
        "the save button is shown",
        "the cancel button is shown"
    ));
    // Shares a prefix but the change is a multi-word phrase describing different behavior (scores
    // >= 0.6, but changes five words) -> not a parameterization.
    assert!(!fires(
        "the AI chatbot toggle button should be visible",
        "the AI chatbot window should be open"
    ));
    // Opposite polarity -> not a parameterization.
    assert!(!fires(
        "the panel should be shown",
        "the panel should not be shown"
    ));
    // A `dis-` prefix opposite is a polarity conflict, not a value to parameterize.
    assert!(!fires(
        "the client should connect",
        "the client should disconnect"
    ));
    // The `in-` prefix and its assimilated forms `il-`/`im-`/`ir-` are opposites too.
    assert!(!fires("the value is valid", "the value is invalid"));
    assert!(!fires(
        "the argument is logical",
        "the argument is illogical"
    ));
    assert!(!fires("the action is possible", "the action is impossible"));
    assert!(!fires("the layout is regular", "the layout is irregular"));
    // Two disjoint changes with a shared word flanked between them ("button") is not one
    // parameterizable value, even though only three words differ overall.
    assert!(!fires("the red button shown", "the blue button hidden"));
    // But a shared word only at a region edge is an overlap within one shifted value, which a single
    // parameter still covers.
    assert!(fires(
        "the New York office is open",
        "the York City office is open"
    ));
}

#[test]
fn near_duplicate_handler_similarity_floor_is_configurable() {
    // Similarly-worded steps whose handlers share only half their behavior (handler similarity 0.5:
    // one call of two in common). The corpus showed most such pairs are systematically-named steps
    // acting on different things, so the default 0.70 floor suppresses them; lowering the
    // configurable floor to 0.5 restores the finding. Reverting the emit gate to the fixed 0.5
    // constant makes the default case fire, so this pins both the default and the knob.
    let source = "\
When('I am on login page', async ({ page }) => { await page.goto('/login'); await page.waitForSelector('#user'); });
When('I am on the login page', async ({ page }) => { await page.goto('/login'); });
";
    let fires = |floor: Option<f64>| {
        let definitions = definitions(source);
        let (_directory, config) = match floor {
            Some(floor) => config_with_near_floor(floor),
            None => config(),
        };
        analyze(definitions, Vec::new(), &config)
            .unwrap()
            .findings
            .iter()
            .any(|finding| finding.rule == Rule::NearDuplicateStep)
    };
    assert!(
        !fires(None),
        "the default 0.70 floor suppresses a 0.5-handler-similarity near-duplicate"
    );
    assert!(fires(Some(0.5)), "lowering the floor to 0.5 restores it");
}

#[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, expected) in [
        (
            "I click the save button on the checkout summary page",
            "I click the cancel button on the checkout summary page",
            true,
        ),
        (
            "I select the first row of the table",
            "I select the last row of the table",
            true,
        ),
        (
            "the advanced reporting feature is enabled for this account",
            "the advanced reporting feature is disabled for this account",
            false,
        ),
        (
            "the advanced reporting feature uses dark theme for this account",
            "the advanced reporting feature uses light theme for this account",
            true,
        ),
    ] {
        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_eq!(
            result
                .findings
                .iter()
                .any(|finding| finding.rule == Rule::ParameterizationCandidate),
            expected,
            "{left} / {right}"
        );
        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, computed, dynamic, event prefix`.
///
/// `VALUE` is substituted per definition. `computed` names the property with a static string and
/// must behave exactly like `dotted`. `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, &str); 6] = [
    (
        "factory",
        "api.expect(state).not.toBe(VALUE)",
        "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)['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['toBe'](VALUE)",
        "api.expect(state).not[matcherKey](VALUE)",
        "assert:expect.not#toBe:",
    ),
    (
        "factory option",
        "api.expect.soft(state).toBe(VALUE)",
        "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['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)['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"
        );
    }
}

/// OPEN-2 / R5190030268-S2. A statically computed modifier names the same modifier as dot access,
/// so `expect(x)['not']` must carry the semantics `expect(x).not` carries: conflicting expected
/// values stay distinguishable, and equal values remain an exact duplicate. A modifier selected at
/// runtime is unknown and must not inherit that trust.
///
/// Currently the computed form yields generic call events whose literals are normalized away, so
/// conflicting values collapse into one `parameterization-candidate`.
///
/// Comparing finding sets alone is not enough: unwrapping `['not']` while discarding the modifier
/// would still distinguish differing values and still equate identical handlers. The event
/// assertions below pin the modifier itself, so dropping negation fails this test.
#[test]
fn computed_modifier_access_matches_dot_access_semantics() {
    let (_directory, config) = config();

    // Behavior events for a single definition asserting on `subject` using `access` before
    // `.toBe(value)`. The subject is a parameter so that erasing it from the event is observable.
    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()
    };

    // Handler rules only: `unused-definition` depends on a feature corpus these snippets lack.
    let outcome = |access: &str, left: &str, right: &str| {
        let source = format!(
            "Then('alpha holds', () => {{ expect(state){access}.toBe({left}); }}); \
             Then('alpha stands', () => {{ expect(state){access}.toBe({right}); }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        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();
        rules
    };

    // The dotted form is the reference. Anchor it absolutely, so a change that drops the modifier
    // from both access forms cannot satisfy the equality below by making them agree on nothing.
    let dotted_negated = events("state", ".not", "'ready'");
    assert!(
        dotted_negated
            .iter()
            .any(|event| event.starts_with("assert:expect.not#toBe:")),
        "dot access must record the negation modifier: {dotted_negated:?}"
    );

    // Negation is an execution effect: a negated assertion must never look like the unmodified one.
    assert_ne!(
        dotted_negated,
        events("state", "", "'ready'"),
        "a negated assertion must not match the same assertion without the modifier"
    );
    assert_ne!(
        events("state", "['not']", "'ready'"),
        events("state", "", "'ready'"),
        "a computed negation must not be reduced to the unmodified assertion"
    );

    // The computed modifier must produce the same events as dot access, modifier included.
    assert_eq!(
        events("state", "['not']", "'ready'"),
        dotted_negated,
        "a static computed modifier must produce the same assertion events as dot access"
    );

    for (left, right, expected) in [
        ("'ready'", "'idle'", Vec::new()),
        ("'ready'", "'ready'", vec![Rule::DuplicateHandler]),
    ] {
        let dotted = outcome(".not", left, right);
        assert_eq!(
            dotted, expected,
            "dot access baseline changed for {left}/{right}"
        );
        assert_eq!(
            outcome("['not']", left, right),
            dotted,
            "a static computed modifier must match dot access for {left}/{right}"
        );
    }

    // Control: the modifier is chosen at runtime, so it is not provably `not`. Emitting the
    // unresolved sentinel is a conservative, contract-compliant answer here — it makes the handler
    // non-comparable rather than claiming a modifier — so only a *trusted* assertion event is
    // forbidden.
    let dynamic = events("state", "[modifier]", "'ready'");
    assert!(
        !dynamic
            .iter()
            .any(|event| event.starts_with("assert:") && event != "assert:unresolved"),
        "a runtime-selected modifier must not produce a trusted assertion event: {dynamic:?}"
    );
    // Forbidding only `DuplicateHandler` while supplying differing literals cannot fail: differing
    // literals already preclude that rule whatever the modifier means, so the check passes without
    // observing the modifier at all. Pin the whole rule set for both pairings instead, which holds
    // the runtime form to a stated outcome rather than to a condition it satisfies for free.
    assert_eq!(
        outcome("[modifier]", "'ready'", "'idle'"),
        vec![Rule::ParameterizationCandidate],
        "an unresolved modifier falls back to structural similarity for differing values"
    );
    assert_eq!(
        outcome("[modifier]", "'ready'", "'ready'"),
        vec![Rule::DuplicateHandler],
        "handlers identical in source stay duplicates however the modifier is spelled"
    );
}

/// OPEN-1 / R5190030268-S1. A destructuring pattern that binds a matcher builder through nested
/// levels aliases the same module object as the equivalent flat member access, so a write through
/// either alias must revoke assertion trust identically.
///
/// Today only the flat alias revokes it: the pattern collector records an identifier at the first
/// supported property level, so nested bindings never reach the owner and the write is invisible.
///
/// Each scenario is asserted as nested-equals-flat rather than against an absolute value, because
/// the consistency requirement is the contract and the product has not decided every absolute
/// answer. `flat_matcher_aliases_revoke_trust_only_for_matcher_paths` anchors the flat side, so
/// these equalities cannot be satisfied by both forms degrading together.
#[test]
fn nested_destructuring_aliases_revoke_matcher_trust_like_flat_aliases() {
    let (_directory, config) = config();
    let flat_mutated = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, MATCHER_WRITE, &config);
    let flat_clean = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, "", &config);

    for pattern in [
        "const { expect: { not: negated } } = api;",
        "const { expect: { not: negated } = {} } = api;",
        // A computed key that resolves statically names the same property as the plain key.
        "const { expect: { ['not']: negated } } = api;",
        // A computed key that does not resolve statically may still name it. Unknown provenance
        // must remove trust rather than keep it, so this form cannot be treated as an unrelated
        // property either.
        "const { expect: { ['n' + 'ot']: negated } } = api;",
        // The same applies to escapes the decoder does not read: an escaped identifier and a
        // legacy numeric escape both still name `not`, and the flat path already treats them as
        // unknown rather than unrelated.
        "const { expect: { n\\u006ft: negated } } = api;",
        "const { expect: { ['\\156ot']: negated } } = api;",
    ] {
        assert_eq!(
            aliased_matcher_outcome(pattern, MATCHER_WRITE, &config),
            flat_mutated,
            "a write through `{pattern}` must revoke trust like the flat alias"
        );
        assert_eq!(
            aliased_matcher_outcome(pattern, "", &config),
            flat_clean,
            "`{pattern}` without a write must stay trusted like the flat alias"
        );
    }

    // Binding forms whose local name is not `negated`: a shorthand, a shorthand carrying a default,
    // an escaped shorthand, and a rest binding. Object rest copies the property values, so `copy`
    // holds the very matcher objects the owner holds and a write through it reaches them.
    for (pattern, write) in [
        (
            "const { expect: { not } } = api;",
            "not.objectContaining = replacement;",
        ),
        (
            "const { expect: { not = {} } } = api;",
            "not.objectContaining = replacement;",
        ),
        (
            "const { expect: { n\\u006ft } } = api;",
            "n\\u006ft.objectContaining = replacement;",
        ),
    ] {
        assert_eq!(
            aliased_matcher_outcome(pattern, write, &config),
            flat_mutated,
            "a write through `{pattern}` must revoke trust like the flat alias"
        );
        assert_eq!(
            aliased_matcher_outcome(pattern, "", &config),
            flat_clean,
            "`{pattern}` without a write must stay trusted like the flat alias"
        );
    }

    // Bindings are tracked by spelling: nothing in this analyzer decodes identifier escapes, so a
    // declaration and a write that spell one identifier differently do not match. That is a
    // limitation rather than a judgement about provenance, and normalizing it in the nested
    // collector alone would disagree with registration and shadowing and lose real mutations. Pin
    // it as nested-equals-flat so the two forms cannot drift apart while it stands.
    for (nested, flat, write) in [
        (
            "const { expect: { n\\u006ft } } = api;",
            "const n\\u006ft = api.expect.not;",
            "not.objectContaining = replacement;",
        ),
        (
            "const { expect: { not } } = api;",
            "const not = api.expect.not;",
            "n\\u006ft.objectContaining = replacement;",
        ),
    ] {
        assert_eq!(
            aliased_matcher_outcome(nested, write, &config),
            aliased_matcher_outcome(flat, write, &config),
            "`{nested}` with `{write}` must behave like the equivalent flat alias"
        );
    }

    // The nested collector must reach every property the flat walker reaches, not only `not`.
    assert_eq!(
        aliased_matcher_outcome(
            "const { expect: { not: { objectContaining: negated } } } = api;",
            "negated.any = replacement;",
            &config
        ),
        aliased_matcher_outcome(
            "const negated = api.expect.not.objectContaining;",
            "negated.any = replacement;",
            &config
        ),
        "a matcher-builder path must be treated the same through both alias forms"
    );

    // Depth is not a judgement about provenance. An arbitrarily nested pattern must still
    // revoke, or nesting would quietly become a way to keep trust.
    let beyond_bound = {
        let mut pattern = "negated".to_owned();
        for _ in 0..24 {
            pattern = format!("{{ ['n' + 'ot']: {pattern} }}");
        }
        format!("const {{ expect: {pattern} }} = api;")
    };
    assert_eq!(
        aliased_matcher_outcome(&beyond_bound, MATCHER_WRITE, &config),
        flat_mutated,
        "an arbitrarily nested pattern must still revoke trust"
    );

    // A variable that appears only as a computed key is not a binding, so a write through it must
    // not revoke trust. Nested deeply so this is decided by the same walk at every level.
    let beyond_bound_key = {
        let mut pattern = "{ [marker]: { not: leaf } }".to_owned();
        for _ in 0..20 {
            pattern = format!("{{ ['n' + 'ot']: {pattern} }}");
        }
        format!("const marker = 'k'; const {{ expect: {pattern} }} = api;")
    };
    assert_eq!(
        aliased_matcher_outcome(
            &beyond_bound_key,
            "marker.objectContaining = replacement;",
            &config
        ),
        flat_clean,
        "a variable used only as a computed key must not revoke trust"
    );
    assert_eq!(
        aliased_matcher_outcome(
            &beyond_bound_key,
            "leaf.objectContaining = replacement;",
            &config
        ),
        flat_mutated,
        "a deeply nested binding must still revoke trust"
    );

    // An object rest binding is a shallow copy, and the two spellings of one must agree whatever
    // the write depth. What each depth *means* is pinned by
    // `object_rest_aliases_propagate_only_writes_that_reach_the_shared_object`; this only holds
    // the nested and flat spellings together.
    for write in [
        "copy.not = replacement;",
        "copy.not.objectContaining = replacement;",
    ] {
        assert_eq!(
            aliased_matcher_outcome("const { expect: { ...copy } } = api;", write, &config),
            aliased_matcher_outcome("const { ...copy } = api.expect;", write, &config),
            "a rest binding must be treated the same through both alias forms for `{write}`"
        );
    }

    // The same property filter applies at every depth. An unrelated property stops the walk
    // whether it is the first level or the twentieth, and agrees with the flat spelling either
    // way; depth is not a judgement about provenance.
    let nested_unrelated = |levels: usize| {
        let mut pattern = "{ other: { not: leaf } }".to_owned();
        for _ in 0..levels {
            pattern = format!("{{ ['n' + 'ot']: {pattern} }}");
        }
        format!("const {{ expect: {pattern} }} = api;")
    };
    const LEAF_WRITE: &str = "leaf.objectContaining = replacement;";
    let flat_unrelated =
        aliased_matcher_outcome("const leaf = api.expect.other.not;", LEAF_WRITE, &config);
    for levels in [0, 20] {
        assert_eq!(
            aliased_matcher_outcome(&nested_unrelated(levels), LEAF_WRITE, &config),
            flat_unrelated,
            "an unrelated property must stop the walk at {levels} levels of nesting"
        );
    }

    // A write to an unrelated property of the aliased object is the same question on both forms,
    // whatever it is decided to mean, so consistency is asserted without fixing the answer.
    const UNRELATED_WRITE: &str = "negated.unrelatedProperty = replacement;";
    assert_eq!(
        aliased_matcher_outcome(
            "const { expect: { not: negated } } = api;",
            UNRELATED_WRITE,
            &config
        ),
        aliased_matcher_outcome(FLAT_MATCHER_ALIAS, UNRELATED_WRITE, &config),
        "an unrelated write must be treated the same through both alias forms"
    );

    // The same nesting shape under a property that is not a matcher path must also agree, so an
    // over-broad collector that aliased identifiers beneath any property fails rather than passes.
    assert_eq!(
        aliased_matcher_outcome(
            "const { other: { not: negated } } = api;",
            MATCHER_WRITE,
            &config
        ),
        aliased_matcher_outcome("const negated = api.other.not;", MATCHER_WRITE, &config),
        "an alias under an unrelated property must be treated the same through both forms"
    );
}

/// OPEN-2 / R5190030268-S2, generalized across assertion positions. A statically computed property
/// names the same thing as dot access at every position of an assertion chain, so each must carry
/// the same semantics for both conflicting and equal expected values.
///
/// Every divergence is collected before asserting, so the failure names each unsupported position
/// instead of stopping at the first. At the current tree the factory and nested-builder positions
/// already agree.
#[test]
fn computed_access_matches_dot_access_at_every_position() {
    let (_directory, config) = config();
    let mut diverging = Vec::new();
    for (label, dotted, computed, _, _) in ASSERTION_CHAIN_POSITIONS {
        for values in [CONFLICTING, EQUAL] {
            if assertion_position_outcome(computed, values, &config)
                != assertion_position_outcome(dotted, values, &config)
            {
                diverging.push(label);
                break;
            }
        }
    }
    assert!(
        diverging.is_empty(),
        "computed access must match dot access, but diverges at: {diverging:?}"
    );
}

/// Object rest copies property *values* into a fresh object, so the depth of a write decides
/// whether it reaches the object that was copied from: `copy.not = x` replaces a slot on the copy
/// alone and changes nothing shared, while `copy.not.objectContaining = x` mutates the very object
/// the source still references.
///
/// The direct alias is anchored absolutely first, so the equalities below cannot be satisfied by
/// every form degrading to the same answer.
#[test]
fn object_rest_aliases_propagate_only_writes_that_reach_the_shared_object() {
    let (_directory, config) = config();
    let flat_mutated = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, MATCHER_WRITE, &config);
    let flat_clean = aliased_matcher_outcome(FLAT_MATCHER_ALIAS, "", &config);
    assert_ne!(
        flat_mutated, flat_clean,
        "the direct alias baseline must distinguish a write from no write"
    );

    for rest in [
        "const { expect: { ...copy } } = api;",
        "const { ...copy } = api.expect;",
    ] {
        assert_eq!(
            aliased_matcher_outcome(rest, "copy.not = replacement;", &config),
            flat_clean,
            "`{rest}` with a depth-1 write changes nothing shared and must keep trust"
        );
        assert_eq!(
            aliased_matcher_outcome(rest, "copy.not.objectContaining = replacement;", &config),
            flat_mutated,
            "`{rest}` with a depth-2 write reaches the shared object and must revoke trust"
        );
    }

    // A direct alias is not a copy, so a depth-1 write through it reaches the source. Comparing it
    // against the copy is what makes this fail if the exemption ever leaks across.
    assert_ne!(
        aliased_matcher_outcome(FLAT_MATCHER_ALIAS, MATCHER_WRITE, &config),
        aliased_matcher_outcome(
            "const { ...copy } = api.expect;",
            "copy.not = replacement;",
            &config
        ),
        "a direct alias must not inherit the depth-1 exemption a copy gets"
    );

    // Depth travels along alias edges: `negated` sits one level below `copy`, so a depth-1 write
    // on it is a depth-2 write on the copy and does reach the shared object. Both spellings of
    // that alias must agree.
    for alias in [
        "const { ...copy } = api.expect; const negated = copy.not;",
        "const { ...copy } = api.expect; const { not: negated } = copy;",
    ] {
        assert_eq!(
            aliased_matcher_outcome(alias, MATCHER_WRITE, &config),
            flat_mutated,
            "`{alias}` reaches the shared object and must revoke trust"
        );
    }

    // One binding can be reached at different depths by different paths: `copy` is written
    // directly at depth 1, and reached at depth 2 through `negated`. Recording only that a binding
    // was seen would let whichever path is walked first decide the answer, so the deeper arrival
    // has to be able to revisit it. Both statement orders are checked because the order is exactly
    // what must not matter.
    //
    // The names matter: bindings are visited in sorted order, so `zcopy` is reached by its own
    // shallow write before `anegated` can offer the deeper one. Naming them the other way round
    // hides the defect entirely, which is why both orders and this spelling are pinned.
    const ALIAS_CHAIN: &str = "const { ...zcopy } = api.expect; const anegated = zcopy.not;";
    const SHALLOW_FIRST: &str = "zcopy.not = replacement; anegated.objectContaining = replacement;";
    const DEEP_FIRST: &str = "anegated.objectContaining = replacement; zcopy.not = replacement;";
    for write in [SHALLOW_FIRST, DEEP_FIRST] {
        assert_eq!(
            aliased_matcher_outcome(ALIAS_CHAIN, write, &config),
            flat_mutated,
            "the deeper path must decide, whichever order the writes appear in"
        );
    }

    // A binding name changes the traversal order too, and must not change the answer.
    for name in ["a", "z"] {
        let alias = format!("const {{ ...{name} }} = api.expect;");
        let write = format!("{name}.not.objectContaining = replacement; {name}.not = replacement;");
        assert_eq!(
            aliased_matcher_outcome(&alias, &write, &config),
            flat_mutated,
            "a deep write must survive a shallow one whatever the binding is called"
        );
    }

    // A copy taken straight from `require(...)` shares the module's provenance like any other
    // binding of it.
    assert_eq!(
        aliased_matcher_outcome(
            "const { ...copy } = require('@playwright/test').expect;",
            "copy.not.objectContaining = replacement;",
            &config
        ),
        flat_mutated,
        "a rest copy taken straight from require() must share the module's provenance"
    );

    // Being a copy belongs to the edge that made it one, not to the name. Reassigning the binding
    // to a direct alias must not carry the exemption over.
    assert_eq!(
        aliased_matcher_outcome(
            "let { ...copy } = api.expect; copy = api.expect.not;",
            "copy.objectContaining = replacement;",
            &config
        ),
        flat_mutated,
        "a binding reassigned to a direct alias must not keep the copy exemption"
    );

    // One receiver written at several depths takes the largest: the deep write reaches shared
    // state whatever the shallow one does, so a depth-1 write cannot mask it.
    assert_eq!(
        aliased_matcher_outcome(
            "const { ...copy } = api.expect;",
            "copy.not = replacement; copy.anything.any = replacement;",
            &config
        ),
        flat_mutated,
        "a depth-1 write must not mask a deeper write through the same receiver"
    );

    // One assignment target can name a receiver at two depths as well, so the aggregation inside
    // the target walk has to take the largest too, not only the aggregation across statements.
    assert_eq!(
        aliased_matcher_outcome(
            "const { ...copy } = api.expect;",
            "[copy.not, copy.anything.any] = pair;",
            &config
        ),
        flat_mutated,
        "a deeper write in the same assignment target must not be masked"
    );

    // A shorthand binding carrying a default is filtered by its key like any other: one named for
    // an unrelated property must not become an alias. Without this the accepting branch of that
    // arm is the only one exercised.
    assert_eq!(
        aliased_matcher_outcome(
            "const { expect: { other = {} } } = api;",
            "other.objectContaining = replacement;",
            &config
        ),
        aliased_matcher_outcome(
            "const other = api.expect.other;",
            "other.objectContaining = replacement;",
            &config
        ),
        "an unrelated shorthand default must be treated like the unrelated property itself"
    );
    assert_eq!(
        aliased_matcher_outcome(
            "const { expect: { other = {} } } = api;",
            "other.objectContaining = replacement;",
            &config
        ),
        flat_clean,
        "an unrelated shorthand default must not revoke trust"
    );

    // An unrelated property path is still not a matcher path, copy or not. Anchored against the
    // clean outcome rather than another alias, so it cannot pass by both sides degrading.
    assert_eq!(
        aliased_matcher_outcome(
            "const { ...copy } = api.other;",
            "copy.not.objectContaining = replacement;",
            &config
        ),
        flat_clean,
        "a copy of an unrelated property must not revoke trust"
    );
}

/// `obj['name']` and `obj.name` read the same property, so two handlers that differ only in that
/// spelling are the same handler. The behaviour signature already agreed across the two forms;
/// the alpha fingerprint did not, and `duplicate-handler` needs both.
///
/// Only a static string literal whose decoded value is a valid identifier is canonicalised, since
/// that is the only case where a dot spelling of the property exists.
#[test]
fn static_computed_property_access_shares_a_handler_fingerprint() {
    let (_directory, config) = config();
    let outcome = |left: &str, right: &str| {
        let source = format!(
            "Then('the alpha gauge is settled', () => {{ {left} }}); \
             Then('the beta gauge is settled', () => {{ {right} }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        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))
            .collect();
        rules.sort();
        rules.dedup();
        rules
    };
    let duplicate = vec![Rule::DuplicateHandler];

    // Anchor: each spelling equates with itself, so the equalities below cannot pass by making
    // every handler comparable to everything.
    for body in [
        "expect(s).not.toBe('ready');",
        "expect(s)['not'].toBe('ready');",
        "page.locator('x').click();",
        "page['locator']('x').click();",
    ] {
        assert_eq!(
            outcome(body, body),
            duplicate,
            "`{body}` must equate with itself"
        );
    }

    // The contract: the two spellings of one property are one handler.
    for (dotted, computed) in [
        (
            "expect(s).not.toBe('ready');",
            "expect(s)['not'].toBe('ready');",
        ),
        (
            "expect(s).toEqual(expect.objectContaining({ r: 1 }));",
            "expect(s).toEqual(expect['objectContaining']({ r: 1 }));",
        ),
        (
            "page.locator('x').click();",
            "page['locator']('x').click();",
        ),
    ] {
        assert_eq!(
            outcome(dotted, computed),
            duplicate,
            "`{computed}` reads the same property as `{dotted}`"
        );
    }

    // Optional access short-circuits where plain access throws, so the optional link is part of
    // the access. `a?.['b']` is `a?.b`, and neither is `a.b`.
    assert_eq!(
        outcome("expect(s)?.['not'].toBe('a');", "expect(s)?.not.toBe('a');"),
        duplicate,
        "an optional computed access is the optional dotted access"
    );
    assert_ne!(
        outcome("expect(s)?.['not'].toBe('a');", "expect(s).not.toBe('a');"),
        duplicate,
        "an optional access must not collapse into a plain one"
    );
    assert_ne!(
        outcome("expect(s)['not'].toBe('a');", "expect(s)?.not.toBe('a');"),
        duplicate,
        "a plain computed access must not gain an optional link"
    );

    // A key that is not a valid identifier has no dot spelling, so it must not be folded into one.
    assert_ne!(
        outcome(
            "expect(s)['not.resolves'].toBe('ready');",
            "expect(s).not.resolves.toBe('ready');"
        ),
        duplicate,
        "a property literally named `not.resolves` is not the chain `.not.resolves`"
    );

    // Indexes that cannot be read statically keep their own identity.
    for computed in [
        "expect(s)[key].toBe('ready');",
        "expect(s)[`not`].toBe('ready');",
    ] {
        assert_ne!(
            outcome("expect(s).not.toBe('ready');", computed),
            duplicate,
            "`{computed}` is not provably the `not` property"
        );
        assert_eq!(
            outcome(computed, computed),
            duplicate,
            "`{computed}` must still equate with itself"
        );
    }
}

/// A `for (const x of xs)` head binds `x` for the loop, so a reference to `x` inside the body is
/// the loop variable and never an outer constant of the same name. The grammar attaches that
/// binding to the loop rather than to a `variable_declarator`, so the declarator path did not see
/// it and the outer constant's value was substituted into the loop body.
///
/// The three-cell shape is what makes this observable. Two handlers whose only difference is an
/// *unrelated* outer constant must stay comparable-but-equal; if the loop variable is taking that
/// constant's value, the same pair becomes distinguishable instead.
#[test]
fn loop_head_bindings_shadow_an_outer_handler_constant() {
    let (_directory, config) = config();
    let outcome = |left: &str, right: &str| {
        let source = format!(
            "Then('the alpha gauge is settled', () => {{ {left} }}); \
             Then('the beta gauge is settled', () => {{ {right} }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        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();
        rules
    };

    for head in [
        "for (const expected of list)",
        "for (let expected of list)",
        "for (const expected in list)",
    ] {
        let body = format!("{head} {{ expect(state).toBe(expected); }}");
        // The loop variable is unresolved, so the handlers are not comparable at all.
        let bare = outcome(&body, &body);
        assert!(
            bare.is_empty(),
            "`{head}` alone must leave the loop variable unresolved: {bare:?}"
        );
        // Adding an unrelated outer constant of the same name must change nothing. If it is
        // substituted into the loop body the pair becomes comparable and reports a duplicate.
        let shadowed = format!("const expected = 'ready'; {body}");
        assert_eq!(
            outcome(&shadowed, &shadowed),
            bare,
            "`{head}` must shadow an outer constant of the same name"
        );
        // ...and differing outer constants must likewise stay invisible to the loop body.
        assert_eq!(
            outcome(
                &format!("const expected = 'ready'; {body}"),
                &format!("const expected = 'idle'; {body}")
            ),
            bare,
            "`{head}` must not expose a differing outer constant either"
        );
    }

    // Control: the same reference without a loop head does resolve, so the probe is live and the
    // shadow above is doing the work rather than the reference being unresolvable everywhere.
    let resolved = outcome(
        "const expected = 'ready'; expect(state).toBe(expected);",
        "const expected = 'ready'; expect(state).toBe(expected);",
    );
    assert_eq!(
        resolved,
        vec![Rule::DuplicateHandler],
        "an outer constant must still resolve when no loop head shadows it"
    );
}

/// Two `require()` calls for one module return the same cached object, so replacing the factory
/// through either binding replaces it for both. Trust must therefore be revoked whichever binding
/// the write goes through.
///
/// Conflicting expected values are the observable: a trusted factory distinguishes them and reports
/// nothing, while a replaced one falls back to structural similarity. The unwritten case is
/// anchored first so the equalities below cannot pass by every form reporting the same thing.
#[test]
fn a_write_through_any_binding_of_one_module_revokes_factory_trust() {
    let (_directory, config) = config();
    let outcome = |setup: &str, right: &str| {
        let source = format!(
            "const api = require('@playwright/test'); {setup} \
             Then('the panel reads the first value', () => {{ api.expect(state).toBe('ready'); }}); \
             Then('the panel reads the final value', () => {{ api.expect(state).toBe({right}); }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        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();
        rules
    };

    // Anchors: an untouched factory distinguishes conflicting values; a replaced one does not.
    let untouched = outcome("", "'idle'");
    assert!(
        untouched.is_empty(),
        "an untouched factory must distinguish conflicting values: {untouched:?}"
    );
    let replaced = outcome("api.expect = replacement;", "'idle'");
    assert_eq!(
        replaced,
        vec![Rule::ParameterizationCandidate],
        "replacing the factory must fall back to structural similarity"
    );

    // A local alias of the binding already propagates; a second `require()` of the same module
    // returns that same object and must propagate identically.
    for setup in [
        "const other = api; other.expect = replacement;",
        "const other = require('@playwright/test'); other.expect = replacement;",
        "const other = require('@playwright/test'); other['expect'] = replacement;",
        "const first = require('@playwright/test'); const second = first; second.expect = replacement;",
    ] {
        assert_eq!(
            outcome(setup, "'idle'"),
            replaced,
            "`{setup}` writes the same module object and must revoke trust"
        );
    }

    // Control: writing a property *on the factory function* is not replacing the factory.
    // `expect(state).toBe(...)` calls `toBe` on the call's result, not on `expect`, so this
    // changes nothing the assertions rely on.
    assert_eq!(
        outcome(
            "const { expect: other } = require('@playwright/test'); other.toBe = replacement;",
            "'idle'"
        ),
        untouched,
        "a write to a property of the factory function must not revoke trust"
    );

    // Control: a different module is a different object, so it must not revoke.
    assert_eq!(
        outcome(
            "const other = require('unrelated-assertion-library'); other.expect = replacement;",
            "'idle'"
        ),
        untouched,
        "a write through an unrelated module must not revoke trust"
    );
}

/// A direct property read of a required assertion module is the factory, in either spelling, so
/// `require('...')['expect']` must carry exactly the trust `require('...').expect` carries.
///
/// The dotted spelling is anchored absolutely, so the equalities below cannot be satisfied by both
/// spellings failing to resolve together.
#[test]
fn a_computed_require_property_is_an_assertion_factory() {
    let (_directory, config) = config();
    let outcome = |spelling: &str, right: &str| {
        let source = format!(
            "const check = {spelling}; \
             Then('the panel reads the first value', () => {{ check(state).not.toBe('ready'); }}); \
             Then('the panel reads the final value', () => {{ check(state).not.toBe({right}); }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        let events = extracted[0].handler.behavior_signature.clone();
        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)
    };
    let dotted = "require('@playwright/test').expect";
    let computed = "require('@playwright/test')['expect']";

    let (anchored, _) = outcome(dotted, "'idle'");
    assert!(
        anchored
            .iter()
            .any(|event| event.starts_with("assert:expect.not#toBe:")),
        "the dotted spelling must resolve to a trusted assertion: {anchored:?}"
    );

    for right in ["'idle'", "'ready'"] {
        assert_eq!(
            outcome(computed, right),
            outcome(dotted, right),
            "`{computed}` must carry the trust `{dotted}` carries for {right}"
        );
    }
}

/// A subscript index names a property only when it is a static string literal. Deciding that from
/// the index text alone is unsound: any expression whose text merely begins and ends with a
/// matching quote decodes into a key that names nothing, which both invents a modifier and hides
/// whatever the index actually executes.
///
/// The resolved case is anchored absolutely, so the prohibitions below cannot be satisfied by
/// making every subscript unresolved.
#[test]
fn quote_shaped_subscript_indexes_do_not_name_a_property() {
    let (_directory, config) = config();
    let outcome = |index: &str| {
        let handler = format!("expect(state)[{index}].toBe('ready');");
        let source = format!(
            "Then('the alpha gauge is settled', () => {{ {handler} }}); \
             Then('the beta gauge is settled', () => {{ {handler} }});"
        );
        let extracted = definitions(&source);
        assert_eq!(extracted.len(), 2, "{source}");
        let events = extracted[0].handler.behavior_signature.clone();
        let comparable = extracted[0].handler.comparable;
        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, comparable, rules)
    };

    let (resolved, _, _) = outcome("'not'");
    assert!(
        resolved
            .iter()
            .any(|event| event.starts_with("assert:expect.not#toBe:")),
        "a string-literal index must resolve to the modifier it names: {resolved:?}"
    );

    // A backslash before U+2028 or U+2029 is a line continuation, so this key names `not` exactly
    // as `'not'` does. Preserving the separator instead would lose that name and, worse, make the
    // key indistinguishable from one that genuinely contains the separator.
    let (continued, _, _) = outcome("'n\\\u{2028}ot'");
    assert_eq!(
        continued, resolved,
        "a line continuation inside a key must resolve to the name the key spells"
    );
    let (separator, _, _) = outcome("'n\u{2028}ot'");
    assert_ne!(
        separator, resolved,
        "a key that genuinely contains the separator names a different property"
    );

    // `\0` is NUL unless another digit follows it, so these name real properties. Only the legacy
    // octal forms stay unreadable, which keeps the guard and the decoder agreeing.
    for index in [r"'\0foo'", r"'\0'"] {
        let (events, _, _) = outcome(index);
        assert!(
            events
                .iter()
                .any(|event| event.starts_with("assert:expect.")),
            "`[{index}]` is a readable key, but produced: {events:?}"
        );
    }

    // An escaped backslash is not the start of an escape: `'foo\\5'` names `foo\5`, which reads
    // fine. Only a digit that an escape actually consumes makes a key unreadable.
    let (escaped_backslash, _, _) = outcome(r"'foo\\5'");
    assert!(
        escaped_backslash
            .iter()
            .any(|event| event.starts_with("assert:expect.")),
        "an escaped backslash must not make a key unreadable: {escaped_backslash:?}"
    );

    // An identifier may carry unicode escapes, and a decoded key may contain a literal backslash.
    // They name different properties, so encoding must keep them apart: `x.foobar` reads
    // `foobar`, while `x['foo\\u0062ar']` reads a property whose name contains a backslash.
    let (computed_backslash, _, _) = outcome(r"'foo\\u0062ar'");
    let escaped_identifier = {
        let source = "Then('alpha holds', () => { expect(state).foo\\u0062ar.toBe('ready'); });";
        let extracted = definitions(source);
        assert_eq!(extracted.len(), 1, "{source}");
        extracted[0].handler.behavior_signature.clone()
    };
    assert!(
        escaped_identifier
            .iter()
            .any(|event| event.starts_with("assert:expect.")),
        "an escaped identifier must still resolve: {escaped_identifier:?}"
    );
    assert_ne!(
        computed_backslash, escaped_identifier,
        "a key containing a backslash must not encode to the same event as an escaped identifier"
    );

    // A decoded key is arbitrary text, while event components are joined with delimiters. A key
    // containing one of them must stay distinguishable from the join, or a single property named
    // `not.resolves` would be recorded as the two-step chain `.not.resolves`.
    let (dotted_key, _, _) = outcome("'not.resolves'");
    let (chain, _, _) = {
        let source = "Then('the alpha gauge is settled', () => { \
                      expect(state).not.resolves.toBe('ready'); }); \
                      Then('the beta gauge is settled', () => { \
                      expect(state).not.resolves.toBe('ready'); });";
        let extracted = definitions(source);
        assert_eq!(extracted.len(), 2, "{source}");
        (extracted[0].handler.behavior_signature.clone(), true, ())
    };
    assert!(
        chain
            .iter()
            .any(|event| event.starts_with("assert:expect.not.resolves#toBe:")),
        "the modifier chain must resolve, anchoring the comparison below: {chain:?}"
    );
    assert_ne!(
        dotted_key, chain,
        "a property named `not.resolves` must not record the same event as the chain `.not.resolves`"
    );

    // The sequence index executes an assertion against an external binding. Decoding the index as
    // one opaque key swallows that call, which turns a handler that cannot be compared into one
    // that looks fully resolved. Compare against the same handler written without the index so the
    // control states what the difference must be rather than asserting an absolute.
    const SWALLOWED: &str = "'not', ((x) => expect(state).toBe(x))(external), 'not'";
    let (events, comparable, rules) = outcome(SWALLOWED);
    assert!(
        !comparable,
        "an index that executes an unresolved call must leave the handler non-comparable: \
         {events:?}"
    );
    assert!(
        rules.is_empty(),
        "a non-comparable handler must not be equated with another, but produced: {rules:?}"
    );

    for index in [
        "'n' + 'ot'",
        "`not`",
        "'not', ((x) => expect(state).toBe(x))(external), 'not'",
        // A legacy numeric escape is a string literal the shared decoder cannot read: `'n\\157t'`
        // names `not`, not `n157t`. Answering with the undecoded digits would name a property the
        // source never mentions, so it must stay unreadable rather than resolve to the wrong one.
        "'n\\157t'",
        // `\0` followed by another digit is the legacy form, unlike a bare `\0`.
        "'n\\01t'",
    ] {
        let (events, _, _) = outcome(index);
        // Reject every trusted assertion event, not only a modified one: resolving the index to
        // nothing and emitting the unmodified `assert:expect#toBe:` would still be claiming the
        // chain was understood.
        assert!(
            !events
                .iter()
                .any(|event| event.starts_with("assert:") && event != "assert:unresolved"),
            "`[{index}]` does not name a modifier, but produced: {events:?}"
        );
    }
}