perl-lsp 0.5.3

A fast Perl language server with cross-file type inference, completion, goto-definition, and rename. Built on tree-sitter-perl and tower-lsp.
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
use super::*;
use std::path::PathBuf;

fn parse(source: &str) -> FileAnalysis {
    use tree_sitter::Parser;
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    crate::builder::build(&tree, source.as_bytes())
}

#[test]
fn test_refs_to_finds_sub_across_workspace_files() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_test_a.pm");
    let path_b = PathBuf::from("/tmp/resolve_test_b.pm");

    // File A defines sub foo and exports it.
    let fa_a = parse("package A;\nour @EXPORT_OK = qw/foo/;\nsub foo { 42 }\n1;\n");
    store.insert_workspace(path_a.clone(), fa_a);

    // File B imports foo from A and calls it.
    let fa_b = parse("package B;\nuse A qw/foo/;\nsub bar { foo(); }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub {
                package: Some("A".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    // Expect at least the decl in A and the call in B.
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)
                && r.access == AccessKind::Declaration),
        "expected declaration of foo in file A, got {:?}",
        results,
    );
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b)
                && r.access == AccessKind::Read),
        "expected call to foo in file B, got {:?}",
        results,
    );
}

/// Exporter::Extensible: `export(...)` + `:Export` register subs as
/// exports without `@EXPORT_OK`. A consumer's `use X 'name'` must fan
/// out to the def under `refs_to`.
#[test]
fn test_refs_to_exporter_extensible_cross_file() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_ext_a.pm");
    let path_b = PathBuf::from("/tmp/resolve_ext_b.pm");

    let fa_a = parse(
        "package Ext;\nuse Exporter::Extensible -exporter_setup => 1;\nexport(qw/foo/);\nsub foo { 42 }\nsub bar :Export {}\n1;\n",
    );
    store.insert_workspace(path_a.clone(), fa_a);

    let fa_b = parse("package C;\nuse Ext qw/foo/;\nsub baz { foo(); }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub { package: Some("Ext".to_string()) },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)
            && r.access == AccessKind::Declaration),
        "expected declaration of foo in Ext, got {:?}",
        results,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b)
            && r.access == AccessKind::Read),
        "expected call to foo in consumer, got {:?}",
        results,
    );
}

/// Exporter::Declare: `default_export name => sub {}` registers exports.
#[test]
fn test_refs_to_exporter_declare_cross_file() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_decl_a.pm");
    let path_b = PathBuf::from("/tmp/resolve_decl_b.pm");

    let fa_a = parse(
        "package Decl;\nuse Exporter::Declare;\ndefault_export foo => sub { 42 };\nsub foo { 42 }\n1;\n",
    );
    store.insert_workspace(path_a.clone(), fa_a);

    let fa_b = parse("package C;\nuse Decl qw/foo/;\nsub baz { foo(); }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub { package: Some("Decl".to_string()) },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)),
        "expected def of foo in Decl, got {:?}",
        results,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b)
            && r.access == AccessKind::Read),
        "expected call to foo in consumer, got {:?}",
        results,
    );
}

/// Importer consumer form: `use Importer 'Src' => qw/foo/` imports foo
/// from Src — the call must fan out to Src's def, not stop at Importer.
#[test]
fn test_refs_to_importer_consumer_cross_file() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_imp_src.pm");
    let path_b = PathBuf::from("/tmp/resolve_imp_consumer.pm");

    let fa_a = parse("package Src::Mod;\nour @EXPORT_OK = qw/foo/;\nsub foo { 42 }\n1;\n");
    store.insert_workspace(path_a.clone(), fa_a);

    let fa_b = parse(
        "package C;\nuse Importer 'Src::Mod' => qw/foo/;\nsub baz { foo(); }\n1;\n",
    );
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub { package: Some("Src::Mod".to_string()) },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)
            && r.access == AccessKind::Declaration),
        "expected decl of foo in Src::Mod, got {:?}",
        results,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b)),
        "expected import/call of foo in consumer pinned to Src::Mod, got {:?}",
        results,
    );
}

/// False-positive guard: a `sub export {}` in a non-exporter package
/// must not register phantom exports that pollute cross-file refs.
#[test]
fn test_refs_to_export_not_registered_without_use() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_noexport.pm");
    let fa_a = parse("package Plain;\nsub export {}\nexport('phantom');\n1;\n");
    store.insert_workspace(path_a.clone(), fa_a);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "phantom".to_string(),
            kind: TargetKind::Sub { package: Some("Plain".to_string()) },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(results.is_empty(), "no phantom export, got {:?}", results);
}

/// Adversarial #1: a dotted helper `users.create` and a route's
/// `Users#create` share a method name but live on different
/// classes. gr on one must NOT pick up the other.
///
/// Helper leaf lives on `Mojolicious::Controller::_Helper::users`.
/// Route target is `Users::create`. They only share a name.
#[test]
fn refs_to_helper_leaf_excludes_unrelated_route_with_same_method_name() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/helper_route_overlap.pm");

    let fa = parse(
        r#"
package MyApp;
use Mojolicious::Lite;

$app->helper('users.create', sub ($c, $user) {});
$app->routes->post('/users')->to(controller => 'Users', action => 'create');
"#,
    );
    store.insert_workspace(path.clone(), fa);

    // gr on the helper's `create` leaf (class = _Helper::users).
    // Must NOT include the route's `create` ref (targets Users).
    let helper_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "create".to_string(),
            kind: TargetKind::Method {
                class: "Mojolicious::Controller::_Helper::users".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // Route's 'create' string sits at column ~67 on line 5
    // (0-indexed). Anything there is the route, not the helper.
    for r in &helper_results {
        let col = r.span.start.column;
        assert!(
            !(r.span.start.row == 5 && col > 50),
            "gr on helper leaf _Helper::users::create picked up the \
                 route's Users::create ref (line {}, col {}) — unrelated \
                 class, shouldn't appear",
            r.span.start.row,
            col,
        );
    }

    // Mirror: gr on the route's `create` target (class = Users).
    // Must NOT include the helper's Method declaration.
    let route_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "create".to_string(),
            kind: TargetKind::Method {
                class: "Users".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // Helper's 'create' leaf is at line 4 col ~13 (inside the
    // 'users.create' string — the plugin narrows spans to the leaf
    // segment).
    for r in &route_results {
        assert!(
            !(r.span.start.row == 4 && r.span.start.column < 30),
            "gr on route Users::create picked up the helper leaf \
                 _Helper::users::create (line {}, col {}) — unrelated class",
            r.span.start.row,
            r.span.start.column,
        );
    }
}

/// Adversarial #2: two plain Perl packages, each with its own
/// `run` method. `$f->run` targets `Foo::run`; `$b->run` targets
/// `Bar::run`. gr on Foo's run must not union with Bar's.
#[test]
fn refs_to_method_is_class_scoped_plain_packages() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/two_classes_same_method.pm");

    let fa = parse(
        r#"
package Foo;
sub new { bless {}, shift }
sub run { "foo" }

package Bar;
sub new { bless {}, shift }
sub run { "bar" }

package main;
my $f = Foo->new;
my $b = Bar->new;
$f->run;
$b->run;
1;
"#,
    );
    store.insert_workspace(path.clone(), fa);

    let foo_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "run".to_string(),
            kind: TargetKind::Method {
                class: "Foo".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // Must include Foo::run decl and `$f->run` call. Must NOT
    // include Bar::run decl or `$b->run` call.
    let foo_lines: Vec<usize> = foo_results.iter().map(|r| r.span.start.row).collect();
    assert!(
        foo_lines.contains(&3), // `sub run` in package Foo
        "Foo::run decl (line 3) missing from Foo results: {:?}",
        foo_lines
    );
    assert!(
        foo_lines.contains(&12), // `$f->run` call
        "$f->run call (line 12) missing from Foo results: {:?}",
        foo_lines
    );
    assert!(
        !foo_lines.contains(&7), // `sub run` in package Bar
        "Bar::run decl (line 7) wrongly included in Foo results: {:?}",
        foo_lines
    );
    assert!(
        !foo_lines.contains(&13), // `$b->run` call
        "$b->run call (line 13) wrongly included in Foo results: {:?}",
        foo_lines
    );

    let bar_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "run".to_string(),
            kind: TargetKind::Method {
                class: "Bar".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    let bar_lines: Vec<usize> = bar_results.iter().map(|r| r.span.start.row).collect();
    assert!(
        bar_lines.contains(&7),
        "Bar::run decl (line 7) missing from Bar results: {:?}",
        bar_lines
    );
    assert!(
        bar_lines.contains(&13),
        "$b->run call (line 13) missing from Bar results: {:?}",
        bar_lines
    );
    assert!(
        !bar_lines.contains(&3),
        "Foo::run decl (line 3) wrongly included in Bar results: {:?}",
        bar_lines
    );
    assert!(
        !bar_lines.contains(&12),
        "$f->run call (line 12) wrongly included in Bar results: {:?}",
        bar_lines
    );
}

/// NAV (b) repro (i): method references read the build-time-frozen
/// dispatch edge, not a query-time invocant re-derivation. An untyped
/// invocant (`my $w = COND ? external() : undef`) stamps NO edge, so its
/// `->frobnicate` sites are deterministically EXCLUDED, while the typed
/// `$self->frobnicate` (enclosing-class invocant) IS included. This is
/// the determinism the unification buys: no enriched-vs-workspace
/// divergence — the edge is frozen once per build.
#[test]
fn refs_to_method_excludes_untyped_invocant_includes_self() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/nav_untyped_invocant.pm");

    let fa = parse(
        r#"package Widget;
sub frobnicate { 1 }
sub run {
  my $self = shift;
  my $w = $ENV{X} ? external() : undef;
  $w->frobnicate;
  $w->frobnicate;
  $self->frobnicate;
}
1;
"#,
    );
    store.insert_workspace(path.clone(), fa);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "frobnicate".to_string(),
            kind: TargetKind::Method {
                class: "Widget".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    let lines: Vec<usize> = results.iter().map(|r| r.span.start.row).collect();
    // def `sub frobnicate` (row 1) + `$self->frobnicate` (row 7).
    assert!(
        lines.contains(&1),
        "frobnicate decl (row 1) missing: {:?}",
        lines
    );
    assert!(
        lines.contains(&7),
        "$self->frobnicate (row 7) missing: {:?}",
        lines
    );
    // Both untyped `$w->frobnicate` sites (rows 5, 6) EXCLUDED.
    assert!(
        !lines.contains(&5) && !lines.contains(&6),
        "untyped $w->frobnicate sites (rows 5,6) wrongly included: {:?}",
        lines
    );
    // Exactly two hits: the decl + the one typed call.
    assert_eq!(
        results.len(),
        2,
        "expected exactly decl + $self call, got {:?}",
        lines
    );
}

/// NAV regression (iv): a typed same-file invocant (`my $w = Widget->new`)
/// still resolves fully — every `$w->frobnicate` site is matched via the
/// frozen edge. Guards against the unification dropping valid matches.
#[test]
fn refs_to_method_typed_same_file_invocant_resolves_fully() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/nav_typed_invocant.pm");

    let fa = parse(
        r#"package Widget;
sub new { bless {}, shift }
sub frobnicate { 1 }
sub run {
  my $w = Widget->new;
  $w->frobnicate;
  $w->frobnicate;
}
1;
"#,
    );
    store.insert_workspace(path.clone(), fa);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "frobnicate".to_string(),
            kind: TargetKind::Method {
                class: "Widget".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    let lines: Vec<usize> = results.iter().map(|r| r.span.start.row).collect();
    assert!(lines.contains(&2), "frobnicate decl (row 2) missing: {:?}", lines);
    assert!(
        lines.iter().filter(|&&l| l == 5).count() == 1
            && lines.iter().filter(|&&l| l == 6).count() == 1,
        "both typed $w->frobnicate sites (rows 5,6) must resolve: {:?}",
        lines
    );
}

/// NAV honest-miss: a genuinely-untyped receiver — `my $x =
/// external(); $x->m()` — has no inferable class, so NO dispatch edge
/// is stamped, and goto-def returns `None`. It must NEVER jump to an
/// arbitrary same-named sub (the deleted same-name fallback). This is
/// the libwww case: `$ua->get` where `$ua` came from an opaque
/// constructor we can't see.
#[test]
fn goto_def_untyped_receiver_is_honest_miss() {
    use tree_sitter::{Parser, Point};
    let src = r#"package Foo;
sub m { 1 }
package main;
my $x = external();
$x->m();
"#;
    let mut parser = Parser::new();
    parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
    let tree = parser.parse(src, None).unwrap();
    let fa = crate::builder::build(&tree, src.as_bytes());
    // Cursor on `m` in `$x->m()`.
    let row = src.lines().position(|l| l.starts_with("$x->m")).unwrap();
    let col = "$x->".len();
    let def = fa.find_definition(Point::new(row, col), None);
    assert_eq!(
        def, None,
        "untyped `$x->m` (where $x = external()) must be an honest miss, \
         never a same-name jump to Foo::m. got: {:?}",
        def,
    );
}

/// NAV honest-miss, multi-candidate flood guard: two unrelated classes
/// both define `frob`. An untyped `$x->frob` must resolve to `None` —
/// no flood of arbitrary same-named subs. With the same-name fallback
/// gone, the absence of an edge is the only answer.
#[test]
fn goto_def_untyped_receiver_multi_candidate_no_flood() {
    use tree_sitter::{Parser, Point};
    let src = r#"package A;
sub frob { 1 }
package B;
sub frob { 2 }
package main;
my $x = make_something();
$x->frob;
"#;
    let mut parser = Parser::new();
    parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
    let tree = parser.parse(src, None).unwrap();
    let fa = crate::builder::build(&tree, src.as_bytes());
    let row = src.lines().position(|l| l.starts_with("$x->frob")).unwrap();
    let col = "$x->".len();
    let def = fa.find_definition(Point::new(row, col), None);
    assert_eq!(
        def, None,
        "untyped `$x->frob` with two unrelated `frob` definitions must \
         be None — no same-name flood. got: {:?}",
        def,
    );
}

/// Adversarial #3: Corinna classes with same method name. Both
/// call shapes must class-resolve correctly:
///
///   (a) Variable-bound: `my $s = Sner->new; $s->hi` — `$s` gets
///       a ClassName(Sner) type constraint, so invocant resolution
///       finds the class via the variable-type flow.
///   (b) Inline chain: `Sner->new->hi` — the outer `->hi`'s
///       invocant is a `method_call_expression`. The build-time
///       `invocant_class` field on MethodCall refs is populated by
///       `resolve_invocant_class_tree`, which walks chain invocants
///       including `<Class>->new` constructors.
///
/// Critical invariant either way: no cross-linking between Sner
/// and Bler.
#[test]
fn refs_to_method_is_class_scoped_corinna() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/corinna_classes.pm");

    let fa = parse(
        r#"use v5.38;

class Sner {
    method hi {}
}
class Bler {
    method hi {}
}

my $s = Sner->new;
my $b = Bler->new;
$s->hi;
$b->hi;
Sner->new->hi;
Bler->new->hi;
1;
"#,
    );
    store.insert_workspace(path.clone(), fa);

    let sner_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "hi".to_string(),
            kind: TargetKind::Method {
                class: "Sner".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    let sner_lines: Vec<usize> = sner_results.iter().map(|r| r.span.start.row).collect();
    assert!(
        sner_lines.contains(&3),
        "Sner::hi decl missing: {:?}",
        sner_lines
    );
    assert!(
        sner_lines.contains(&11),
        "$s->hi (variable-bound) missing: {:?}",
        sner_lines
    );
    assert!(
        sner_lines.contains(&13),
        "Sner->new->hi (inline chain) missing — chain invocant resolution \
             via build-time invocant_class should cover this: {:?}",
        sner_lines
    );
    // No Bler anywhere in Sner results.
    assert!(
        !sner_lines.contains(&6),
        "Bler::hi decl wrongly in Sner results: {:?}",
        sner_lines
    );
    assert!(
        !sner_lines.contains(&12),
        "$b->hi wrongly in Sner results: {:?}",
        sner_lines
    );
    assert!(
        !sner_lines.contains(&14),
        "Bler->new->hi wrongly in Sner results: {:?}",
        sner_lines
    );

    let bler_results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "hi".to_string(),
            kind: TargetKind::Method {
                class: "Bler".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    let bler_lines: Vec<usize> = bler_results.iter().map(|r| r.span.start.row).collect();
    assert!(
        bler_lines.contains(&6),
        "Bler::hi decl missing: {:?}",
        bler_lines
    );
    assert!(bler_lines.contains(&12), "$b->hi missing: {:?}", bler_lines);
    assert!(
        bler_lines.contains(&14),
        "Bler->new->hi (inline chain) missing: {:?}",
        bler_lines
    );
    assert!(
        !bler_lines.contains(&3),
        "Sner::hi decl wrongly in Bler results: {:?}",
        bler_lines
    );
    assert!(
        !bler_lines.contains(&11),
        "$s->hi wrongly in Bler results: {:?}",
        bler_lines
    );
    assert!(
        !bler_lines.contains(&13),
        "Sner->new->hi wrongly in Bler results: {:?}",
        bler_lines
    );
}

/// ALL FOUR LSP paths (hover, gd, gr, rename) must class-scope
/// for two packages sharing a method name. Single resolver post
/// option-2 — `FileAnalysis::method_call_invocant_class(ref, idx)`
/// — but the four user-visible surfaces still each need their own
/// integration coverage:
///
///   1. find_definition (gd) — bag-routed via the helper, then
///      walks ancestors for cross-class fallback.
///   2. hover_info (K) — same helper; walks ancestors for the
///      "*from BaseClass*" provenance.
///   3. find_references / refs_to (gr) — iterates every MethodCall
///      ref and filters by helper-resolved invocant class.
///   4. rename_method_in_class — class-scopes edits to MethodCall
///      refs whose helper answer matches.
///
/// Classic copy-paste risk. This test drives all four LSP-visible
/// surfaces with a single Foo/Bar fixture and proves every path
/// stays on Foo when the cursor is on Foo, and on Bar when on
/// Bar. If any path drifts, its assertion fires.
#[test]
fn all_four_lsp_paths_class_scope_on_shared_method_name() {
    use crate::file_analysis::RenameKind;
    use tree_sitter::Parser;

    let src = r#"package Foo;
sub new { bless {}, shift }
sub run { "foo" }

package Bar;
sub new { bless {}, shift }
sub run { "bar" }

package main;
my $f = Foo->new;
my $b = Bar->new;
$f->run;
$b->run;
1;
"#;
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let fa = crate::builder::build(&tree, src.as_bytes());

    // Line/col positions (0-indexed):
    //   line 2, col 4  — `sub run` decl in Foo
    //   line 6, col 4  — `sub run` decl in Bar
    //   line 11, col 4 — `$f->run` (cursor on "run"). Line text:
    //                    "$f->run;" → cols 0..1 = "$f", 2..3 = "->",
    //                    4..6 = "run".
    //   line 12, col 4 — `$b->run` (cursor on "run").
    let _run_in_foo_decl = tree_sitter::Point { row: 2, column: 4 };
    let _run_in_bar_decl = tree_sitter::Point { row: 6, column: 4 };
    let f_run_call = tree_sitter::Point { row: 11, column: 4 };
    let b_run_call = tree_sitter::Point { row: 12, column: 4 };

    // ---- (1) hover — cursor on `$f->run`. Must mention Foo, not Bar.
    let hover = fa
        .hover_info(f_run_call, src, None)
        .expect("hover on $f->run returns something");
    assert!(
        hover.contains("Foo"),
        "hover on $f->run should mention Foo; got: {:?}",
        hover
    );
    assert!(
        !hover.contains("Bar"),
        "hover on $f->run leaked Bar into the content: {:?}",
        hover
    );

    // Mirror: hover on $b->run mentions Bar, not Foo.
    let hover_b = fa
        .hover_info(b_run_call, src, None)
        .expect("hover on $b->run returns something");
    assert!(
        hover_b.contains("Bar"),
        "hover on $b->run should mention Bar; got: {:?}",
        hover_b
    );
    assert!(
        !hover_b.contains("Foo"),
        "hover on $b->run leaked Foo into the content: {:?}",
        hover_b
    );

    // ---- (2) goto-def — $f->run must jump to Foo::run (line 2), not Bar::run (line 6).
    let gd_f = fa
        .find_definition(f_run_call, None)
        .expect("gd on $f->run resolves");
    assert_eq!(
        gd_f.start.row, 2,
        "gd on $f->run jumped to line {} (expected 2 = Foo::run)",
        gd_f.start.row
    );

    let gd_b = fa
        .find_definition(b_run_call, None)
        .expect("gd on $b->run resolves");
    assert_eq!(
        gd_b.start.row, 6,
        "gd on $b->run jumped to line {} (expected 6 = Bar::run)",
        gd_b.start.row
    );

    // ---- (3) references — via rename_kind_at → TargetRef → refs_to.
    let target_from_f = match fa.rename_kind_at(f_run_call, None) {
        Some(RenameKind::Method { name, class }) => TargetRef {
            name,
            kind: TargetKind::Method { class },
            method_classes: Vec::new(),
        },
        other => panic!(
            "rename_kind_at($f->run) should be Method{{class=Foo}}, got {:?}",
            other
        ),
    };
    // Verify the class field was populated as Foo (not Bar, not missing).
    if let TargetKind::Method { ref class } = target_from_f.kind {
        assert_eq!(
            class, "Foo",
            "rename_kind_at($f->run) resolved class as {:?}, expected Foo",
            class
        );
    }

    // ---- (4) rename — BEFORE moving `fa` into the store. Rename
    // Foo::run to renamed_run. Must edit Foo::run decl + $f->run
    // call, NOT Bar::run or $b->run.
    let edits = fa.rename_method_in_class("run", "Foo", "renamed_run", None);
    let edit_lines: Vec<usize> = edits.iter().map(|(span, _)| span.start.row).collect();
    assert!(
        edit_lines.contains(&2),
        "rename Foo::run missed the decl: {:?}",
        edit_lines
    );
    assert!(
        edit_lines.contains(&11),
        "rename Foo::run missed the $f->run call: {:?}",
        edit_lines
    );
    assert!(
        !edit_lines.contains(&6),
        "rename Foo::run wrongly rewrote Bar::run decl: {:?}",
        edit_lines
    );
    assert!(
        !edit_lines.contains(&12),
        "rename Foo::run wrongly rewrote $b->run call: {:?}",
        edit_lines
    );

    // Move `fa` into the store for the refs_to walk.
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/lsp_paths_fixture.pm");
    store.insert_workspace(path.clone(), fa);

    let foo_refs = refs_to(&store, None, &target_from_f, RoleMask::EDITABLE);
    let foo_lines: Vec<usize> = foo_refs.iter().map(|r| r.span.start.row).collect();
    assert!(
        foo_lines.contains(&2), // Foo::run decl
        "gr(Foo::run) missed decl: {:?}",
        foo_lines
    );
    assert!(
        foo_lines.contains(&11), // $f->run call
        "gr(Foo::run) missed $f->run call: {:?}",
        foo_lines
    );
    assert!(
        !foo_lines.contains(&6), // Bar::run decl
        "gr(Foo::run) wrongly included Bar::run decl: {:?}",
        foo_lines
    );
    assert!(
        !foo_lines.contains(&12), // $b->run call
        "gr(Foo::run) wrongly included $b->run call: {:?}",
        foo_lines
    );
}

/// Adversarial: two plain packages each declare `sub hi` and
/// `@EXPORT_OK = qw/hi/`. The caller does `use Sner;` (which
/// imports NOTHING — no @EXPORT, only @EXPORT_OK) and
/// `use Bler qw/hi/` (explicit import). The bare `hi()` call
/// therefore resolves to Bler's, not Sner's.
///
/// All four LSP paths must stay on the imported one (Bler):
///   * hover on `hi()` mentions Bler, not Sner.
///   * gd on `hi()` jumps to `sub hi` in Bler.
///   * gr on `hi()` includes the call + Bler::hi decl only.
///   * rename rewrites Bler::hi + the call, NOT Sner::hi.
///
/// Currently RED. The cross-class fix I landed only covered
/// MethodCall refs; FunctionCall refs are still name-only, and
/// the five different resolvers all collapse same-named subs
/// across packages.
///
/// The structural fix: `RefKind::FunctionCall` needs
/// `resolved_package: Option<String>`, populated at build time
/// by consulting `Imports`. Every resolver (find_definition,
/// hover_info, rename_kind_at, refs_to, rename_sub) keys off
/// that field. Same shape as `invocant_class` on MethodCall.
#[test]
fn sub_refs_respect_import_graph_not_just_name() {
    use crate::file_analysis::RenameKind;
    use tree_sitter::Parser;

    // Note: tree-sitter-perl parses bare `hi;` (no parens) as a
    // plain bareword, not a function call — so we write `hi();`
    // here to get a real `function_call_expression`. The
    // import-graph concern this test exercises is independent
    // of the parens question.
    //
    // Three packages, each with `sub hi`:
    //   - Sner — has @EXPORT_OK=qw/hi/, `use Sner;` (no import list
    //     → imports nothing, only @EXPORT would auto-import).
    //   - Bler — has @EXPORT_OK=qw/hi/, `use Bler qw/hi/` imports
    //     `hi` explicitly. This is the one our `hi()` call hits.
    //   - Xler — has `sub hi` too but no @EXPORT/@EXPORT_OK and
    //     never `use`d. It's just *there* in the file, its `hi`
    //     is unreachable to the main call. Double-pin: name-only
    //     resolution would union all three; correct resolution
    //     ignores Xler entirely.
    let src = r#"package Sner {
    our @EXPORT_OK = qw/hi/;
    sub hi {}
}
package Bler {
    our @EXPORT_OK = qw/hi/;
    sub hi {}
}
package Xler {
    sub hi {}
}

use Sner;
use Bler qw/hi/;

hi();
"#;
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let fa = crate::builder::build(&tree, src.as_bytes());

    // Positions (0-indexed rows; blank lines count):
    //   row 2  — `    sub hi {}` in Sner
    //   row 6  — `    sub hi {}` in Bler
    //   row 9  — `    sub hi {}` in Xler (unreachable — never imported)
    //   row 15 — `hi()` call
    let hi_call = tree_sitter::Point { row: 15, column: 0 };

    let kind = fa.rename_kind_at(hi_call, None);
    let hover = fa.hover_info(hi_call, src, None);
    let gd = fa.find_definition(hi_call, None);

    // Rename kind — for gr/rename construction.
    let target = match kind.as_ref() {
        Some(RenameKind::Function { name, package }) => TargetRef {
            name: name.clone(),
            kind: TargetKind::Sub {
                package: package.clone(),
            },
            method_classes: Vec::new(),
        },
        Some(RenameKind::Method { name, class }) => TargetRef {
            name: name.clone(),
            kind: TargetKind::Method {
                class: class.clone(),
            },
            method_classes: Vec::new(),
        },
        other => panic!("unexpected rename_kind_at = {:?}", other),
    };

    let rename_edits = match &kind {
        Some(RenameKind::Function { name, package }) => {
            fa.rename_sub_in_package(name, package, "renamed_hi", None)
        }
        Some(RenameKind::Method { name, class }) => {
            fa.rename_method_in_class(name, class, "renamed_hi", None)
        }
        _ => Vec::new(),
    };

    let store = FileStore::new();
    let path = PathBuf::from("/tmp/sub_import_fixture.pm");
    store.insert_workspace(path.clone(), fa);
    let refs_result = refs_to(&store, None, &target, RoleMask::EDITABLE);

    // ---- Collect all findings ----
    let mut failures: Vec<String> = Vec::new();

    // (1) hover: must mention Bler (imported source), not Sner or Xler.
    match &hover {
        Some(h) if h.contains("Bler") && !h.contains("Sner") && !h.contains("Xler") => { /* ok */ }
        Some(h) => failures.push(format!(
            "hover on `hi()` is ambiguous or names the wrong package; got: {:?} \
                 (should mention Bler; must not mention Sner or Xler)",
            h
        )),
        None => failures.push("hover on `hi()` returned None".into()),
    }

    // (2) gd: must jump to Bler::hi (row 6). Not Sner::hi (row 2), not Xler::hi (row 9).
    match gd {
        Some(s) if s.start.row == 6 => { /* ok */ }
        Some(s) if s.start.row == 2 => failures.push(format!(
            "gd jumped to Sner::hi (row 2) — \
                    should follow imports to Bler::hi (row 6)"
        )),
        Some(s) if s.start.row == 9 => failures.push(format!(
            "gd jumped to Xler::hi (row 9) — \
                    Xler isn't imported, it should be ignored"
        )),
        Some(s) => failures.push(format!(
            "gd jumped to row {} — expected row 6 (Bler::hi)",
            s.start.row
        )),
        None => failures.push("gd returned None".into()),
    }

    // (3) gr: should include Bler::hi decl (row 6) + `hi()` call (row 15).
    // Must NOT include Sner::hi decl (row 2) or Xler::hi decl (row 9).
    let ref_rows: Vec<usize> = refs_result.iter().map(|r| r.span.start.row).collect();
    if !ref_rows.contains(&15) {
        failures.push(format!("gr missed the hi() call at row 15: {:?}", ref_rows));
    }
    if !ref_rows.contains(&6) {
        failures.push(format!("gr missed Bler::hi decl at row 6: {:?}", ref_rows));
    }
    if ref_rows.contains(&2) {
        failures.push(format!(
            "gr wrongly unioned Sner::hi decl at row 2: {:?}",
            ref_rows
        ));
    }
    if ref_rows.contains(&9) {
        failures.push(format!(
            "gr wrongly unioned Xler::hi decl at row 9: {:?}",
            ref_rows
        ));
    }

    // (4) rename: should rewrite Bler::hi + hi() call; NOT Sner::hi or Xler::hi.
    let rename_rows: Vec<usize> = rename_edits.iter().map(|(s, _)| s.start.row).collect();
    if !rename_rows.contains(&15) {
        failures.push(format!(
            "rename missed hi() call at row 15: {:?}",
            rename_rows
        ));
    }
    if !rename_rows.contains(&6) {
        failures.push(format!(
            "rename missed Bler::hi decl at row 6: {:?}",
            rename_rows
        ));
    }
    if rename_rows.contains(&2) {
        failures.push(format!(
            "rename wrongly rewrote Sner::hi decl at row 2: {:?}",
            rename_rows
        ));
    }
    if rename_rows.contains(&9) {
        failures.push(format!(
            "rename wrongly rewrote Xler::hi decl at row 9: {:?}",
            rename_rows
        ));
    }

    assert!(
        failures.is_empty(),
        "import-graph-aware resolution broken across paths:\n  - {}",
        failures.join("\n  - "),
    );
}

/// Adversarial: documentHighlight (the in-editor "highlight all
/// references of this identifier" feature) must respect the
/// same class/package scoping as gr and rename. The mojo demo
/// shape — a helper `users.create` and a route with
/// `action => 'create'` — has two distinct `create` symbols in
/// one file. Cursor on one must NOT highlight the other.
#[test]
fn document_highlight_respects_scope_on_shared_method_name() {
    use tree_sitter::Parser;

    let src = r#"
package MyApp;
use Mojolicious::Lite;
use Mojolicious;

my $app = Mojolicious->new;
$app->helper('users.create' => sub ($c, $name, $email) {});

my $r = app->routes;
$r->post('/users')->to(controller => 'Users', action => 'create');
"#;
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let fa = crate::builder::build(&tree, src.as_bytes());

    // Lines (0-indexed; file starts with a blank row 0):
    //   row 6 — `$app->helper('users.create' => sub ...);`
    //   row 9 — `$r->post('/users')->to(controller => 'Users', action => 'create');`
    let line_helper = 6;
    let line_route = 9;

    let src_line = |n: usize| src.lines().nth(n).unwrap_or("");
    let helper_col = src_line(line_helper)
        .find("create")
        .expect("'create' on helper line");
    let route_col = src_line(line_route)
        .rfind("create")
        .expect("'create' on route line");

    // documentHighlight from the HELPER side: cursor inside
    // `users.create`. Must light up only helper-related spans,
    // NOT the route's `create` string at row 8.
    let helper_pt = tree_sitter::Point {
        row: line_helper,
        column: helper_col + 2,
    };
    let helper_highlights = fa.find_highlights(helper_pt, None);
    let helper_rows: Vec<usize> = helper_highlights.iter().map(|(s, _)| s.start.row).collect();
    assert!(
        helper_rows.contains(&line_helper),
        "helper highlight missed its own site: {:?}",
        helper_rows
    );
    assert!(
        !helper_rows.contains(&line_route),
        "helper highlight leaked into the route line — class-scoping broken: {:?}",
        helper_rows
    );

    // Mirror: documentHighlight from the ROUTE side. Cursor on
    // 'create' in `action => 'create'`. Must light up the route
    // ref only, NOT the helper's `create` site at row 5.
    let route_pt = tree_sitter::Point {
        row: line_route,
        column: route_col + 2,
    };
    let route_highlights = fa.find_highlights(route_pt, None);
    let route_rows: Vec<usize> = route_highlights.iter().map(|(s, _)| s.start.row).collect();
    assert!(
        route_rows.contains(&line_route),
        "route highlight missed its own site: {:?}",
        route_rows
    );
    assert!(
        !route_rows.contains(&line_helper),
        "route highlight leaked into the helper line — class-scoping broken: {:?}",
        route_rows
    );
}

/// Cross-file: gr on a `Users::create` method ref in one file
/// must find the definition in another workspace file AND every
/// call site across files — without cross-linking same-named
/// methods on unrelated classes.
#[test]
fn references_cross_file_method_respects_class_scope() {
    use crate::file_analysis::RenameKind;
    use tree_sitter::Parser;

    let store = FileStore::new();
    let parse_build = |source: &str| {
        let mut parser = Parser::new();
        parser
            .set_language(&ts_parser_perl::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();
        crate::builder::build(&tree, source.as_bytes())
    };

    // File 1: the route declaration.
    let f1_src = r#"
package MyApp;
use Mojolicious::Lite;

$app->helper('users.create' => sub ($c, $name) {});

my $r = app->routes;
$r->post('/users')->to(controller => 'Users', action => 'create');
"#;
    let f1 = parse_build(f1_src);
    store.insert_workspace(PathBuf::from("/tmp/app.pm"), f1);

    // File 2: Users controller with `sub create`.
    let f2_src = r#"
package Users;
sub create {
    my ($self, %args) = @_;
    return { ok => 1 };
}

sub list { }
1;
"#;
    let f2 = parse_build(f2_src);
    store.insert_workspace(PathBuf::from("/tmp/users.pm"), f2);

    // File 3: another caller that creates Users and invokes create.
    let f3_src = r#"
package Consumer;
use Users;
my $u = Users->new;
$u->create(name => 'alice');
1;
"#;
    let f3 = parse_build(f3_src);
    store.insert_workspace(PathBuf::from("/tmp/consumer.pm"), f3);

    // Probe: cursor on the route's 'create' action string in f1.
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let f1_tree = parser.parse(f1_src, None).unwrap();
    let f1_fa = crate::builder::build(&f1_tree, f1_src.as_bytes());
    // Row 7: `$r->post('/users')->to(controller => 'Users', action => 'create');`
    let route_row = 7usize;
    let line_route = f1_src.lines().nth(route_row).unwrap_or("");
    let create_col = line_route.rfind("create").expect("'create' on route line");
    let cursor = tree_sitter::Point {
        row: route_row,
        column: create_col + 2,
    };

    let kind = f1_fa.rename_kind_at(cursor, None);
    let target = match kind {
        Some(RenameKind::Method { name, class }) => TargetRef {
            name,
            kind: TargetKind::Method { class },
            method_classes: Vec::new(),
        },
        other => panic!("expected Method, got {:?}", other),
    };
    // class must be "Users" — from the plugin's emitted invocant_class.
    if let TargetKind::Method { ref class } = target.kind {
        assert_eq!(class, "Users", "target class should be Users");
    }

    let refs = refs_to(&store, None, &target, RoleMask::EDITABLE);

    // Collect (file-basename, row) for clarity.
    let hits: Vec<(String, usize)> = refs
        .iter()
        .map(|r| {
            let fname = match &r.key {
                FileKey::Path(p) => p.file_name().unwrap().to_str().unwrap().to_string(),
                FileKey::Url(u) => u.to_string(),
            };
            (fname, r.span.start.row)
        })
        .collect();

    // Expected:
    //   users.pm     — `sub create` decl (Users class)
    //   consumer.pm  — `$u->create(...)` call
    //   app.pm       — the route's 'create' ref at row 7
    let has_users_decl = hits.iter().any(|(f, _)| f == "users.pm");
    let has_consumer_call = hits.iter().any(|(f, _)| f == "consumer.pm");
    let has_route_ref = hits.iter().any(|(f, r)| f == "app.pm" && *r == route_row);

    assert!(
        has_users_decl,
        "gr missed Users::create decl (users.pm row 2): {:?}",
        hits
    );
    assert!(
        has_consumer_call,
        "gr missed $u->create caller (consumer.pm row 4): {:?}",
        hits
    );
    assert!(has_route_ref, "gr missed route ref in app.pm: {:?}", hits);

    // Must NOT include the helper's `users.create` in app.pm —
    // that's on a different class.
    let helper_row = f1_src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$app->helper"))
        .map(|(i, _)| i)
        .unwrap();
    let leaked_helper = hits.iter().any(|(f, r)| f == "app.pm" && *r == helper_row);
    assert!(
        !leaked_helper,
        "gr wrongly included the helper on a different class at row {}: {:?}",
        helper_row, hits
    );
}

#[test]
fn test_refs_to_empty_when_no_hits() {
    let store = FileStore::new();
    let fa = parse("package Only;\nsub bar { 1 }\n1;\n");
    store.insert_workspace(PathBuf::from("/tmp/resolve_no_hits.pm"), fa);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "nonexistent".to_string(),
            kind: TargetKind::Sub { package: None },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(results.is_empty());
}

/// Phase 5: hash key references are emitted with owner resolved at build
/// time when the binding is local. refs_to then matches both the def and
/// the access in the same file via the HashKeyOfSub target.
///
/// Cross-file HashKeyAccess owners are currently resolved through the
/// enrichment path (which injects synthetic HashKeyDefs in the consumer
/// file); this test covers the same-file case that lands purely via phase
/// 5 build-time linking. A follow-up (enrichment rebuild of
/// refs_by_target) will close the cross-file consumer-access case.
#[test]
fn test_refs_to_finds_hash_key_def_and_access_same_file() {
    let store = FileStore::new();
    let path = PathBuf::from("/tmp/resolve_hash_same.pm");

    let fa = parse(
            "package Lib;\nsub get_config { return { host => 1, port => 2 } }\nmy $cfg = get_config();\nmy $h = $cfg->{host};\n1;\n",
        );
    store.insert_workspace(path.clone(), fa);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "host".to_string(),
            kind: TargetKind::HashKeyOfSub {
                package: Some("Lib".to_string()),
                name: "get_config".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    // Expect at least the HashKeyDef decl AND the HashKeyAccess (both in
    // the same file). Previously, the access required a tree argument to
    // resolve its owner — now it's linked at build time.
    let has_decl = results.iter().any(|r| r.access == AccessKind::Declaration);
    let has_access = results.iter().any(|r| r.access == AccessKind::Read);
    assert!(has_decl, "expected HashKeyDef decl, got {:?}", results);
    assert!(has_access, "expected HashKeyAccess, got {:?}", results);
}

/// Cross-file: the HashKeyDef is discoverable in a different file even
/// when the consumer's access site hasn't been enriched yet. This is a
/// partial cross-file fix — consumer-side access resolution still needs
/// enrichment to run in the consumer's FileAnalysis.
#[test]
fn test_refs_to_finds_cross_file_hash_key_def() {
    let store = FileStore::new();
    let path_lib = PathBuf::from("/tmp/resolve_hash_cross_lib.pm");

    let fa_lib = parse("package Lib;\nsub get_config { return { host => 1, port => 2 } }\n1;\n");
    store.insert_workspace(path_lib.clone(), fa_lib);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "host".to_string(),
            kind: TargetKind::HashKeyOfSub {
                package: Some("Lib".to_string()),
                name: "get_config".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_lib)),
        "expected HashKeyDef match in Lib, got {:?}",
        results,
    );
}

/// THE bug the user caught: two different packages each with `sub X`
/// returning `{ key => ... }` must not cross-pollute. Before the
/// package-qualified `HashKeyOwner::Sub`, every file's `host` key would
/// show up regardless of which `get_config` defined it. Now only the
/// matching package's def does.
#[test]
fn test_refs_to_package_qualified_sub_owner_isolates_name_collisions() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_pkg_a.pm");
    let path_b = PathBuf::from("/tmp/resolve_pkg_b.pm");

    // Two different packages, same sub name, same key name.
    let fa_a = parse("package Alpha;\nsub get_config { return { host => 'alpha' } }\n1;\n");
    store.insert_workspace(path_a.clone(), fa_a);

    let fa_b = parse("package Beta;\nsub get_config { return { host => 'beta' } }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    // Query for `host` in Alpha's get_config — must NOT match Beta's.
    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "host".to_string(),
            kind: TargetKind::HashKeyOfSub {
                package: Some("Alpha".to_string()),
                name: "get_config".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)),
        "expected Alpha hit, got {:?}",
        results,
    );
    assert!(
        !results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b)),
        "Beta's get_config must NOT show up in Alpha's references, got {:?}",
        results,
    );
}

/// Fully-qualified call (`A::foo()`) references must reach the def in
/// package A, even though the call's `target_name` is the whole path
/// `A::foo` while the symbol is keyed by the bare name `foo`. The
/// `resolved_package` qualifier pins package A.
#[test]
fn test_refs_to_qualified_call_resolves_to_def() {
    let store = FileStore::new();
    let path_a = PathBuf::from("/tmp/resolve_qual_a.pm");
    let path_b = PathBuf::from("/tmp/resolve_qual_b.pm");

    let fa_a = parse("package A;\nsub foo { 42 }\n1;\n");
    store.insert_workspace(path_a.clone(), fa_a);

    // No import — the qualifier names the package directly.
    let fa_b = parse("package B;\nsub bar { A::foo(); A::foo() }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub {
                package: Some("A".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    // Decl in A.
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_a)),
        "expected the def in A, got {:?}",
        results,
    );
    // Both qualified call sites in B.
    let b_hits = results
        .iter()
        .filter(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b))
        .count();
    assert_eq!(b_hits, 2, "expected both A::foo() call sites, got {:?}", results);
}

/// A qualified call to package A's `foo` must not match a same-named
/// `foo` in package C — `resolved_package` isolates the qualifier.
#[test]
fn test_refs_to_qualified_call_isolates_package() {
    let store = FileStore::new();
    let path_b = PathBuf::from("/tmp/resolve_qual_iso_b.pm");

    let fa_b = parse("package B;\nsub bar { A::foo(); C::foo() }\n1;\n");
    store.insert_workspace(path_b.clone(), fa_b);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub {
                package: Some("A".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    // Only the A::foo() site, never C::foo().
    let b_hits = results
        .iter()
        .filter(|r| matches!(&r.key, FileKey::Path(p) if p == &path_b))
        .count();
    assert_eq!(b_hits, 1, "only A::foo() should match, got {:?}", results);
}

#[test]
fn test_refs_to_role_mask_excludes_workspace() {
    let store = FileStore::new();
    let fa = parse("package P;\nsub foo {}\n1;\n");
    store.insert_workspace(PathBuf::from("/tmp/masked.pm"), fa);

    // OPEN-only mask should miss this workspace file.
    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub { package: None },
            method_classes: Vec::new(),
        },
        RoleMask::OPEN,
    );
    assert!(results.is_empty());
}

/// Red-pin: cross-file `invocant_class` is set once at build time and
/// never refreshed. When a consumer file's `$b` invocant only becomes
/// typeable post-enrichment (because the producer's return type lives
/// in another file), the consumer's `$b->method()` MethodCall ref keeps
/// `invocant_class: None` forever — the bag learns the type but the
/// ref field doesn't get re-derived. `refs_to`'s
/// `(invocant_class, scope) match (Some(cn), Some(pkg)) => cn == pkg`
/// filter (resolve.rs:256-258) excludes unresolved invocants, so the
/// cross-file call site silently doesn't show up in references for the
/// target method.
///
/// Reproduces with two files:
///   - Producer B: exports `make_b`, which returns `bless {}, 'B'`.
///     `make_b`'s return type IS resolvable at build time (closed
///     under syntax) → `Symbol(make_b) → ClassName('B')` lands in B's
///     bag.
///   - Consumer A: `use B qw(make_b); my $b = make_b(); $b->touch();`.
///     At build time of A the imported sub's return type isn't
///     visible → `$b` untyped → `$b->touch()` ref's `invocant_class`
///     stays None.
///   - `enrich_imported_types_with_keys` on A does push a Variable
///     witness for `$b: ClassName('B')` (so `inferred_type_via_bag`
///     answers correctly) but does NOT re-fill the MethodCall ref's
///     `invocant_class`.
///   - `refs_to` for `B::touch` then misses A's call site.
///
/// Fix surface: either invalidate-and-rebuild the consumer when
/// upstream types arrive (heavy), or post-enrichment re-run
/// `apply_chain_typing_invocants` (or its FA-side equivalent) so refs
/// see the now-resolvable types. A query-time materializer that
/// resolves invocant from the bag on every refs_to read would also
/// work and avoids the cache-invalidation question.
#[test]
fn references_cross_file_invocant_resolved_post_enrichment() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let producer_src = r#"
package B;
use Exporter 'import';
our @EXPORT_OK = qw(make_b);

sub new    { return bless {}, shift }
sub make_b { return B->new }
sub touch  { 1 }
1;
"#;
    let consumer_src = r#"
use B qw(make_b);
my $b = make_b();
$b->touch();
1;
"#;

    let producer_path = PathBuf::from("/tmp/refs_xfile_b.pm");
    let consumer_path = PathBuf::from("/tmp/refs_xfile_a.pm");

    // Module index sees the producer so enrichment can resolve
    // `make_b`'s return type via cross-file scan.
    let idx = ModuleIndex::new_for_test();
    let producer_fa = parse(producer_src);
    idx.register_workspace_module(producer_path.clone(), Arc::new(producer_fa));

    // Build the consumer and enrich it. Post-enrichment, the bag
    // should know `$b: ClassName('B')` — verify that invariant first
    // so the test fails for the right reason.
    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));
    let b_type = consumer_fa.inferred_type_via_bag(
        "$b",
        tree_sitter::Point { row: 4, column: 0 },
    );
    assert_eq!(
        b_type.as_ref().and_then(|t| t.class_name()),
        Some("B"),
        "precondition: enrichment must type $$b as B; got {:?}",
        b_type,
    );

    // Build a FileStore over both files. `refs_to` reads
    // `invocant_class` directly off the consumer's MethodCall ref —
    // that field was populated at consumer-build time when B's types
    // weren't yet known.
    let store = FileStore::new();
    store.insert_workspace(producer_path, parse(producer_src));
    store.insert_workspace(consumer_path.clone(), consumer_fa);

    let target = TargetRef {
        name: "touch".to_string(),
        kind: TargetKind::Method { class: "B".to_string() },
        method_classes: Vec::new(),
    };
    let refs = refs_to(&store, Some(&idx), &target, RoleMask::WORKSPACE);
    let consumer_hit = refs.iter().any(|r| {
        matches!(&r.key, FileKey::Path(p) if p == &consumer_path)
    });
    assert!(
        consumer_hit,
        "refs_to(B::touch) missed consumer's $$b->touch() call site. \
         invocant_class on the MethodCall ref is None because the \
         consumer was built before B's return types were known, and \
         enrichment does not refresh ref fields. hits: {:?}",
        refs.iter().map(|r| (&r.key, r.span.start.row)).collect::<Vec<_>>(),
    );
}

/// Companion: `find_highlights`'s cross-file fallback path
/// must match both `$b->touch()` sites once enrichment has typed
/// `$b: B`. Cursor on the first call; the second has the same None
/// build-time-resolved invocant_class — both should highlight.
#[test]
fn find_highlights_cross_file_invocant_resolved_post_enrichment() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let producer_src = r#"
package B;
use Exporter 'import';
our @EXPORT_OK = qw(make_b);

sub new    { return bless {}, shift }
sub make_b { return B->new }
sub touch  { 1 }
1;
"#;
    let consumer_src = r#"
use B qw(make_b);
my $b = make_b();
$b->touch();
$b->touch();
1;
"#;

    let producer_path = PathBuf::from("/tmp/highlights_xfile_b.pm");

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(producer_path, Arc::new(parse(producer_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    // Cursor on the first $b->touch() — column 4 lands on `t` of touch.
    let highlights = consumer_fa.find_highlights(
        tree_sitter::Point { row: 3, column: 4 },
        Some(&idx));

    assert_eq!(
        highlights.len(),
        2,
        "find_highlights should match both $$b->touch() sites once \
         enrichment has typed $$b: B. got {:?}",
        highlights,
    );
}

/// Multi-hop: producer's exported sub returns a class that inherits
/// from another. The consumer's `$x->ancestor_method()` call site
/// resolves to the parent class only after enrichment + ancestor
/// walk. Confirms the bag-only path composes with cross-file
/// inheritance resolution.
#[test]
fn refs_to_cross_file_invocant_inherited_method() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let parent_src = r#"
package P;
sub new { return bless {}, shift }
sub ping { "pong" }
1;
"#;
    let child_src = r#"
package C;
use parent 'P';
use Exporter 'import';
our @EXPORT_OK = qw(make_c);
sub make_c { return C->new }
1;
"#;
    let consumer_src = r#"
use C qw(make_c);
my $x = make_c();
$x->ping();
1;
"#;

    let parent_path = PathBuf::from("/tmp/multihop_p.pm");
    let child_path = PathBuf::from("/tmp/multihop_c.pm");
    let consumer_path = PathBuf::from("/tmp/multihop_consumer.pm");

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(parent_path.clone(), Arc::new(parse(parent_src)));
    idx.register_workspace_module(child_path.clone(), Arc::new(parse(child_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    // Sanity: enrichment typed $x as C.
    let x_type = consumer_fa.inferred_type_via_bag(
        "$x",
        tree_sitter::Point { row: 4, column: 0 },
    );
    assert_eq!(
        x_type.as_ref().and_then(|t| t.class_name()),
        Some("C"),
        "precondition: enrichment must type $$x as C; got {:?}",
        x_type,
    );

    let store = FileStore::new();
    store.insert_workspace(parent_path, parse(parent_src));
    store.insert_workspace(child_path, parse(child_src));
    store.insert_workspace(consumer_path.clone(), consumer_fa);

    // Target the parent's `ping` — refs_to uses class-keyed Method
    // matching, so `$x->ping()` (whose nearest invocant class is C)
    // doesn't directly equal P. Targeting `C::ping` (the inherited
    // shape) is what matches today.
    let refs = refs_to(
        &store,
        Some(&idx),
        &TargetRef {
            name: "ping".to_string(),
            kind: TargetKind::Method { class: "C".to_string() },
            method_classes: Vec::new(),
        },
        RoleMask::WORKSPACE,
    );
    assert!(
        refs.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &consumer_path)),
        "refs_to(C::ping) missed consumer's $$x->ping() call site \
         (multi-hop: $$x typed as C only post-enrichment). hits: {:?}",
        refs.iter().map(|r| (&r.key, r.span.start.row)).collect::<Vec<_>>(),
    );
}

/// Perf bench, gated on `--features perf_bench` so the default
/// `cargo test` never sees it (no `#[ignore]` count). Generates
/// a synthetic workspace with N files × M method-call sites and
/// measures `refs_to` wall time. Useful when changing the
/// invocant resolver — gut-check the cost. Run with:
///   cargo test --release --features perf_bench -- --nocapture \
///     bench_refs_to_invocant_resolution
#[cfg(feature = "perf_bench")]
#[test]
fn bench_refs_to_invocant_resolution() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;
    use std::time::Instant;

    const N_FILES: usize = 200;
    const M_CALLS: usize = 50;
    const R_REPS: usize = 50;

    // Producer: defines `B::touch` plus a constructor.
    let producer_src = r#"
package B;
use Exporter 'import';
our @EXPORT_OK = qw(make_b);

sub new    { return bless {}, shift }
sub make_b { return B->new }
sub touch  { 1 }
1;
"#;

    let store = FileStore::new();
    let idx = ModuleIndex::new_for_test();
    let producer_path = PathBuf::from("/tmp/bench_b.pm");
    idx.register_workspace_module(producer_path.clone(), Arc::new(parse(producer_src)));
    store.insert_workspace(producer_path, parse(producer_src));

    // N consumer files, each with M method-call sites that mix:
    //  - $b->touch() (var invocant, cross-file enrichment)
    //  - B->touch() (bareword invocant)
    //  - $self->touch() (enclosing-class invocant)
    //  - $b->touch()->touch() (chain invocant)
    //  - make_b()->touch() (function-call invocant)
    for f in 0..N_FILES {
        let mut src = String::from(
            "package Consumer;\nuse B qw(make_b);\nsub run {\n  my $self = shift;\n  my $b = make_b();\n",
        );
        for c in 0..M_CALLS {
            match c % 5 {
                0 => src.push_str("  $b->touch();\n"),
                1 => src.push_str("  B->touch();\n"),
                2 => src.push_str("  $self->touch();\n"),
                3 => src.push_str("  $b->touch()->touch();\n"),
                _ => src.push_str("  make_b()->touch();\n"),
            }
        }
        src.push_str("}\n1;\n");
        let path = PathBuf::from(format!("/tmp/bench_consumer_{}.pm", f));
        let mut fa = parse(&src);
        fa.enrich_imported_types_with_keys(Some(&idx));
        store.insert_workspace(path, fa);
    }

    let target = TargetRef {
        name: "touch".to_string(),
        kind: TargetKind::Method { class: "B".to_string() },
        method_classes: Vec::new(),
    };

    // Warm-up — JIT'd registry caches, lazy index allocs.
    let _ = refs_to(&store, Some(&idx), &target, RoleMask::WORKSPACE);

    let t0 = Instant::now();
    let mut total_hits: usize = 0;
    for _ in 0..R_REPS {
        let refs = refs_to(&store, Some(&idx), &target, RoleMask::WORKSPACE);
        total_hits += refs.len();
    }
    let elapsed = t0.elapsed();
    let per_call = elapsed / (R_REPS as u32);
    eprintln!(
        "BENCH refs_to: {} files × {} calls × {} reps = {} hits in {:?} ({:?}/call avg)",
        N_FILES, M_CALLS, R_REPS, total_hits, elapsed, per_call,
    );
}

/// Discriminator: a chain hop where the inner receiver's class is
/// only known via cross-file enrichment. Hybrid branch (cache + bag
/// fallback inside `invocant_class_of_method_call`) handles VARIABLE
/// invocants whose type comes from enrichment, but does NOT handle
/// CHAIN invocants (`$x->makeFoo()->ping()`) when the inner
/// `$x->makeFoo()` ref's invocant_class cache stayed None at build
/// time — the hybrid's bag fallback hits `resolve_invocant_class`
/// which doesn't know how to walk a chain at read time. Option 2's
/// helper recurses on the inner receiver via `call_ref_by_start`,
/// re-resolving fresh, so cross-file enrichment composes through
/// every chain hop.
///
/// Expected:
///   * Option 2 branch: passes (refs_to finds the consumer's chain hop).
///   * Hybrid branch: fails (chain hop's class stays unknown).
#[test]
fn refs_to_cross_file_chain_hop_post_enrichment() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    // Producer P — defines a class returning itself (so makeFoo's return is P).
    let producer_src = r#"
package P;
use Exporter 'import';
our @EXPORT_OK = qw(makeP);

sub new     { return bless {}, shift }
sub makeP   { return P->new }
sub makeFoo { return P->new }
sub ping    { 1 }
1;
"#;
    // Consumer A — uses P, builds a chain whose inner receiver
    // ($x) is typed only by cross-file enrichment.
    let consumer_src = r#"
use P qw(makeP);
my $x = makeP();
$x->makeFoo()->ping();
1;
"#;

    let producer_path = PathBuf::from("/tmp/chain_xfile_p.pm");
    let consumer_path = PathBuf::from("/tmp/chain_xfile_consumer.pm");

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(producer_path.clone(), Arc::new(parse(producer_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    // Sanity: $x types as P via enrichment.
    let x_type = consumer_fa.inferred_type_via_bag(
        "$x",
        tree_sitter::Point { row: 4, column: 0 },
    );
    assert_eq!(
        x_type.as_ref().and_then(|t| t.class_name()),
        Some("P"),
        "precondition: enrichment must type $$x as P; got {:?}",
        x_type,
    );

    let store = FileStore::new();
    store.insert_workspace(producer_path, parse(producer_src));
    store.insert_workspace(consumer_path.clone(), consumer_fa);

    // refs_to(P::ping) — the consumer's `->ping()` is reachable
    // only by typing `$x->makeFoo()` (the chain hop's invocant)
    // through the cross-file P::makeFoo return type. Only works
    // if the helper resolves the chain hop fresh against the bag.
    let refs = refs_to(
        &store,
        Some(&idx),
        &TargetRef {
            name: "ping".to_string(),
            kind: TargetKind::Method { class: "P".to_string() },
            method_classes: Vec::new(),
        },
        RoleMask::WORKSPACE,
    );
    assert!(
        refs.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &consumer_path)),
        "refs_to(P::ping) missed the chain hop $$x->makeFoo()->ping(). \
         The inner $$x->makeFoo() invocant ($$x) was typed only by \
         cross-file enrichment; chain typing must compose through the \
         bag at read time. hits: {:?}",
        refs.iter().map(|r| (&r.key, r.span.start.row)).collect::<Vec<_>>(),
    );
}

/// `find_highlights` chain-hop case: receiver class only known
/// via cross-file `MethodOnClass` resolution (`$x->makeFoo()->ping()`
/// — `makeFoo` returns a cross-file class). Was a red-pin until
/// the polish commit threaded `module_index` through
/// `find_highlights` / `collect_refs_for_target` /
/// `find_references` / `rename_kind_at` / `rename_callable_in_scope`,
/// matching `crate::resolve::refs_to`'s already-threaded shape.
#[test]
fn find_highlights_cross_file_chain_hop_post_enrichment() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let producer_src = r#"
package P;
use Exporter 'import';
our @EXPORT_OK = qw(makeP);

sub new     { return bless {}, shift }
sub makeP   { return P->new }
sub makeFoo { return P->new }
sub ping    { 1 }
1;
"#;
    let consumer_src = r#"
use P qw(makeP);
my $x = makeP();
$x->makeFoo()->ping();
$x->makeFoo()->ping();
1;
"#;

    let producer_path = PathBuf::from("/tmp/highlights_chain_p.pm");
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(producer_path, Arc::new(parse(producer_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    // Cursor on the first `->ping()` — column 18 lands on `p` of ping.
    let highlights = consumer_fa.find_highlights(
        tree_sitter::Point { row: 3, column: 18 },
        Some(&idx));

    // Both call sites of `->ping()` share the same chain receiver
    // shape; they must highlight together once chain typing
    // composes through the bag at read time.
    assert_eq!(
        highlights.len(),
        2,
        "find_highlights should match both $$x->makeFoo()->ping() sites \
         once chain typing through cross-file enrichment is threaded \
         via module_index. got {:?}",
        highlights,
    );
}

/// Minion task references fan out cross-file. `$minion->add_task('T' => sub)`
/// stamps a `Handler` owned by `Class("Minion")`; every dispatch site
/// (`enqueue`, and crm's tenant sugar) emits a `DispatchCall` ref carrying
/// the same `(name, owner)`. Pairing is owner+name only — the dispatcher
/// verb never enters the match — so `refs_to(TargetKind::Handler)` collects
/// the registration AND every caller across files. This is the resolve-side
/// contract the LSP `references` handler and the `--references` CLI both lean
/// on for "go to references on a minion task".
#[test]
fn refs_to_handler_fans_out_across_files() {
    let store = FileStore::new();
    let path_reg = PathBuf::from("/tmp/resolve_minion_reg.pm");
    let path_call = PathBuf::from("/tmp/resolve_minion_call.pm");

    // Registry file: add_task stamps the Handler (owner Class("Minion")).
    let fa_reg = parse(
        "package App::Tasks;\nuse Minion;\n\
sub setup ($minion) {\n  $minion->add_task('send_email' => sub ($job, $to) { 1 });\n}\n1;\n",
    );
    store.insert_workspace(path_reg.clone(), fa_reg);

    // Caller file: plain enqueue dispatch site → DispatchCall ref.
    let fa_call = parse(
        "package App::Caller;\nuse Minion;\n\
sub fire ($minion) {\n  $minion->enqueue('send_email' => ['a@b']);\n}\n1;\n",
    );
    store.insert_workspace(path_call.clone(), fa_call);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "send_email".to_string(),
            kind: TargetKind::Handler {
                owner: crate::file_analysis::HandlerOwner::Class("Minion".to_string()),
                name: "send_email".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_reg)),
        "expected the add_task registration in the registry file, got {:?}",
        results,
    );
    assert!(
        results
            .iter()
            .any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_call)),
        "expected the cross-file enqueue caller, got {:?}",
        results,
    );
}

/// The query-time `ReceiverGated` gap closer: a Handler `refs_to` must
/// include a dispatch call-site in a NON-OPEN workspace file whose receiver
/// `isa Minion` only CROSS-FILE and which does NOT `use Minion` itself. The
/// emit-hook path can't fire (no `use Minion` trigger) and the file is never
/// enriched (workspace, not open), so nothing materializes a `DispatchCall`
/// ref. Under enrichment-eager promotion this call site was invisible
/// (the previously-`#[ignore]`d gap); query-time resolution of the gated
/// candidate against the cross-file `My::Minion isa Minion` chain surfaces
/// it. See `docs/adr/receiver-gated-dispatch.md`.
#[test]
fn refs_to_handler_finds_dispatch_in_unenriched_cross_file_subclass() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let store = FileStore::new();
    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    // `My::Minion isa Minion`, established cross-file in the index.
    let minion_sub_path = PathBuf::from("/tmp/rg_my_minion.pm");
    let minion_sub_fa = parse("package My::Minion;\nuse parent 'Minion';\nsub new { bless {}, shift }\n1;\n");
    idx.register_workspace_module(minion_sub_path, Arc::new(minion_sub_fa));

    // Registry file (open/workspace): add_task stamps the Handler.
    let path_reg = PathBuf::from("/tmp/rg_minion_reg.pm");
    let fa_reg = parse(
        "package App::Tasks;\nuse Minion;\n\
sub setup ($minion) {\n  $minion->add_task('send_email' => sub ($job, $to) { 1 });\n}\n1;\n",
    );
    store.insert_workspace(path_reg.clone(), fa_reg);

    // Caller: receiver is a cross-file Minion SUBCLASS, and the file does
    // NOT `use Minion`. Built without enrichment (insert_workspace mirrors
    // the indexer). No materialized DispatchCall ref — must resolve lazily.
    let path_call = PathBuf::from("/tmp/rg_minion_call.pm");
    let fa_call = parse(
        "package App::Worker;\n\
sub fire {\n  my $self = shift;\n  my $minion = My::Minion->new;\n  $minion->enqueue('send_email' => ['a@b']);\n}\n1;\n",
    );
    // Sanity: no DispatchCall ref was materialized at build (query-time path
    // is the only thing that can surface this site).
    assert!(
        !fa_call.refs.iter().any(|r|
            matches!(&r.kind, crate::file_analysis::RefKind::DispatchCall { .. })),
        "precondition: the caller must have NO materialized DispatchCall ref",
    );
    store.insert_workspace(path_call.clone(), fa_call);

    let results = refs_to(
        &store,
        Some(&idx),
        &TargetRef {
            name: "send_email".to_string(),
            kind: TargetKind::Handler {
                owner: crate::file_analysis::HandlerOwner::Class("Minion".to_string()),
                name: "send_email".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_reg)),
        "expected the add_task registration; got {:?}",
        results,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_call)),
        "expected the cross-file enqueue call-site in the unenriched subclass \
         worker to surface via query-time gated resolution; got {:?}",
        results,
    );
}

/// A package that declares its exports via a runtime exporter setup
/// (Sub::Exporter) must let cross-file `refs_to` fan the defining sub
/// out to a consumer's `use X qw/name/` import and call site — the
/// same as a `@EXPORT_OK` sub. Models the export so the import resolves.
#[test]
fn refs_to_fans_runtime_exported_sub_to_consumer() {
    let store = FileStore::new();
    let path_def = PathBuf::from("/tmp/runtime_export_def.pm");
    let path_use = PathBuf::from("/tmp/runtime_export_use.pm");

    // Exporting package: names come from Sub::Exporter, not @EXPORT_OK.
    let fa_def = parse(
        "package Sugar::Sub;\n\
         use Sub::Exporter -setup => { exports => [qw/sweeten/] };\n\
         sub sweeten { 42 }\n1;\n",
    );
    store.insert_workspace(path_def.clone(), fa_def);

    // Consumer imports and calls it.
    let fa_use = parse(
        "package Consumer;\n\
         use Sugar::Sub qw/sweeten/;\n\
         sub run { sweeten(); }\n1;\n",
    );
    store.insert_workspace(path_use.clone(), fa_use);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "sweeten".to_string(),
            kind: TargetKind::Sub { package: Some("Sugar::Sub".to_string()) },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_def)
            && r.access == AccessKind::Declaration),
        "expected declaration of sweeten in the exporting package; got {:?}",
        results,
    );
    assert!(
        results.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &path_use)),
        "expected the consumer's import/call of sweeten to fan out; got {:?}",
        results,
    );
}

/// Cross-file plain-sub references: an exported sub defined in one
/// workspace file, imported and called from two others, plus an
/// unrelated same-named sub in a *different* package that must NOT
/// be collected. Mirrors the crm `info_to_task` case (def in
/// TaskInfo, callers in TaskProxy + tests). The def-site query is the
/// one the hand-rolled CLI walk used to miss — here exercised through
/// `refs_to`, the single path both backend and CLI now share.
#[test]
fn references_cross_file_sub_fans_out_and_stays_package_scoped() {
    let store = FileStore::new();
    let def = PathBuf::from("/tmp/xsub_def.pm");
    let caller1 = PathBuf::from("/tmp/xsub_c1.pm");
    let caller2 = PathBuf::from("/tmp/xsub_c2.pm");
    let decoy = PathBuf::from("/tmp/xsub_decoy.pm");

    store.insert_workspace(
        def.clone(),
        parse("package TaskInfo;\nuse Exporter 'import';\nour @EXPORT_OK = qw/info_to_task/;\nsub info_to_task { 1 }\n1;\n"),
    );
    store.insert_workspace(
        caller1.clone(),
        parse("package TaskProxy;\nuse TaskInfo qw/info_to_task/;\nsub run { info_to_task(); }\n1;\n"),
    );
    store.insert_workspace(
        caller2.clone(),
        parse("use TaskInfo qw/info_to_task/;\ninfo_to_task();\n1;\n"),
    );
    // Decoy: a *different* package with a same-named sub, never imported.
    store.insert_workspace(
        decoy.clone(),
        parse("package Other;\nsub info_to_task { 99 }\nsub use_it { info_to_task(); }\n1;\n"),
    );

    let target = TargetRef {
        name: "info_to_task".to_string(),
        kind: TargetKind::Sub { package: Some("TaskInfo".to_string()) },
        method_classes: Vec::new(),
    };
    let refs = refs_to(&store, None, &target, RoleMask::EDITABLE);
    let hit = |p: &PathBuf| refs.iter().any(|r| matches!(&r.key, FileKey::Path(x) if x == p));

    assert!(hit(&def), "missed TaskInfo def. hits: {:?}", refs);
    assert!(hit(&caller1), "missed TaskProxy caller. hits: {:?}", refs);
    assert!(hit(&caller2), "missed top-level caller. hits: {:?}", refs);
    assert!(
        !hit(&decoy),
        "cross-linked Other::info_to_task (unrelated package). hits: {:?}",
        refs,
    );
}

/// Cross-file method references via inheritance: a method defined on
/// a parent/role, called on a child instance (`$child->m()`) in
/// another file, must surface when the *parent* class is the target.
/// This is the crm role case (`Clove::Role::REST::success` called as
/// `$c->success` in every controller that `with`s the role) and the
/// `todays_rate`/`add_data` shape generally. The matcher uses
/// `method_rename_chain`, so the parent is on the invocant's
/// resolution chain; an unrelated class sharing the method name is
/// not, and stays out.
#[test]
fn references_cross_file_method_matches_inheriting_invocant() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    // Role/parent defines `success`; child consumes it via `use parent`.
    let role_src = "package Role::REST;\nsub success { 1 }\n1;\n";
    let child_src = "package Ctrl;\nuse parent 'Role::REST';\nsub find ($c) { $c->success(); }\n1;\n";
    // Decoy: an unrelated class with its own `success`, called on its
    // own instance — must NOT be attributed to Role::REST.
    let decoy_src = "package Loner;\nsub new { bless {}, shift }\nsub success { 0 }\nsub go { my $x = Loner->new; $x->success(); }\n1;\n";

    let role_path = PathBuf::from("/tmp/inh_role.pm");
    let child_path = PathBuf::from("/tmp/inh_child.pm");
    let decoy_path = PathBuf::from("/tmp/inh_decoy.pm");

    // Module index carries parents so the child's cross-file ancestor
    // walk reaches Role::REST.
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(role_path.clone(), Arc::new(parse(role_src)));
    idx.register_workspace_module(child_path.clone(), Arc::new(parse(child_src)));

    let store = FileStore::new();
    store.insert_workspace(role_path.clone(), parse(role_src));
    store.insert_workspace(child_path.clone(), parse(child_src));
    store.insert_workspace(decoy_path.clone(), parse(decoy_src));

    let target = TargetRef {
        name: "success".to_string(),
        kind: TargetKind::Method { class: "Role::REST".to_string() },
        method_classes: Vec::new(),
    };
    let refs = refs_to(&store, Some(&idx), &target, RoleMask::EDITABLE);
    let hit = |p: &PathBuf| refs.iter().any(|r| matches!(&r.key, FileKey::Path(x) if x == p));

    assert!(hit(&role_path), "missed Role::REST::success decl. hits: {:?}", refs);
    assert!(
        hit(&child_path),
        "missed $c->success() in child controller (inherited from Role::REST). hits: {:?}",
        refs,
    );
    assert!(
        !hit(&decoy_path),
        "cross-linked Loner::success (unrelated class, own method). hits: {:?}",
        refs,
    );
}

/// `references_mask_for`: a target declared in editable space (open or
/// workspace) scopes to EDITABLE so "find references" never scans
/// @INC; a target with no editable declaration widens to VISIBLE.
#[test]
fn references_mask_scopes_to_editable_for_project_symbols() {
    let store = FileStore::new();
    let def = PathBuf::from("/tmp/mask_def.pm");
    store.insert_workspace(
        def.clone(),
        parse("package Proj;\nsub thing { 1 }\n1;\n"),
    );

    // Declared in the workspace → editable, no dep scan.
    let in_ws = TargetRef {
        name: "thing".to_string(),
        kind: TargetKind::Sub { package: Some("Proj".to_string()) },
        method_classes: Vec::new(),
    };
    assert_eq!(
        references_mask_for(&store, None, &in_ws).bits(),
        RoleMask::EDITABLE.bits(),
        "project-declared sub should scope to EDITABLE",
    );

    // No editable declaration anywhere → widen to VISIBLE so refs into
    // a dependency-defined symbol still surface.
    let dep_only = TargetRef {
        name: "nowhere".to_string(),
        kind: TargetKind::Sub { package: Some("CPAN::Thing".to_string()) },
        method_classes: Vec::new(),
    };
    assert_eq!(
        references_mask_for(&store, None, &dep_only).bits(),
        RoleMask::VISIBLE.bits(),
        "symbol with no editable decl should widen to VISIBLE",
    );
}

// ---- Rename-specific pins --------------------------------------------------------
//
// `rename_via_refs_to` in backend.rs calls `refs_to(EDITABLE)` directly —
// so these tests exercise the same code path rename uses. If rename and
// references ever diverge, a test here (EDITABLE) will disagree with
// the references test (VISIBLE/EDITABLE via references_mask_for).

/// Rename a base-class method: call sites on child-class invocants in
/// other workspace files must be included. This is the inheritance
/// fan-out the old per-file `rename_method_in_class` missed — it matched
/// `invocant_class == target_class` exactly, so `$child->ping()` (where
/// invocant class is "Child") fell out when targeting "Base::ping".
///
/// `refs_to` uses `method_rename_chain(invocant_class)` which checks
/// whether the target class is anywhere on the invocant's resolution
/// chain, so `$child->ping()` targeting Base IS matched when Child
/// inherits Base's `ping`.
///
/// Cross-file parent resolution requires a ModuleIndex (the consumer
/// file doesn't declare Child's parents — only child.pm does). The
/// module index is how production code surfaces this: the LSP backend
/// passes `Some(&self.module_index)` to every `refs_to` call.
#[test]
fn rename_base_method_includes_child_call_sites() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    // Base class file: defines the method being renamed.
    let base_src = r#"
package Base;
sub new { bless {}, shift }
sub ping { "pong" }
1;
"#;
    // Child class file: inherits from Base. No local `ping` override.
    let child_src = r#"
package Child;
use parent 'Base';
1;
"#;
    // Consumer file: calls `ping` on a Child instance.
    let consumer_src = r#"
package Consumer;
use Child;
my $c = Child->new;
$c->ping;
1;
"#;
    // Decoy file: unrelated class with a same-named method — must NOT appear.
    let decoy_src = r#"
package Decoy;
sub new { bless {}, shift }
sub ping { "decoy" }
my $d = Decoy->new;
$d->ping;
1;
"#;

    let base_path = PathBuf::from("/tmp/rename_base.pm");
    let child_path = PathBuf::from("/tmp/rename_child.pm");
    let consumer_path = PathBuf::from("/tmp/rename_consumer.pm");
    let decoy_path = PathBuf::from("/tmp/rename_decoy.pm");

    // Register base + child in module index so cross-file parent resolution
    // works (consumer_fa sees Child's parents via idx.parents_cached("Child")).
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(base_path.clone(), Arc::new(parse(base_src)));
    idx.register_workspace_module(child_path.clone(), Arc::new(parse(child_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    let store = FileStore::new();
    store.insert_workspace(base_path.clone(), parse(base_src));
    store.insert_workspace(child_path.clone(), parse(child_src));
    store.insert_workspace(consumer_path.clone(), consumer_fa);
    store.insert_workspace(decoy_path.clone(), parse(decoy_src));

    // Targeting Base::ping (where rename cursor would sit at the `sub ping` declaration).
    let target = TargetRef {
        name: "ping".to_string(),
        kind: TargetKind::Method { class: "Base".to_string() },
        method_classes: Vec::new(),
    };

    // Rename uses EDITABLE — workspace-only, no dep scan.
    let locs = refs_to(&store, Some(&idx), &target, RoleMask::EDITABLE);
    let hits: Vec<(&str, usize)> = locs.iter().map(|r| {
        let fname = match &r.key {
            FileKey::Path(p) => p.file_name().unwrap().to_str().unwrap(),
            FileKey::Url(_) => "url",
        };
        (fname, r.span.start.row)
    }).collect();

    // Base::ping declaration must be included.
    assert!(
        hits.iter().any(|(f, _)| *f == "rename_base.pm"),
        "rename missed Base::ping declaration: {:?}", hits,
    );
    // Consumer's $c->ping call on a Child invocant must be included —
    // Child inherits ping from Base so it's on the rename chain.
    assert!(
        hits.iter().any(|(f, _)| *f == "rename_consumer.pm"),
        "rename missed Consumer's $$c->ping call (inherited from Base via Child): {:?}", hits,
    );
    // Decoy::ping is an unrelated class — must NOT be included.
    assert!(
        !hits.iter().any(|(f, _)| *f == "rename_decoy.pm"),
        "rename wrongly included Decoy::ping (unrelated class): {:?}", hits,
    );
}

/// Rename never edits dependency files. A `ping` method that also appears
/// in a dep module (registered in ModuleIndex, not in the workspace store)
/// must not produce edits for that dep file — `RoleMask::EDITABLE` stops
/// at OPEN + WORKSPACE, which is what `rename_via_refs_to` uses.
#[test]
fn rename_does_not_edit_dep_files() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    // The dep defines Base::ping. It's in the module index (dep cache),
    // not in the workspace store.
    let dep_src = r#"
package Base;
sub new { bless {}, shift }
sub ping { "pong" }
1;
"#;
    let dep_path = PathBuf::from("/tmp/rename_dep_base.pm");

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(dep_path.clone(), Arc::new(parse(dep_src)));

    // Consumer in the workspace calls ping on a Base invocant.
    let consumer_src = r#"
package Consumer;
my $b = Base->new;
$b->ping;
1;
"#;
    let consumer_path = PathBuf::from("/tmp/rename_dep_consumer.pm");

    let store = FileStore::new();
    store.insert_workspace(consumer_path.clone(), parse(consumer_src));

    let target = TargetRef {
        name: "ping".to_string(),
        kind: TargetKind::Method { class: "Base".to_string() },
        method_classes: Vec::new(),
    };

    // EDITABLE mask — rename never scans deps.
    let editable_locs = refs_to(&store, Some(&idx), &target, RoleMask::EDITABLE);
    for loc in &editable_locs {
        assert!(
            !matches!(&loc.key, FileKey::Path(p) if p == &dep_path),
            "rename emitted an edit for the dep file (read-only): {:?}", editable_locs,
        );
    }

    // Sanity: VISIBLE would find the dep decl.
    let visible_locs = refs_to(&store, Some(&idx), &target, RoleMask::VISIBLE);
    assert!(
        visible_locs.iter().any(|r| matches!(&r.key, FileKey::Path(p) if p == &dep_path)),
        "sanity: VISIBLE should see dep file's ping decl: {:?}", visible_locs,
    );
}

/// Rename and references agree on the target set for a base-class Method:
/// both call `refs_to` with the same target, so the only difference should
/// be the mask (EDITABLE vs references_mask_for's EDITABLE-or-VISIBLE).
/// When the method is defined in workspace, references_mask_for returns
/// EDITABLE — so the result sets are IDENTICAL.
///
/// This is the DRY invariant: rename and references share one code path.
#[test]
fn rename_and_references_agree_on_same_base_method_target() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let base_src = r#"
package Greeter;
sub new { bless {}, shift }
sub hello { "hi" }
1;
"#;
    let child_src = r#"
package ChildGreeter;
use parent 'Greeter';
1;
"#;
    let consumer_src = r#"
package Main;
use ChildGreeter;
my $g = ChildGreeter->new;
$g->hello;
1;
"#;

    let base_path = PathBuf::from("/tmp/agree_greeter.pm");
    let child_path = PathBuf::from("/tmp/agree_child.pm");
    let consumer_path = PathBuf::from("/tmp/agree_consumer.pm");

    // Module index carries the Child→Base parent edge for cross-file chain walk.
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(base_path.clone(), Arc::new(parse(base_src)));
    idx.register_workspace_module(child_path.clone(), Arc::new(parse(child_src)));

    let mut consumer_fa = parse(consumer_src);
    consumer_fa.enrich_imported_types_with_keys(Some(&idx));

    let store = FileStore::new();
    store.insert_workspace(base_path.clone(), parse(base_src));
    store.insert_workspace(child_path.clone(), parse(child_src));
    store.insert_workspace(consumer_path.clone(), consumer_fa);

    let target = TargetRef {
        name: "hello".to_string(),
        kind: TargetKind::Method { class: "Greeter".to_string() },
        method_classes: Vec::new(),
    };

    // references uses references_mask_for (EDITABLE when def in workspace).
    let ref_mask = references_mask_for(&store, Some(&idx), &target);
    assert_eq!(ref_mask.bits(), RoleMask::EDITABLE.bits(),
        "precondition: references_mask_for should be EDITABLE when def is in workspace");

    let rename_locs = refs_to(&store, Some(&idx), &target, RoleMask::EDITABLE);
    let ref_locs    = refs_to(&store, Some(&idx), &target, ref_mask);

    // Collect (path, row) pairs for easy comparison.
    let to_set = |v: &[crate::resolve::RefLocation]| -> std::collections::BTreeSet<(String, usize)> {
        v.iter().map(|r| {
            let p = match &r.key {
                FileKey::Path(p) => p.display().to_string(),
                FileKey::Url(u) => u.to_string(),
            };
            (p, r.span.start.row)
        }).collect()
    };
    let rename_set = to_set(&rename_locs);
    let ref_set    = to_set(&ref_locs);

    assert_eq!(
        rename_set, ref_set,
        "rename and references disagree on target set for Greeter::hello\n\
         rename-only: {:?}\nrefs-only: {:?}",
        rename_set.difference(&ref_set).collect::<Vec<_>>(),
        ref_set.difference(&rename_set).collect::<Vec<_>>(),
    );
    // Also verify the consumer (child invocant) is in BOTH sets.
    assert!(
        rename_set.iter().any(|(f, _)| f.contains("agree_consumer")),
        "both rename and references must include consumer's $$g->hello call: {:?}",
        rename_set,
    );
}

/// Rename invoked AT THE CHILD CALL SITE of an inherited base method must
/// still edit the parent declaration. Here `rename_kind_at` returns the
/// cursor's static class (`MyWorker`), not the defining class (`BaseWorker`):
/// the parent `sub process` decl lives in a class the target's strict
/// `class` field never names. The fix precomputes the inheritance
/// rename-chain (`[MyWorker, .., BaseWorker]`) on the target — built from the
/// originating analysis, the only one that knows MyWorker's parents — so
/// `symbol_defines_target` admits a `sub NAME` in ANY chain class. Without
/// it the base declaration edit silently drops (the e2e inheritance rename
/// regression).
#[test]
fn rename_from_child_call_site_includes_inherited_base_declaration() {
    use crate::file_analysis::RenameKind;
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let base_src = "package BaseWorker;\nsub new { bless {}, shift }\nsub process { 1 }\n1;\n";
    // Child inherits process; no local override.
    let child_src = "package MyWorker;\nuse parent 'BaseWorker';\n1;\n";
    // Script calls process() on a MyWorker instance.
    let script_src = "use MyWorker;\nmy $worker = MyWorker->new;\n$worker->process();\n";

    let base_path = PathBuf::from("/tmp/cs_base.pm");
    let child_path = PathBuf::from("/tmp/cs_child.pm");
    let script_path = PathBuf::from("/tmp/cs_script.pl");

    // The originating analysis (the script) must know MyWorker's parents to
    // build the chain — production threads the module index for exactly this.
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(base_path.clone(), Arc::new(parse(base_src)));
    idx.register_workspace_module(child_path.clone(), Arc::new(parse(child_src)));

    let mut script_fa = parse(script_src);
    script_fa.enrich_imported_types_with_keys(Some(&idx));

    // Resolve the target the way the rename handler does: cursor on the
    // `process` token of `$worker->process()`, mapped via from_rename_kind.
    let call_point = tree_sitter::Point { row: 2, column: 9 };
    let rk = script_fa.rename_kind_at(call_point, Some(&idx));
    assert!(
        matches!(&rk, Some(RenameKind::Method { class, .. }) if class == "MyWorker"),
        "precondition: call-site rename_kind_at should resolve invocant class MyWorker, got {:?}",
        rk,
    );
    let target = TargetRef::from_rename_kind(rk.unwrap(), &script_fa, Some(&idx))
        .expect("Method maps to a target");
    assert!(
        target.method_classes.iter().any(|c| c == "BaseWorker"),
        "chain must reach the defining ancestor BaseWorker, got {:?}",
        target.method_classes,
    );

    let store = FileStore::new();
    store.insert_workspace(base_path.clone(), parse(base_src));
    store.insert_workspace(child_path.clone(), parse(child_src));
    store.insert_workspace(script_path.clone(), script_fa);

    let locs = refs_to(&store, Some(&idx), &target, RoleMask::EDITABLE);
    let hit = |p: &PathBuf| locs.iter().any(|r| matches!(&r.key, FileKey::Path(x) if x == p));

    assert!(
        hit(&base_path),
        "rename from child call site dropped the BaseWorker::process declaration edit. hits: {:?}",
        locs,
    );
    assert!(
        hit(&script_path),
        "rename from child call site missed the $worker->process() call edit. hits: {:?}",
        locs,
    );
}

// ---- resolve_symbol: the single cursor→target entry point ----

/// Every kind that maps to a cross-file target must come back as
/// `Target`, lexical variables as `Local`, and blank space as `None` —
/// the same answers regardless of which handler (LSP or CLI) asks.
#[test]
fn test_resolve_symbol_kinds() {
    let src = "\
package Counter;
sub new { my ($class) = @_; return bless { count => 0 }, $class }
sub bump { my ($self) = @_; $self->{count}++; my $local = 1; return $local }
1;
";
    let fa = parse(src);
    let at = |row, col| resolve_symbol(&fa, tree_sitter::Point { row, column: col }, None);

    // `bump` decl → callable target scoped to the package ("same callable,
    // two shapes": decls surface as Sub even when call sites are Method).
    match at(2, 5) {
        Some(ResolvedTarget::Target(t)) => {
            assert_eq!(t.name, "bump");
            assert!(
                matches!(&t.kind, TargetKind::Sub { package: Some(p) } if p == "Counter"),
                "expected Sub scoped to Counter, got {:?}",
                t.kind,
            );
            assert!(t.supports_cross_file_rename());
        }
        other => panic!("expected callable target for bump decl, got {:?}", other),
    }

    // Package name → Package target.
    match at(0, 9) {
        Some(ResolvedTarget::Target(t)) => {
            assert!(matches!(t.kind, TargetKind::Package));
            assert!(t.supports_cross_file_rename());
        }
        other => panic!("expected Package target, got {:?}", other),
    }

    // `$local` → lexical, single-file.
    let local_col = src.lines().nth(2).unwrap().find("$local").unwrap() + 1;
    assert!(
        matches!(at(2, local_col), Some(ResolvedTarget::Local)),
        "expected Local for lexical $local, got {:?}",
        at(2, local_col),
    );
}

/// An owned hash key resolves to a cross-file HashKeyOfClass target —
/// walkable by references — but reports itself non-renameable
/// cross-file (hash-key rename is in-file-only by design). This is the
/// divergence the CLI used to have: its references path dropped owned
/// hash keys to single-file because the owner mapping lived only in the
/// LSP handler.
#[test]
fn test_resolve_symbol_owned_hash_key() {
    let src = "\
package Widget;
use Moo;
has size => (is => 'ro');
sub describe { my ($self) = @_; return $self->{size} }
1;
";
    let fa = parse(src);
    // Cursor on `size` inside `$self->{size}`.
    let col = src.lines().nth(3).unwrap().find("{size}").unwrap() + 1;
    match resolve_symbol(&fa, tree_sitter::Point { row: 3, column: col }, None) {
        Some(ResolvedTarget::Target(t)) => {
            assert_eq!(t.name, "size");
            assert!(
                matches!(&t.kind, TargetKind::HashKeyOfClass(c) if c == "Widget"),
                "expected HashKeyOfClass(Widget), got {:?}",
                t.kind,
            );
            assert!(!t.supports_cross_file_rename());
        }
        other => panic!("expected owned hash-key target, got {:?}", other),
    }
}

// ---- field projection groups: cross-file union ----

/// `field $x :param :reader` in Point.pm; a consumer constructs
/// `Point->new(x => 1)` and reads `$p->x`. References/rename from the
/// field decl must surface the consumer's ctor key and reader call;
/// from the consumer's key, the field must surface back.
#[test]
fn test_field_group_unions_across_files() {
    let store = FileStore::new();
    let point_path = PathBuf::from("/tmp/fieldgroup_point.pm");
    let user_path = PathBuf::from("/tmp/fieldgroup_user.pl");

    let point_src = "\
use v5.38;
class Point {
    field $x :param :reader;
    method magnitude () { return $x * $x; }
}
1;
";
    let user_src = "\
use Point;
my $p = Point->new(x => 3);
my $val = $p->x;
";
    let point_fa = parse(point_src);
    let user_fa = parse(user_src);
    store.insert_workspace(point_path.clone(), point_fa);
    store.insert_workspace(user_path.clone(), user_fa);

    let origin_fa = store.workspace_raw().get(&point_path).unwrap().value().clone();
    // Cursor on `$x` in the field decl (row 2, col 11 = bare name).
    let resolved = resolve_symbol(&origin_fa, tree_sitter::Point { row: 2, column: 11 }, None)
        .expect("field decl resolves");
    let ResolvedTarget::Group { local_spans, pinned_spans, members } = resolved else {
        panic!("expected Group, got {:?}", resolved);
    };
    assert!(pinned_spans.is_empty(), "local mint has no pinned spans");
    assert!(!local_spans.is_empty(), "field var spellings present");
    assert_eq!(members.len(), 2, "reader + ctor-key members: {:?}", members);

    let locs = group_refs(
        &store,
        None,
        &FileKey::Path(point_path.clone()),
        &local_spans,
        &pinned_spans,
        &members,
        None,
    );
    let in_user: Vec<_> = locs
        .iter()
        .filter(|l| matches!(&l.key, FileKey::Path(p) if p == &user_path))
        .map(|l| (l.span.start.row, l.span.start.column))
        .collect();
    assert!(
        in_user.contains(&(1, 19)),
        "consumer ctor key `x` included; user-file hits: {:?}",
        in_user,
    );
    assert!(
        in_user.contains(&(2, 14)),
        "consumer reader call `->x` included; user-file hits: {:?}",
        in_user,
    );
}

/// Consumer-side cursor, class elsewhere: from the ctor key (or accessor
/// call) in a file that only `use`s Point, the group is minted from the
/// CLASS's cached analysis — its field-variable/decl spans pin to the
/// class file, so rename from the consumer rewrites the field decl and
/// body uses over there too.
#[test]
fn test_consumer_cursor_mints_group_from_class_analysis() {
    let point_src = "\
use v5.38;
class Point {
    field $x :param :reader;
    method magnitude () { return $x * $x; }
}
1;
";
    let idx = crate::module_index::ModuleIndex::new_for_test();
    let class_path = PathBuf::from("/tmp/grp_mint_point.pm");
    idx.insert_cache(
        "Point",
        Some(std::sync::Arc::new(crate::module_index::CachedModule::new(
            class_path.clone(),
            std::sync::Arc::new(parse(point_src)),
        ))),
    );

    let consumer = parse("use Point;\nmy $p = Point->new(x => 3);\nmy $v = $p->x;\n");

    // From the ctor key `x` (row 1, col 19).
    let resolved = resolve_symbol(&consumer, tree_sitter::Point { row: 1, column: 19 }, Some(&idx))
        .expect("consumer key resolves");
    let ResolvedTarget::Group { local_spans, pinned_spans, members } = resolved else {
        panic!("expected Group from consumer key, got {:?}", resolved);
    };
    assert!(local_spans.is_empty(), "remote mint: no origin spans");
    assert_eq!(members.len(), 2, "reader + ctor-key members");
    assert!(
        pinned_spans.iter().all(|(p, _)| p == &class_path),
        "pinned to the class file: {:?}",
        pinned_spans,
    );
    // Decl (row 2) + body use (row 3) pinned from the class analysis.
    let pinned_rows: Vec<usize> = pinned_spans.iter().map(|(_, s)| s.start.row).collect();
    assert!(
        pinned_rows.contains(&2) && pinned_rows.contains(&3),
        "field decl + body use pinned: {:?}",
        pinned_rows,
    );

    // From the accessor call `->x` (row 2, col 12): same group shape.
    let resolved = resolve_symbol(&consumer, tree_sitter::Point { row: 2, column: 12 }, Some(&idx))
        .expect("consumer accessor resolves");
    assert!(
        matches!(resolved, ResolvedTarget::Group { ref pinned_spans, .. } if !pinned_spans.is_empty()),
        "accessor-call cursor mints the remote group, got {:?}",
        resolved,
    );
}

/// Cross-file mapped rename: the consumer's `$w->has_size` predicate
/// call re-derives to `has_extent` when the attr renames — per-member
/// replacement texts via group_rename_edits.
#[test]
fn test_group_rename_rederives_mapped_members_cross_file() {
    let store = FileStore::new();
    let class_path = PathBuf::from("/tmp/grp_map_widget.pm");
    let user_path = PathBuf::from("/tmp/grp_map_user.pl");
    store.insert_workspace(
        class_path.clone(),
        parse("package Widget;\nuse Moo;\nhas size => (is => 'ro', predicate => 1);\n1;\n"),
    );
    store.insert_workspace(
        user_path.clone(),
        parse("use Widget;\nmy $w = Widget->new(size => 3);\nprint $w->size if $w->has_size;\n"),
    );

    let class_fa = store.workspace_raw().get(&class_path).unwrap().value().clone();
    // Cursor on the attr decl token `size` (row 2, col 4).
    let resolved = resolve_symbol(&class_fa, tree_sitter::Point { row: 2, column: 4 }, None)
        .expect("attr decl resolves");
    let ResolvedTarget::Group { local_spans, pinned_spans, members } = resolved else {
        panic!("expected Group, got {:?}", resolved);
    };
    let edits = group_rename_edits(
        &store,
        None,
        &FileKey::Path(class_path.clone()),
        &local_spans,
        &pinned_spans,
        &members,
        "extent",
    );
    let user_edits: Vec<_> = edits
        .iter()
        .filter(|(l, _)| matches!(&l.key, FileKey::Path(p) if p == &user_path))
        .map(|(l, t)| (l.span.start.row, l.span.start.column, t.clone()))
        .collect();
    assert!(
        user_edits.contains(&(2, 22, "has_extent".to_string())),
        "consumer predicate call re-derived; user edits: {:?}",
        user_edits,
    );
    assert!(
        user_edits.iter().any(|(r, _, t)| *r == 1 && t == "extent"),
        "consumer ctor key renamed bare; user edits: {:?}",
        user_edits,
    );
}

/// Internal slot pokes join the group cross-file: a subclass (or any
/// promiscuous consumer) reaching into `$self->{size}` renames with the
/// attr — under STRICT Class-owner matching, so another sub's
/// `(size => 1)` arg keys in unrelated classes stay out.
#[test]
fn test_internal_slot_pokes_join_group_cross_file() {
    let store = FileStore::new();
    let class_path = PathBuf::from("/tmp/grp_slot_widget.pm");
    let sub_path = PathBuf::from("/tmp/grp_slot_subclass.pm");
    store.insert_workspace(
        class_path.clone(),
        parse("package Widget;\nuse Moo;\nhas size => (is => 'rw');\n1;\n"),
    );
    // Subclass pokes the parent's slot directly — classic promiscuous Perl.
    store.insert_workspace(
        sub_path.clone(),
        parse("package Gadget;\nuse Moo;\nextends 'Widget';\nsub poke { my ($self) = @_; return $self->{size}; }\n1;\n"),
    );

    let class_fa = store.workspace_raw().get(&class_path).unwrap().value().clone();
    let resolved = resolve_symbol(&class_fa, tree_sitter::Point { row: 2, column: 4 }, None)
        .expect("attr decl resolves");
    let ResolvedTarget::Group { local_spans, pinned_spans, members } = resolved else {
        panic!("expected Group, got {:?}", resolved);
    };
    assert!(
        members.iter().any(|m| matches!(m.target.kind, TargetKind::InternalHashKey { .. })),
        "internal-key member minted: {:?}",
        members,
    );
    let edits = group_rename_edits(
        &store,
        None,
        &FileKey::Path(class_path.clone()),
        &local_spans,
        &pinned_spans,
        &members,
        "extent",
    );
    assert!(
        edits.iter().any(|(l, t)| {
            matches!(&l.key, FileKey::Path(p) if p == &sub_path) && t == "extent"
        }),
        "subclass slot poke renamed; edits: {:?}",
        edits,
    );
}

#[test]
fn test_implementations_of_role_requires_fans_out_to_composers() {
    use crate::module_index::{CachedModule, ModuleIndex};
    use std::sync::Arc;

    let idx = ModuleIndex::new_for_test();
    let insert = |name: &str, src: &str| {
        let analysis = Arc::new(parse(src));
        idx.insert_cache(
            name,
            Some(Arc::new(CachedModule::new(
                PathBuf::from(format!("/fake/{}.pm", name.replace("::", "/"))),
                analysis,
            ))),
        );
    };
    insert("My::Role", "package My::Role;\nuse Moo::Role;\nrequires 'fetch';\n1;\n");
    insert(
        "My::Composer",
        "package My::Composer;\nuse Moo;\nwith 'My::Role';\nsub fetch { 42 }\n1;\n",
    );
    // Role-composing-role: re-requires the contract (a marker, not an
    // implementation) and adds a transitive hop to reach My::Deep.
    insert(
        "My::SubRole",
        "package My::SubRole;\nuse Moo::Role;\nwith 'My::Role';\nrequires 'fetch';\n1;\n",
    );
    insert("My::Deep", "package My::Deep;\nuse Moo;\nwith 'My::SubRole';\nsub fetch { 7 }\n1;\n");

    let target = TargetRef {
        name: "fetch".to_string(),
        kind: TargetKind::Method { class: "My::Role".to_string() },
        method_classes: Vec::new(),
    };
    let origin = parse("package Probe;\n1;\n");
    let results = implementations_of(&origin, Some(&idx), &target);
    let files: Vec<String> = results
        .iter()
        .map(|r| match &r.key {
            FileKey::Path(p) => p.display().to_string(),
            FileKey::Url(u) => u.to_string(),
        })
        .collect();
    assert_eq!(
        files,
        vec!["/fake/My/Composer.pm", "/fake/My/Deep.pm"],
        "direct + transitive composer defs, sorted; the SubRole re-requires marker excluded",
    );

    // Non-Method targets have no descendant-implementation semantics.
    let pkg_target = TargetRef::new("My::Role".to_string(), TargetKind::Package);
    assert!(implementations_of(&origin, Some(&idx), &pkg_target).is_empty());
}