syster-base 0.3.4-alpha

Core library for SysML v2 and KerML parsing, AST, and semantic analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
//! Name resolution — resolving references to their definitions.
//!
//! This module provides name resolution for SysML/KerML.
//! It builds on top of the symbol extraction layer.
//!
//! # Architecture (January 2026)
//!
//! Name resolution follows a rust-analyzer inspired pattern:
//!
//! 1. **Symbol Extraction** - HIR extraction captures raw names/references with spans
//! 2. **Visibility Maps** - A separate pass builds per-scope visibility maps with resolved imports
//! 3. **Query-time Resolution** - Uses pre-computed visibility maps for O(1) lookups
//!
//! ## Key Data Structures
//!
//! - [`ScopeVisibility`] - Per-scope map of visible symbols (direct + imported)
//! - [`SymbolIndex`] - Global index with all symbols + pre-computed visibility maps
//! - [`Resolver`] - Query-time resolution using visibility maps

use indexmap::IndexMap;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

use super::symbols::{HirSymbol, RefKind, SymbolKind, TypeRefKind};
use crate::base::FileId;

/// Type alias for resolution cache: (name, starting_scope) -> resolved_qname
type ResolutionCache = HashMap<(Arc<str>, Arc<str>), Option<Arc<str>>>;

// ============================================================================
// SCOPE VISIBILITY (Pre-computed at index time)
// ============================================================================

/// Per-scope visibility map capturing what names are visible and where they resolve to.
///
/// Built once during index construction, used at query time for O(1) resolution.
///
/// # Example
///
/// For a scope like `ISQ` with `public import ISQSpaceTime::*`:
/// - `direct_defs` contains symbols defined directly in ISQ
/// - `imports` contains symbols from ISQSpaceTime (via the wildcard import)
/// - `public_reexports` tracks that ISQSpaceTime's symbols are re-exported
#[derive(Clone, Debug, Default)]
pub struct ScopeVisibility {
    /// The scope this visibility applies to (e.g., "ISQ", "Automotive::Torque").
    scope: Arc<str>,

    /// Symbols defined directly in this scope.
    /// SimpleName → QualifiedName
    direct_defs: HashMap<Arc<str>, Arc<str>>,

    /// Symbols visible via imports (includes transitive public re-exports).
    /// SimpleName → QualifiedName (the resolved target)
    imports: HashMap<Arc<str>, Arc<str>>,

    /// Namespaces that are publicly re-exported from this scope.
    /// Used for transitive import resolution.
    public_reexports: Vec<Arc<str>>,
}

impl ScopeVisibility {
    /// Create a new empty visibility map for a scope.
    pub fn new(scope: impl Into<Arc<str>>) -> Self {
        Self {
            scope: scope.into(),
            direct_defs: HashMap::new(),
            imports: HashMap::new(),
            public_reexports: Vec::new(),
        }
    }

    /// Get the scope this visibility applies to.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Look up a simple name in this scope's visibility.
    ///
    /// Checks direct definitions first, then imports.
    /// Returns the qualified name if found.
    pub fn lookup(&self, name: &str) -> Option<&Arc<str>> {
        self.direct_defs
            .get(name)
            .or_else(|| self.imports.get(name))
    }

    /// Look up only in direct definitions.
    pub fn lookup_direct(&self, name: &str) -> Option<&Arc<str>> {
        self.direct_defs.get(name)
    }

    /// Look up only in imports.
    pub fn lookup_import(&self, name: &str) -> Option<&Arc<str>> {
        self.imports.get(name)
    }

    /// Add a direct definition to this scope.
    pub fn add_direct(&mut self, simple_name: Arc<str>, qualified_name: Arc<str>) {
        self.direct_defs.insert(simple_name, qualified_name);
    }

    /// Add an imported symbol to this scope.
    pub fn add_import(&mut self, simple_name: Arc<str>, qualified_name: Arc<str>) {
        // Don't overwrite direct definitions with imports
        if !self.direct_defs.contains_key(&simple_name) {
            self.imports.insert(simple_name, qualified_name);
        }
    }

    /// Add a public re-export (for transitive import resolution).
    pub fn add_public_reexport(&mut self, namespace: Arc<str>) {
        if !self.public_reexports.contains(&namespace) {
            self.public_reexports.push(namespace);
        }
    }

    /// Get all public re-exports.
    pub fn public_reexports(&self) -> &[Arc<str>] {
        &self.public_reexports
    }

    /// Get iterator over all direct definitions.
    pub fn direct_defs(&self) -> impl Iterator<Item = (&Arc<str>, &Arc<str>)> {
        self.direct_defs.iter()
    }

    /// Get iterator over all imports.
    pub fn imports(&self) -> impl Iterator<Item = (&Arc<str>, &Arc<str>)> {
        self.imports.iter()
    }

    /// Get count of visible symbols (direct + imported).
    pub fn len(&self) -> usize {
        self.direct_defs.len() + self.imports.len()
    }

    /// Check if visibility map is empty.
    pub fn is_empty(&self) -> bool {
        self.direct_defs.is_empty() && self.imports.is_empty()
    }

    /// Debug: dump contents of this visibility map.
    pub fn debug_dump(&self) -> String {
        let mut s = format!(
            "Scope '{}': {} direct, {} imports\n",
            self.scope,
            self.direct_defs.len(),
            self.imports.len()
        );
        for (name, qname) in self.direct_defs.iter().take(10) {
            s.push_str(&format!("  direct: {} -> {}\n", name, qname));
        }
        if self.direct_defs.len() > 10 {
            s.push_str(&format!(
                "  ... and {} more direct defs\n",
                self.direct_defs.len() - 10
            ));
        }
        for (name, qname) in self.imports.iter().take(10) {
            s.push_str(&format!("  import: {} -> {}\n", name, qname));
        }
        if self.imports.len() > 10 {
            s.push_str(&format!(
                "  ... and {} more imports\n",
                self.imports.len() - 10
            ));
        }
        s
    }
}

// ============================================================================
// SYMBOL INDEX
// ============================================================================

/// Index into the symbols vector.
pub type SymbolIdx = usize;

/// An index of all symbols across multiple files.
///
/// This is the main data structure for workspace-wide name resolution.
/// It includes pre-computed visibility maps for efficient query-time resolution.
///
/// Symbols are stored in a single vector (`symbols`) and referenced by index
/// from all other maps. This ensures consistency when symbols are mutated
/// (e.g., when resolving type references).
#[derive(Debug, Default)]
pub struct SymbolIndex {
    /// The single source of truth for all symbols.
    symbols: Vec<HirSymbol>,
    /// Index by qualified name -> symbol index (IndexMap preserves insertion order).
    by_qualified_name: IndexMap<Arc<str>, SymbolIdx>,
    /// Index by simple name -> symbol indices (may have multiple).
    by_simple_name: HashMap<Arc<str>, Vec<SymbolIdx>>,
    /// Index by short name (alias) -> symbol indices (for lookups like `kg` -> `SI::kilogram`).
    by_short_name: HashMap<Arc<str>, Vec<SymbolIdx>>,
    /// Index by file -> symbol indices.
    by_file: HashMap<FileId, Vec<SymbolIdx>>,
    /// Definitions only (not usages) -> symbol indices.
    definitions: HashMap<Arc<str>, SymbolIdx>,
    /// Lazily-built visibility map for each scope.
    /// Built on-demand when a scope is queried, not upfront.
    visibility_map: HashMap<Arc<str>, ScopeVisibility>,
    /// Index from parent scope -> child symbol indices (for fast visibility building)
    by_parent_scope: HashMap<Arc<str>, Vec<SymbolIdx>>,
    /// Filters for each scope (e.g., "SafetyGroup" -> ["Safety"])
    /// Elements must have ALL listed metadata to be visible in that scope.
    /// These come from `filter @Metadata;` statements.
    scope_filters: HashMap<Arc<str>, Vec<Arc<str>>>,
    /// Filters for specific imports (import qualified name -> metadata names)
    /// These come from bracket syntax: `import X::*[@Filter]`
    import_filters: HashMap<Arc<str>, Vec<Arc<str>>>,
    /// Flag to track if parent scope index needs rebuilding.
    parent_index_dirty: bool,
    /// Cache for SemanticMetadata baseType resolution (with interior mutability for lazy population).
    /// Maps annotation short name (e.g., "systemdd") -> resolved baseType qualified name (e.g., "AHFProfileLib::SysDD").
    /// None value means "already looked up, no baseType found".
    metadata_basetype_cache: RwLock<HashMap<Arc<str>, Option<Arc<str>>>>,
}

// Manual Clone implementation because RwLock doesn't implement Clone
impl Clone for SymbolIndex {
    fn clone(&self) -> Self {
        Self {
            symbols: self.symbols.clone(),
            by_qualified_name: self.by_qualified_name.clone(),
            by_simple_name: self.by_simple_name.clone(),
            by_short_name: self.by_short_name.clone(),
            by_file: self.by_file.clone(),
            definitions: self.definitions.clone(),
            visibility_map: self.visibility_map.clone(),
            by_parent_scope: self.by_parent_scope.clone(),
            scope_filters: self.scope_filters.clone(),
            import_filters: self.import_filters.clone(),
            parent_index_dirty: self.parent_index_dirty,
            // Clone the cache contents, not the lock
            metadata_basetype_cache: RwLock::new(
                self.metadata_basetype_cache.read().unwrap().clone(),
            ),
        }
    }
}

impl SymbolIndex {
    /// Create a new empty index.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add symbols and filters from an extraction result.
    pub fn add_extraction_result(
        &mut self,
        file: FileId,
        result: crate::hir::symbols::ExtractionResult,
    ) {
        // Add symbols
        self.add_file(file, result.symbols);

        // Add scope filters (from `filter @X;` statements)
        for (scope, metadata_names) in result.scope_filters {
            for name in metadata_names {
                self.add_scope_filter(scope.clone(), name);
            }
        }

        // Add import filters (from bracket syntax `import X::*[@Filter]`)
        for (import_qname, metadata_names) in result.import_filters {
            for name in metadata_names {
                self.import_filters
                    .entry(import_qname.clone())
                    .or_default()
                    .push(Arc::from(name));
            }
        }
    }

    /// Add symbols from a file to the index.
    pub fn add_file(&mut self, file: FileId, symbols: Vec<HirSymbol>) {
        // Remove existing symbols from this file first
        self.remove_file(file);

        // Mark parent index as dirty (need to rebuild by_parent_scope)
        self.parent_index_dirty = true;

        // Clear visibility maps for affected scopes (they'll be rebuilt lazily)
        // We don't clear ALL visibility maps - just mark that parent index needs rebuild

        let mut file_indices = Vec::with_capacity(symbols.len());

        for symbol in symbols {
            let idx = self.symbols.len();

            // Index by qualified name
            self.by_qualified_name
                .insert(symbol.qualified_name.clone(), idx);

            // Index by simple name
            self.by_simple_name
                .entry(symbol.name.clone())
                .or_default()
                .push(idx);

            // Index by short name (e.g., <kg> for "kilogram")
            if let Some(ref short) = symbol.short_name {
                self.by_short_name
                    .entry(short.clone())
                    .or_default()
                    .push(idx);
            }

            // Track definitions separately
            if symbol.kind.is_definition() {
                self.definitions.insert(symbol.qualified_name.clone(), idx);
            }

            // Track for file index
            file_indices.push(idx);

            // Store the symbol
            self.symbols.push(symbol);
        }

        // Index by file
        self.by_file.insert(file, file_indices);
    }

    /// Add a single symbol to the index (not associated with any file).
    /// Useful for symbols imported from models (XMI/JSON-LD).
    pub fn add_symbol(&mut self, symbol: HirSymbol) {
        // Mark parent index as dirty
        self.parent_index_dirty = true;

        let idx = self.symbols.len();

        // Index by qualified name
        self.by_qualified_name
            .insert(symbol.qualified_name.clone(), idx);

        // Index by simple name
        self.by_simple_name
            .entry(symbol.name.clone())
            .or_default()
            .push(idx);

        // Index by short name (e.g., <kg> for "kilogram")
        if let Some(ref short) = symbol.short_name {
            self.by_short_name
                .entry(short.clone())
                .or_default()
                .push(idx);
        }

        // Track definitions separately
        if symbol.kind.is_definition() {
            self.definitions.insert(symbol.qualified_name.clone(), idx);
        }

        // Store the symbol
        self.symbols.push(symbol);
    }

    /// Add a filter for a scope. Elements imported into this scope must have
    /// the specified metadata to be visible.
    pub fn add_scope_filter(
        &mut self,
        scope: impl Into<Arc<str>>,
        metadata_name: impl Into<Arc<str>>,
    ) {
        self.parent_index_dirty = true;
        self.scope_filters
            .entry(scope.into())
            .or_default()
            .push(metadata_name.into());
    }

    /// Remove all symbols from a file.
    ///
    /// Note: This marks indices as invalid but doesn't compact the symbols vec
    /// to avoid invalidating other indices. For a full cleanup, rebuild the index.
    pub fn remove_file(&mut self, file: FileId) {
        if let Some(indices) = self.by_file.remove(&file) {
            // Mark parent index as dirty
            self.parent_index_dirty = true;

            // Clear metadata baseType cache since definitions might have changed
            self.metadata_basetype_cache.write().unwrap().clear();

            for &idx in &indices {
                if let Some(symbol) = self.symbols.get(idx) {
                    let qname = symbol.qualified_name.clone();
                    let sname = symbol.name.clone();
                    let short = symbol.short_name.clone();

                    self.by_qualified_name.shift_remove(&qname);
                    self.definitions.remove(&qname);

                    // Clear visibility map for this scope (will be rebuilt lazily)
                    self.visibility_map.remove(&qname);

                    // Remove from simple name index
                    if let Some(list) = self.by_simple_name.get_mut(&sname) {
                        list.retain(|&i| i != idx);
                        if list.is_empty() {
                            self.by_simple_name.remove(&sname);
                        }
                    }

                    // Remove from short name index
                    if let Some(short_name) = short {
                        if let Some(list) = self.by_short_name.get_mut(&short_name) {
                            list.retain(|&i| i != idx);
                            if list.is_empty() {
                                self.by_short_name.remove(&short_name);
                            }
                        }
                    }
                }
            }
            // Note: We don't remove from self.symbols to preserve indices
            // A rebuild would be needed for true cleanup
        }
    }

    /// Look up a symbol by qualified name.
    pub fn lookup_qualified(&self, name: &str) -> Option<&HirSymbol> {
        self.by_qualified_name
            .get(name)
            .and_then(|&idx| self.symbols.get(idx))
    }

    /// Look up a symbol by qualified name (mutable).
    pub fn lookup_qualified_mut(&mut self, name: &str) -> Option<&mut HirSymbol> {
        self.by_qualified_name
            .get(name)
            .copied()
            .and_then(move |idx| self.symbols.get_mut(idx))
    }

    /// Apply a function to all symbols (mutable).
    ///
    /// Used to update symbol properties like element_id after loading metadata.
    pub fn update_all_symbols<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirSymbol),
    {
        for symbol in &mut self.symbols {
            f(symbol);
        }
    }

    /// Look up all symbols with a simple name (also checks short names/aliases).
    pub fn lookup_simple(&self, name: &str) -> Vec<&HirSymbol> {
        let mut results = Vec::new();

        // Check by simple name
        if let Some(indices) = self.by_simple_name.get(name) {
            for &idx in indices {
                if let Some(sym) = self.symbols.get(idx) {
                    results.push(sym);
                }
            }
        }

        // Also check by short name (aliases like <kg> for "kilogram")
        if let Some(indices) = self.by_short_name.get(name) {
            for &idx in indices {
                if let Some(sym) = self.symbols.get(idx) {
                    // Avoid duplicates if name == short_name
                    if !results
                        .iter()
                        .any(|s| Arc::ptr_eq(&s.qualified_name, &sym.qualified_name))
                    {
                        results.push(sym);
                    }
                }
            }
        }

        results
    }

    /// Look up all symbols with a short name only.
    pub fn lookup_by_short_name(&self, name: &str) -> Vec<&HirSymbol> {
        self.by_short_name
            .get(name)
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&idx| self.symbols.get(idx))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get the cached baseType for a SemanticMetadata annotation (e.g., "systemdd" -> "SysDD").
    /// Returns None if the annotation doesn't resolve to a SemanticMetadata with baseType.
    /// Uses interior mutability to lazily populate the cache.
    pub fn get_metadata_basetype(&self, annotation_name: &str) -> Option<Arc<str>> {
        // Check cache first (read lock)
        {
            let cache = self.metadata_basetype_cache.read().unwrap();
            if let Some(cached) = cache.get(annotation_name) {
                return cached.clone();
            }
        }

        // Not in cache - compute it
        let result = self.compute_metadata_basetype(annotation_name);

        // Store in cache (write lock, even if None to avoid repeated lookups)
        self.metadata_basetype_cache
            .write()
            .unwrap()
            .insert(Arc::from(annotation_name), result.clone());

        result
    }

    /// Compute the baseType for a SemanticMetadata annotation (internal helper).
    fn compute_metadata_basetype(&self, annotation_name: &str) -> Option<Arc<str>> {
        use crate::hir::symbols::{RefKind, SymbolKind, TypeRefKind};

        // Look up the metadata definition by short name
        let metadata_defs = self.lookup_by_short_name(annotation_name);

        // Find a metadata definition (kind = MetadataDefinition or Other since that's what Metaclass becomes)
        let metadata_def = metadata_defs
            .iter()
            .find(|s| matches!(s.kind, SymbolKind::MetadataDefinition | SymbolKind::Other))?;

        // Look for "baseType" feature in this metadata definition
        let basetype_qname = format!("{}::baseType", metadata_def.qualified_name);
        let basetype_sym = self.lookup_qualified(&basetype_qname)?;

        // Look for the Expression type_ref - this is the `= value` part
        for type_ref in &basetype_sym.type_refs {
            if let TypeRefKind::Simple(tr) = type_ref {
                if matches!(tr.kind, RefKind::Expression) {
                    // This is the value expression (e.g., global_systemsdd)
                    // Try resolved_target first (if already resolved)
                    if let Some(ref resolved) = tr.resolved_target {
                        if let Some(value_sym) = self.lookup_qualified(resolved) {
                            return value_sym.supertypes.first().map(|s| Arc::from(s.as_ref()));
                        }
                    }
                    // Fall back: try to find the target symbol by simple lookup
                    // The target is in the same scope as the metadata definition, so try looking it up
                    // in the parent scope (the package where the metadata def is defined)
                    let parent_scope =
                        Self::parent_scope(&metadata_def.qualified_name).unwrap_or("");
                    let target_qname = format!("{}::{}", parent_scope, tr.target);
                    if let Some(value_sym) = self.lookup_qualified(&target_qname) {
                        return value_sym.supertypes.first().map(|s| Arc::from(s.as_ref()));
                    }
                    // Try direct lookup (might be a fully qualified name)
                    if let Some(value_sym) = self.lookup_qualified(&tr.target) {
                        return value_sym.supertypes.first().map(|s| Arc::from(s.as_ref()));
                    }
                }
            }
        }

        None
    }

    /// Debug: Find which scopes contain a name in their visibility map.
    pub fn debug_find_name_in_visibility(&self, name: &str) -> Vec<String> {
        let mut results = Vec::new();
        for (scope, vis) in &self.visibility_map {
            if vis.lookup_direct(name).is_some() {
                results.push(format!("{}: direct", scope));
            }
            if vis.lookup_import(name).is_some() {
                results.push(format!("{}: import", scope));
            }
        }
        results
    }

    /// Debug: Dump visibility map for a scope.
    pub fn debug_dump_scope(&self, scope: &str) -> String {
        self.visibility_map
            .get(scope)
            .map(|vis| vis.debug_dump())
            .unwrap_or_else(|| format!("No visibility map for scope '{}'", scope))
    }

    /// Look up a definition by qualified name.
    pub fn lookup_definition(&self, name: &str) -> Option<&HirSymbol> {
        self.definitions
            .get(name)
            .and_then(|&idx| self.symbols.get(idx))
    }

    /// Get all symbols in a file.
    pub fn symbols_in_file(&self, file: FileId) -> Vec<&HirSymbol> {
        self.by_file
            .get(&file)
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&idx| self.symbols.get(idx))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get all definitions in the index.
    pub fn all_definitions(&self) -> impl Iterator<Item = &HirSymbol> {
        self.definitions
            .values()
            .filter_map(|&idx| self.symbols.get(idx))
    }

    /// Get all symbols in the index.
    pub fn all_symbols(&self) -> impl Iterator<Item = &HirSymbol> {
        self.by_qualified_name
            .values()
            .filter_map(|&idx| self.symbols.get(idx))
    }

    /// Update symbols in the index using a closure.
    /// The closure is called for each symbol and can modify it in place.
    pub fn update_symbols<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirSymbol),
    {
        for &idx in self.by_qualified_name.values() {
            if let Some(symbol) = self.symbols.get_mut(idx) {
                f(symbol);
            }
        }
    }

    /// Get the total number of symbols.
    pub fn len(&self) -> usize {
        self.by_qualified_name.len()
    }

    /// Check if the index is empty.
    pub fn is_empty(&self) -> bool {
        self.by_qualified_name.is_empty()
    }

    /// Get number of files indexed.
    pub fn file_count(&self) -> usize {
        self.by_file.len()
    }

    /// Insert a single symbol into the index.
    /// This is a convenience wrapper around add_file for single-symbol insertion.
    pub fn insert(&mut self, symbol: HirSymbol) {
        // Use a dummy file ID for test/debug purposes
        let file = FileId::new(0);
        let idx = self.symbols.len();

        // Index by qualified name
        self.by_qualified_name
            .insert(symbol.qualified_name.clone(), idx);

        // Index by simple name
        self.by_simple_name
            .entry(symbol.name.clone())
            .or_default()
            .push(idx);

        // Index by short name
        if let Some(ref short) = symbol.short_name {
            self.by_short_name
                .entry(short.clone())
                .or_default()
                .push(idx);
        }

        // Track definitions
        if symbol.kind.is_definition() {
            self.definitions.insert(symbol.qualified_name.clone(), idx);
        }

        // Track for file index
        self.by_file.entry(file).or_default().push(idx);

        // Store the symbol
        self.symbols.push(symbol);

        // Mark parent index as dirty
        self.parent_index_dirty = true;
    }

    /// Get a reference to the visibility maps.
    pub fn visibility_maps(&self) -> &HashMap<Arc<str>, ScopeVisibility> {
        &self.visibility_map
    }

    /// Mark that parent scope index needs rebuilding.
    /// Mark visibility maps as needing full rebuild.
    /// Call this after external changes that affect symbol visibility.
    pub fn mark_visibility_dirty(&mut self) {
        self.parent_index_dirty = true;
        // Clear visibility map to force rebuild
        self.visibility_map.clear();
    }

    /// Ensure the parent scope index is built (needed for lazy visibility lookups).
    fn ensure_parent_index(&mut self) {
        if !self.parent_index_dirty {
            return;
        }

        self.by_parent_scope.clear();

        // Only include symbols that are still valid (in by_qualified_name)
        // This handles the case where remove_file marks symbols as invalid
        // but doesn't remove them from the symbols vec
        for (idx, symbol) in self.symbols.iter().enumerate() {
            // Skip symbols that have been removed (not in by_qualified_name lookup)
            if !self.by_qualified_name.contains_key(&symbol.qualified_name) {
                continue;
            }

            let parent_scope: Arc<str> = Self::parent_scope(&symbol.qualified_name)
                .map(Arc::from)
                .unwrap_or_else(|| Arc::from(""));

            self.by_parent_scope
                .entry(parent_scope)
                .or_default()
                .push(idx);
        }

        self.parent_index_dirty = false;
    }

    /// Update visibility maps incrementally for symbols in specific files.
    /// Only rebuild visibility for affected scopes, not the entire workspace.
    pub fn update_visibility_for_files(&mut self, files: &[FileId]) {
        // Ensure parent index is built
        self.ensure_parent_index();

        // Collect scopes that need rebuilding
        let mut scopes_to_rebuild: HashSet<Arc<str>> = HashSet::new();

        for file in files {
            if let Some(indices) = self.by_file.get(file).cloned() {
                for idx in indices {
                    if let Some(symbol) = self.symbols.get(idx) {
                        // This symbol's scope needs rebuilding
                        scopes_to_rebuild.insert(symbol.qualified_name.clone());

                        // Parent scope needs rebuilding
                        let parent: Arc<str> = Self::parent_scope(&symbol.qualified_name)
                            .map(Arc::from)
                            .unwrap_or_else(|| Arc::from(""));
                        scopes_to_rebuild.insert(parent);
                    }
                }
            }
        }

        // Rebuild only the affected scopes
        for scope in scopes_to_rebuild {
            self.build_visibility_for_scope(&scope);
        }
    }

    // ========================================================================
    // VISIBILITY MAP CONSTRUCTION
    // ========================================================================

    /// Ensure visibility maps are up-to-date, rebuilding ALL if needed.
    /// Use this for initial load / full resolution.
    pub fn ensure_visibility_maps(&mut self) {
        // Build parent index first
        self.ensure_parent_index();

        // If visibility maps are empty, do a full build
        if self.visibility_map.is_empty() {
            self.build_visibility_maps();
        }
    }

    /// Resolve all type references in all symbols.
    ///
    /// This is called after visibility maps are built to fill in `resolved_target`
    /// on all TypeRefs. This is the "semantic resolution pass" that pre-computes
    /// what each type reference points to.
    ///
    /// Feature chains (like `takePicture.focus`) are now preserved explicitly
    /// as TypeRefKind::Chain from the parser. Simple refs use TypeRefKind::Simple.
    pub fn resolve_all_type_refs(&mut self) {
        use crate::hir::symbols::TypeRefKind;

        // Ensure visibility maps are built first
        self.ensure_visibility_maps();

        // Memoization cache for scope walk results: (name, starting_scope) -> resolved_qname
        // This avoids re-resolving the same name from the same scope multiple times
        let mut resolution_cache: ResolutionCache = HashMap::new();

        // Two-pass resolution to handle dependencies:
        // Pass 1: Resolve simple refs and chain first-parts (they don't depend on other refs)
        // Pass 2: Resolve chain subsequent parts (they depend on the first part's resolved type)

        use std::rc::Rc;

        // Collect work items, separating first-parts from subsequent chain parts
        // Each item: (sym_idx, trk_idx, part_idx, target, chain_context, ref_kind)
        type WorkItem = (
            SymbolIdx,
            usize,
            usize,
            Arc<str>,
            Option<(Rc<Vec<Arc<str>>>, usize)>,
            RefKind,
        );
        let mut pass1_work: Vec<WorkItem> = Vec::new();
        let mut pass2_work: Vec<WorkItem> = Vec::new();

        for (sym_idx, sym) in self.symbols.iter().enumerate() {
            for (trk_idx, trk) in sym.type_refs.iter().enumerate() {
                match trk {
                    TypeRefKind::Simple(tr) => {
                        // Simple refs go in pass 1
                        pass1_work.push((sym_idx, trk_idx, 0, tr.target.clone(), None, tr.kind));
                    }
                    TypeRefKind::Chain(chain) => {
                        let chain_parts: Rc<Vec<Arc<str>>> =
                            Rc::new(chain.parts.iter().map(|p| p.target.clone()).collect());
                        for (part_idx, part) in chain.parts.iter().enumerate() {
                            let item = (
                                sym_idx,
                                trk_idx,
                                part_idx,
                                part.target.clone(),
                                Some((Rc::clone(&chain_parts), part_idx)),
                                part.kind,
                            );
                            if part_idx == 0 {
                                // First part of chain - pass 1
                                pass1_work.push(item);
                            } else {
                                // Subsequent parts - pass 2 (depend on first part's type)
                                pass2_work.push(item);
                            }
                        }
                    }
                }
            }
        }

        // Pass 1: Resolve simple refs and chain first-parts
        for (sym_idx, trk_idx, part_idx, target, chain_context, ref_kind) in pass1_work {
            let symbol_qname = self.symbols[sym_idx].qualified_name.clone();

            // For Redefines refs, try context resolution FIRST before normal scope walk.
            // This handles cases like `requirement X :>> X` where X redefines a member
            // from the parent/satisfy context, not itself in the current scope.
            let mut resolved = if ref_kind == RefKind::Redefines {
                self.resolve_redefines_in_context(&symbol_qname, &target)
            } else {
                None
            };

            // If context resolution didn't find anything (or wasn't a Redefines), try normal resolution
            if resolved.is_none() {
                resolved = self.resolve_type_ref_cached(
                    &symbol_qname,
                    &target,
                    &chain_context,
                    &mut resolution_cache,
                );
            }

            // For unresolved Redefines refs (when context resolution was skipped or failed),
            // try one more time with context resolution as fallback
            if resolved.is_none() && ref_kind == RefKind::Redefines {
                resolved = self.resolve_redefines_in_context(&symbol_qname, &target);
            }

            if let Some(trk) = self.symbols[sym_idx].type_refs.get_mut(trk_idx) {
                match trk {
                    TypeRefKind::Simple(tr) => {
                        tr.resolved_target = resolved;
                    }
                    TypeRefKind::Chain(chain) => {
                        if let Some(part) = chain.parts.get_mut(part_idx) {
                            part.resolved_target = resolved;
                        }
                    }
                }
            }
        }

        // Pass 2: Resolve chain subsequent parts (can now use resolved types from pass 1)
        for (sym_idx, trk_idx, part_idx, target, chain_context, _ref_kind) in pass2_work {
            let symbol_qname = self.symbols[sym_idx].qualified_name.clone();
            let resolved = self.resolve_type_ref_cached(
                &symbol_qname,
                &target,
                &chain_context,
                &mut resolution_cache,
            );

            if let Some(TypeRefKind::Chain(chain)) =
                self.symbols[sym_idx].type_refs.get_mut(trk_idx)
            {
                if let Some(part) = chain.parts.get_mut(part_idx) {
                    part.resolved_target = resolved;
                }
            }
        }
    }

    /// Resolve type references only for symbols in specific files.
    /// This is used for incremental updates to avoid re-resolving the entire workspace.
    pub fn resolve_type_refs_for_files(&mut self, files: &[FileId]) {
        use crate::hir::symbols::TypeRefKind;

        // Ensure visibility maps are built first
        self.ensure_visibility_maps();

        // Memoization cache for scope walk results
        let mut resolution_cache: ResolutionCache = HashMap::new();

        // Collect symbol indices for the specified files
        let symbol_indices: Vec<SymbolIdx> = files
            .iter()
            .filter_map(|file| self.by_file.get(file))
            .flat_map(|indices| indices.iter().copied())
            .collect();

        use std::rc::Rc;

        // Collect work items for these symbols only
        type WorkItem = (
            SymbolIdx,
            usize,
            usize,
            Arc<str>,
            Option<(Rc<Vec<Arc<str>>>, usize)>,
            RefKind,
        );
        let mut pass1_work: Vec<WorkItem> = Vec::new();
        let mut pass2_work: Vec<WorkItem> = Vec::new();

        for &sym_idx in &symbol_indices {
            if let Some(sym) = self.symbols.get(sym_idx) {
                for (trk_idx, trk) in sym.type_refs.iter().enumerate() {
                    match trk {
                        TypeRefKind::Simple(tr) => {
                            pass1_work.push((
                                sym_idx,
                                trk_idx,
                                0,
                                tr.target.clone(),
                                None,
                                tr.kind,
                            ));
                        }
                        TypeRefKind::Chain(chain) => {
                            let chain_parts: Rc<Vec<Arc<str>>> =
                                Rc::new(chain.parts.iter().map(|p| p.target.clone()).collect());
                            for (part_idx, part) in chain.parts.iter().enumerate() {
                                let item = (
                                    sym_idx,
                                    trk_idx,
                                    part_idx,
                                    part.target.clone(),
                                    Some((Rc::clone(&chain_parts), part_idx)),
                                    part.kind,
                                );
                                if part_idx == 0 {
                                    pass1_work.push(item);
                                } else {
                                    pass2_work.push(item);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Pass 1: Resolve simple refs and chain first-parts
        for (sym_idx, trk_idx, part_idx, target, chain_context, ref_kind) in pass1_work {
            let symbol_qname = self.symbols[sym_idx].qualified_name.clone();
            let mut resolved = self.resolve_type_ref_cached(
                &symbol_qname,
                &target,
                &chain_context,
                &mut resolution_cache,
            );

            if resolved.is_none() && ref_kind == RefKind::Redefines {
                resolved = self.resolve_redefines_in_context(&symbol_qname, &target);
            }

            if let Some(trk) = self.symbols[sym_idx].type_refs.get_mut(trk_idx) {
                match trk {
                    TypeRefKind::Simple(tr) => {
                        tr.resolved_target = resolved;
                    }
                    TypeRefKind::Chain(chain) => {
                        if let Some(part) = chain.parts.get_mut(part_idx) {
                            part.resolved_target = resolved;
                        }
                    }
                }
            }
        }

        // Pass 2: Resolve chain subsequent parts
        for (sym_idx, trk_idx, part_idx, target, chain_context, _ref_kind) in pass2_work {
            let symbol_qname = self.symbols[sym_idx].qualified_name.clone();
            let resolved = self.resolve_type_ref_cached(
                &symbol_qname,
                &target,
                &chain_context,
                &mut resolution_cache,
            );

            if let Some(TypeRefKind::Chain(chain)) =
                self.symbols[sym_idx].type_refs.get_mut(trk_idx)
            {
                if let Some(part) = chain.parts.get_mut(part_idx) {
                    part.resolved_target = resolved;
                }
            }
        }
    }

    /// Resolve a single type reference within a symbol's scope (with caching).
    ///
    /// For regular references: uses lexical scoping + imports
    /// For feature chain members: resolves through type membership
    fn resolve_type_ref_cached(
        &self,
        containing_symbol: &str,
        target: &str,
        chain_context: &Option<(std::rc::Rc<Vec<Arc<str>>>, usize)>,
        cache: &mut ResolutionCache,
    ) -> Option<Arc<str>> {
        // Get the scope for resolution
        // For import symbols (e.g., "Pkg::import:Target" or "import:Target"), use the parent scope
        let scope = if let Some(import_pos) = containing_symbol.find("::import:") {
            &containing_symbol[..import_pos]
        } else if containing_symbol.starts_with("import:") {
            // Root-level import - use empty scope
            ""
        } else {
            containing_symbol
        };

        // Check if this is a feature chain member (index > 0)
        // Chain members can't be cached the same way (they depend on the full chain)
        if let Some((chain_parts, chain_idx)) = chain_context {
            if *chain_idx > 0 {
                return self.resolve_feature_chain_member(
                    scope,
                    chain_parts.as_slice(),
                    *chain_idx,
                );
            }
        }

        // Note: Anonymous redefining symbols (like `<:>>speedSensor#N>`) are now registered
        // in visibility maps under their base name during build_visibility_maps().
        // The regular resolve_with_scope_walk will find them via visibility map lookup.

        // For simple references, use cache
        let cache_key = (Arc::from(target), Arc::from(scope));
        if let Some(cached) = cache.get(&cache_key) {
            return cached.clone();
        }

        // Not in cache - do the actual resolution using visibility maps
        // NOTE: We intentionally do NOT fall back to lookup_qualified here.
        // If the name isn't visible through imports or direct definitions,
        // it should remain unresolved (the user removed the import).
        let result = self
            .resolve_with_scope_walk(target, scope)
            .map(|sym| sym.qualified_name.clone());

        // Store in cache
        cache.insert(cache_key, result.clone());
        result
    }

    /// Follow a typing chain to find the actual type definition.
    ///
    /// For example, if we have:
    ///   action takePicture : TakePicture;  // usage typed by definition
    ///   action a :> takePicture;           // usage subsets usage
    ///
    /// When resolving from `a`, we need to follow: a -> takePicture -> TakePicture
    ///
    /// IMPORTANT: If the input symbol is already a definition, return it immediately.
    /// We only follow the chain for usages, not for definition inheritance.
    fn follow_typing_chain(&self, sym: &HirSymbol, scope: &str) -> Arc<str> {
        // If the input is already a definition, return it - don't follow inheritance
        if sym.kind.is_definition() {
            return sym.qualified_name.clone();
        }

        let mut current_qname = sym.qualified_name.clone();
        let mut visited = std::collections::HashSet::new();
        visited.insert(current_qname.clone());

        // Keep following supertypes until we find a definition or loop
        while let Some(current) = self.lookup_qualified(&current_qname) {
            let Some(type_name) = current.supertypes.first() else {
                // No supertypes
                break;
            };

            let type_resolver = Resolver::new(self).with_scope(scope);
            let ResolveResult::Found(type_sym) = type_resolver.resolve(type_name) else {
                // Can't resolve further, use what we have
                break;
            };

            if visited.contains(&type_sym.qualified_name) {
                // Cycle detected, stop here
                break;
            }
            visited.insert(type_sym.qualified_name.clone());

            // If this symbol is a definition, return it
            if type_sym.kind.is_definition() {
                return type_sym.qualified_name.clone();
            }

            // Otherwise continue following
            current_qname = type_sym.qualified_name.clone();
        }

        current_qname
    }

    /// Resolve a feature chain member (e.g., `focus` in `takePicture.focus`).
    ///
    /// Chain resolution follows rust-analyzer's approach:
    /// 1. Resolve first part using full lexical scoping (walks up parent scopes)
    /// 2. Get that symbol's type definition
    /// 3. Resolve subsequent parts as members of that type
    /// 4. For each member, follow its type to resolve the next part
    ///
    /// IMPORTANT: SysML usages can have nested members defined directly within them,
    /// even when they have a type annotation. We must check the usage's own scope
    /// BEFORE falling back to its type definition.
    pub fn resolve_feature_chain_member(
        &self,
        scope: &str,
        chain_parts: &[Arc<str>],
        chain_idx: usize,
    ) -> Option<Arc<str>> {
        if chain_idx == 0 || chain_parts.is_empty() {
            return None;
        }

        // Step 1: Resolve the first part using full lexical scoping
        // Anonymous redefining symbols are registered in visibility maps under their base name,
        // so resolve_with_scope_walk will find them automatically.
        let first_part = &chain_parts[0];
        let first_sym = self.resolve_with_scope_walk(first_part, scope)?;

        // Track the current symbol (for checking nested members) and its type scope (for inheritance)
        let mut current_sym_qname = first_sym.qualified_name.clone();
        let mut current_type_scope = self.get_member_lookup_scope(&first_sym, scope);

        // Step 2: Walk through the chain, resolving each part
        for (i, part) in chain_parts.iter().enumerate().take(chain_idx + 1).skip(1) {
            // SysML Pattern: Usages can have nested members defined directly within them.
            // For example: part differential:Differential { port leftDiffPort:DiffPort; }
            // Here `leftDiffPort` is a member of the usage, not the Differential definition.
            //
            // Strategy: First try to find member in the symbol's own scope (nested members),
            // then fall back to the type scope (inherited members).

            let member_sym = {
                // Try 1: Look for nested member directly in the current symbol
                if let Some(sym) = self.find_member_in_scope(&current_sym_qname, part) {
                    sym
                } else if current_sym_qname != current_type_scope {
                    // Try 2: Look in the type scope (inherited members)
                    self.find_member_in_scope(&current_type_scope, part)?
                } else {
                    return None;
                }
            };

            if i == chain_idx {
                // This is the target - return it
                return Some(member_sym.qualified_name.clone());
            }

            // Update for next iteration: track both the symbol and its type scope
            current_sym_qname = member_sym.qualified_name.clone();
            current_type_scope = self.get_member_lookup_scope(&member_sym, scope);
        }

        None
    }

    /// Resolve a name using visibility maps (which already handle scope hierarchy).
    ///
    /// NOTE: Resolver::resolve() already walks up the scope hierarchy internally,
    /// so we just need to call it once with the starting scope.
    fn resolve_with_scope_walk(&self, name: &str, starting_scope: &str) -> Option<HirSymbol> {
        let resolver = Resolver::new(self).with_scope(starting_scope);
        match resolver.resolve(name) {
            ResolveResult::Found(sym) => Some(sym),
            _ => None,
        }
    }

    /// Get the scope to use for member lookups on a symbol.
    /// If the symbol has a type, returns the type's qualified name.
    /// Otherwise, returns the symbol's own qualified name (for nested members).
    ///
    /// Checks the symbol's resolved type_refs first (if available), then falls back
    /// to resolving the supertype name. This ensures we use the same type resolution
    /// that was computed for the symbol's own type annotation.
    ///
    /// For interface endpoints with `::>` (References), we follow the reference to find
    /// where members actually live. E.g., `connect lugNutPort ::> wheel1.lugNutCompositePort`
    /// means members of `lugNutPort` are actually in `wheel1.lugNutCompositePort`.
    fn get_member_lookup_scope(&self, sym: &HirSymbol, resolution_scope: &str) -> Arc<str> {
        // First, check if the symbol has a resolved type_ref (from its : TypeAnnotation)
        // This is more accurate than re-resolving the name because it uses the same
        // resolution context that was used for the symbol's own typing.
        for trk in &sym.type_refs {
            for tr in trk.as_refs() {
                // Look for typed-by refs with resolved targets
                if tr.kind == crate::hir::symbols::RefKind::TypedBy {
                    if let Some(ref resolved) = tr.resolved_target {
                        // Got a pre-resolved type - use it
                        if let Some(type_sym) = self.lookup_qualified(resolved) {
                            if type_sym.kind.is_definition() {
                                return type_sym.qualified_name.clone();
                            }
                            // If it's a usage, follow the typing chain
                            return self.follow_typing_chain(type_sym, resolution_scope);
                        }
                    }
                }
            }
        }

        // For interface endpoints: check for ::> (References) relationships
        // These indicate the endpoint is a proxy for another scope where members live.
        // E.g., `connect lugNutPort ::> wheel1.lugNutCompositePort` means members
        // of lugNutPort are actually defined in wheel1.lugNutCompositePort.
        for trk in &sym.type_refs {
            match trk {
                crate::hir::TypeRefKind::Chain(chain) => {
                    // Check if this is a References chain
                    if let Some(first_part) = chain.parts.first() {
                        if first_part.kind == crate::hir::symbols::RefKind::References {
                            // This is a ::> chain - follow the last resolved part
                            if let Some(last_part) = chain.parts.last() {
                                if let Some(ref resolved) = last_part.resolved_target {
                                    return resolved.clone();
                                }
                            }
                        }
                    }
                }
                crate::hir::TypeRefKind::Simple(tr) => {
                    // Also handle simple References (non-chain)
                    if tr.kind == crate::hir::symbols::RefKind::References {
                        if let Some(ref resolved) = tr.resolved_target {
                            return resolved.clone();
                        }
                    }
                }
            }
        }

        // Fallback: resolve the supertype name (for symbols without resolved type_refs yet)
        if let Some(type_name) = sym.supertypes.first() {
            let sym_scope = Self::parent_scope(&sym.qualified_name).unwrap_or("");

            if let Some(type_sym) = self.resolve_with_scope_walk(type_name, sym_scope) {
                if type_sym.kind.is_usage() {
                    return type_sym.qualified_name.clone();
                }
                return self.follow_typing_chain(&type_sym, resolution_scope);
            }

            if let Some(type_sym) = self.lookup_qualified(type_name) {
                if type_sym.kind.is_usage() {
                    return type_sym.qualified_name.clone();
                }
                return self.follow_typing_chain(type_sym, resolution_scope);
            }
        }

        // No type - use the symbol itself as the scope for nested members
        sym.qualified_name.clone()
    }

    /// Find a member within a type scope.
    /// Tries visibility map lookup first, then searches inherited members from supertypes.
    pub fn find_member_in_scope(&self, type_scope: &str, member_name: &str) -> Option<HirSymbol> {
        let mut visited = HashSet::new();
        self.find_member_in_scope_internal(type_scope, member_name, &mut visited)
    }

    /// Internal implementation with visited tracking to prevent infinite loops.
    fn find_member_in_scope_internal(
        &self,
        type_scope: &str,
        member_name: &str,
        visited: &mut HashSet<String>,
    ) -> Option<HirSymbol> {
        // Check for cycles - if we've already visited this scope, skip it
        if !visited.insert(type_scope.to_string()) {
            return None;
        }

        // Check visibility map for the type scope
        // This includes direct children and inherited members from imports
        if let Some(vis) = self.visibility_for_scope(type_scope) {
            if let Some(qname) = vis.lookup(member_name) {
                if let Some(sym) = self.lookup_qualified(qname) {
                    return Some(sym.clone());
                }
            }
        }

        // Not found directly - recursively search supertypes
        if let Some(scope_sym) = self.lookup_qualified(type_scope) {
            for supertype in &scope_sym.supertypes {
                // Resolve the supertype name to a qualified name
                // First try with the current scope
                let resolver = Resolver::new(self).with_scope(type_scope.to_string());
                let resolved = if let ResolveResult::Found(super_sym) = resolver.resolve(supertype)
                {
                    Some(super_sym)
                } else {
                    // If not found, try resolving from parent scopes
                    // This handles cases like `redefines monitoredOccurrence` where the
                    // redefined feature is in an ancestor's scope, not the current one
                    self.try_resolve_in_parent_scopes(type_scope, supertype)
                };

                if let Some(super_sym) = resolved {
                    if let Some(found) = self.find_member_in_scope_internal(
                        &super_sym.qualified_name,
                        member_name,
                        visited,
                    ) {
                        return Some(found);
                    }
                }
            }
        }

        None
    }

    /// Try to resolve a name by walking up parent scopes.
    /// This handles nested redefinitions where the redefined symbol is in an ancestor's scope.
    /// Uses visibility maps directly instead of creating Resolver objects for each level.
    ///
    /// Optimized to scan the scope string once, working backwards to find each parent.
    fn try_resolve_in_parent_scopes(&self, start_scope: &str, name: &str) -> Option<HirSymbol> {
        let bytes = start_scope.as_bytes();
        let mut end = bytes.len();

        while end > 1 {
            // Find the previous `::` separator, accounting for `<...>` brackets
            let mut depth = 0i32;
            let mut sep_pos = None;
            let mut i = end;

            while i > 1 {
                i -= 1;
                match bytes[i] {
                    b'>' => depth += 1,
                    b'<' => depth -= 1,
                    b':' if depth == 0 && i > 0 && bytes[i - 1] == b':' => {
                        sep_pos = Some(i - 1);
                        break;
                    }
                    _ => {}
                }
            }

            let parent_end = sep_pos?;
            let parent = &start_scope[..parent_end];

            // Check visibility map for this parent scope
            if let Some(vis) = self.visibility_map.get(parent) {
                if let Some(qname) = vis.lookup(name) {
                    if let Some(sym) = self.lookup_qualified(qname) {
                        return Some(sym.clone());
                    }
                }
            }

            end = parent_end;
        }
        None
    }

    /// Find a member within a type scope by short name.
    /// This is used for short name references like `:>> 'member'`.
    pub fn find_member_by_short_name_in_scope(
        &self,
        type_scope: &str,
        short_name: &str,
    ) -> Option<HirSymbol> {
        // Check visibility map for the type scope and look for symbols with matching short name
        if let Some(vis) = self.visibility_for_scope(type_scope) {
            // Check direct definitions
            for (_name, qname) in vis.direct_defs() {
                if let Some(sym) = self.lookup_qualified(qname) {
                    if sym.short_name.as_ref().map(|s| s.as_ref()) == Some(short_name) {
                        return Some(sym.clone());
                    }
                }
            }
            // Check imports
            for (_name, qname) in vis.imports() {
                if let Some(sym) = self.lookup_qualified(qname) {
                    if sym.short_name.as_ref().map(|s| s.as_ref()) == Some(short_name) {
                        return Some(sym.clone());
                    }
                }
            }
        }

        None
    }

    /// Resolve a Redefines ref by looking at the parent's satisfy/perform context,
    /// or by looking in the parent's typing context (inheritance).
    ///
    /// For `satisfy Req by Subject { :>> reqMember; }`, the reqMember should resolve
    /// to a member of Req (the satisfied requirement).
    ///
    /// For `part vehicle : Vehicle { perform redefines providePower; }`, the providePower
    /// should resolve to Vehicle::providePower (inherited from the typed-by relationship).
    fn resolve_redefines_in_context(
        &self,
        symbol_qname: &str,
        member_name: &str,
    ) -> Option<Arc<str>> {
        // Get the parent scope - be careful with anonymous scopes like `<perform:...>`
        // For `TestPkg::vehicle_b::<perform:ActionTree::providePower#2@L9>`, parent is `TestPkg::vehicle_b`
        let parent_qname = Self::parent_scope(symbol_qname)?;

        // Look up the parent symbol
        let parent = self.lookup_qualified(parent_qname)?;

        // First, check the parent's type_refs for satisfy context
        if let Some(result) = self.check_satisfy_context(parent, member_name) {
            return Some(result);
        }

        // Check siblings and descendants using indexed lookup (O(1) for scope, O(children) for iteration)
        // This handles cases where the parser places the satisfy relationship on a nested symbol
        let parent_arc: Arc<str> = Arc::from(parent_qname);
        if let Some(sibling_indices) = self.by_parent_scope.get(&parent_arc) {
            for &idx in sibling_indices {
                if let Some(sym) = self.symbols.get(idx) {
                    if sym.qualified_name.as_ref() != symbol_qname {
                        if let Some(result) = self.check_satisfy_context(sym, member_name) {
                            return Some(result);
                        }
                    }
                }
            }
        }

        // Check the parent's typing relationship (inheritance)
        // For `part vehicle_b : Vehicle { perform redefines providePower; }`
        // The parent (vehicle_b) is typed by Vehicle, so look for providePower in Vehicle
        if let Some(result) = self.resolve_in_parent_type(parent, member_name) {
            return Some(result);
        }

        // Also check grandparent's type (for deeper nesting)
        if let Some(grandparent_qname) = parent_qname.rsplit_once("::").map(|(gp, _)| gp) {
            if let Some(grandparent) = self.lookup_qualified(grandparent_qname) {
                if let Some(result) = self.resolve_in_parent_type(grandparent, member_name) {
                    return Some(result);
                }
            }
        }

        None
    }

    /// Resolve a member name by looking in the symbol's typed-by relationship.
    /// This handles inheritance-based redefines resolution.
    fn resolve_in_parent_type(&self, parent: &HirSymbol, member_name: &str) -> Option<Arc<str>> {
        // Find the parent's type (from TypedBy or Subsets relationships)
        for type_ref_kind in &parent.type_refs {
            let type_ref = match type_ref_kind {
                TypeRefKind::Simple(tr) => tr,
                TypeRefKind::Chain(chain) => {
                    if let Some(part) = chain.parts.first() {
                        part
                    } else {
                        continue;
                    }
                }
            };

            // Look for TypedBy references (: Type)
            if !matches!(type_ref.kind, RefKind::TypedBy | RefKind::Subsets) {
                continue;
            }

            // Try resolved target first, then fall back to resolving the target name
            let type_def = if let Some(resolved) = &type_ref.resolved_target {
                self.lookup_qualified(resolved).cloned()
            } else {
                // Target isn't resolved yet - try to resolve it now using parent's scope
                let parent_scope = parent
                    .qualified_name
                    .rsplit_once("::")
                    .map(|(p, _)| p)
                    .unwrap_or("");
                let resolver = self.resolver_for_scope(parent_scope);
                match resolver.resolve(&type_ref.target) {
                    ResolveResult::Found(sym) => Some(sym),
                    ResolveResult::Ambiguous(syms) => syms.into_iter().next(),
                    ResolveResult::NotFound => self.lookup_qualified(&type_ref.target).cloned(),
                }
            };

            let Some(type_def) = type_def else {
                continue;
            };

            // Look for the member directly in the type's scope
            let member_qname = format!("{}::{}", type_def.qualified_name, member_name);
            if self.lookup_qualified(&member_qname).is_some() {
                return Some(Arc::from(member_qname));
            }

            // Also check the visibility map for inherited members
            if let Some(vis) = self.visibility_for_scope(&type_def.qualified_name) {
                if let Some(qname) = vis.lookup(member_name) {
                    if self.lookup_qualified(qname).is_some() {
                        return Some(Arc::from(qname.as_ref()));
                    }
                }
            }
        }

        None
    }

    /// Check a symbol's type_refs for satisfy context and try to resolve member in that context
    fn check_satisfy_context(&self, sym: &HirSymbol, member_name: &str) -> Option<Arc<str>> {
        for type_ref_kind in &sym.type_refs {
            let type_ref = match type_ref_kind {
                TypeRefKind::Simple(tr) => tr,
                TypeRefKind::Chain(chain) => {
                    // For chains, use the first part if it has a resolved target
                    if let Some(part) = chain.parts.first() {
                        part
                    } else {
                        continue;
                    }
                }
            };

            // Skip refs without resolved targets
            let Some(resolved_qname) = type_ref.resolved_target.as_ref() else {
                continue;
            };

            // Look for satisfied requirement - can be Subsets (from :>) or Other (from satisfy)
            // The satisfy relationship creates a ref to the requirement being satisfied
            // We check the target's kind rather than the ref kind to be more robust
            let Some(target_type) = self.lookup_qualified(resolved_qname) else {
                continue;
            };

            // Check if target is a requirement-like definition
            if matches!(
                target_type.kind,
                SymbolKind::RequirementDefinition
                    | SymbolKind::RequirementUsage
                    | SymbolKind::ConstraintDefinition
                    | SymbolKind::ConstraintUsage
            ) {
                // Look for the member in the requirement's scope
                let member_qname = format!("{}::{}", resolved_qname, member_name);
                if self.lookup_qualified(&member_qname).is_some() {
                    return Some(Arc::from(member_qname));
                }

                // Also check visibility map for inherited members
                if let Some(vis) = self.visibility_for_scope(resolved_qname) {
                    if let Some(qname) = vis.lookup(member_name) {
                        if self.lookup_qualified(qname).is_some() {
                            return Some(Arc::from(qname.as_ref()));
                        }
                    }
                }
            }
        }

        None
    }

    /// Get the visibility map for a scope (if built).
    pub fn visibility_for_scope(&self, scope: &str) -> Option<&ScopeVisibility> {
        self.visibility_map.get(scope)
    }

    /// Build visibility map for a single scope.
    fn build_visibility_for_scope(&mut self, scope: &Arc<str>) {
        let mut vis = ScopeVisibility::new(scope.clone());

        // Add direct children of this scope
        if let Some(child_indices) = self.by_parent_scope.get(scope).cloned() {
            for idx in child_indices {
                if let Some(symbol) = self.symbols.get(idx) {
                    // Skip imports - handle them separately
                    if symbol.kind == SymbolKind::Import {
                        continue;
                    }

                    vis.add_direct(symbol.name.clone(), symbol.qualified_name.clone());

                    if let Some(ref short_name) = symbol.short_name {
                        vis.add_direct(short_name.clone(), symbol.qualified_name.clone());
                    }
                }
            }
        }

        // Process imports in this scope
        self.process_imports_for_scope_lazy(scope, &mut vis);

        // Handle anonymous scope children (promote to grandparent)
        for (parent_scope, indices) in &self.by_parent_scope.clone() {
            if parent_scope.contains('<') {
                if let Some(grandparent) = Self::parent_scope(parent_scope) {
                    if grandparent == scope.as_ref() {
                        for &idx in indices {
                            if let Some(symbol) = self.symbols.get(idx) {
                                if symbol.kind != SymbolKind::Import {
                                    vis.add_direct(
                                        symbol.name.clone(),
                                        symbol.qualified_name.clone(),
                                    );
                                    if let Some(ref short_name) = symbol.short_name {
                                        vis.add_direct(
                                            short_name.clone(),
                                            symbol.qualified_name.clone(),
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        self.visibility_map.insert(scope.clone(), vis);
    }

    /// Process imports for a single scope (used in lazy building).
    fn process_imports_for_scope_lazy(&self, scope: &Arc<str>, vis: &mut ScopeVisibility) {
        // Find import symbols in this scope
        let imports: Vec<_> = self
            .by_parent_scope
            .get(scope)
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&idx| self.symbols.get(idx))
                    .filter(|s| s.kind == SymbolKind::Import)
                    .map(|s| (s.name.clone(), s.qualified_name.clone(), s.is_public))
                    .collect()
            })
            .unwrap_or_default();

        for (import_name, _import_qname, _is_public) in imports {
            let is_wildcard = import_name.ends_with("::*") && !import_name.ends_with("::**");
            let is_recursive = import_name.ends_with("::**");

            let import_target = if is_recursive {
                import_name.trim_end_matches("::**")
            } else {
                import_name.trim_end_matches("::*")
            };

            // Resolve the import target
            let resolved_target = self.resolve_import_target_simple(scope, import_target);

            if is_wildcard || is_recursive {
                // Wildcard import: add all direct children of target
                if let Some(target_children) = self
                    .by_parent_scope
                    .get(&Arc::from(resolved_target.as_str()))
                {
                    for &idx in target_children {
                        if let Some(child_sym) = self.symbols.get(idx) {
                            if child_sym.kind != SymbolKind::Import {
                                vis.add_import(
                                    child_sym.name.clone(),
                                    child_sym.qualified_name.clone(),
                                );
                                if let Some(ref short) = child_sym.short_name {
                                    vis.add_import(short.clone(), child_sym.qualified_name.clone());
                                }
                            }
                        }
                    }
                }
            } else {
                // Single import: add just that symbol
                // The import target may use a short name (e.g., "Pkg::mop" where mop is a short name)
                if let Some(sym) = self.lookup_qualified(&resolved_target) {
                    // Add the symbol's name to visibility
                    vis.add_import(sym.name.clone(), sym.qualified_name.clone());

                    // Also add the short name if importing by short name
                    // e.g., `import Pkg::mop` should make `mop` visible
                    if let Some(ref short_name) = sym.short_name {
                        vis.add_import(short_name.clone(), sym.qualified_name.clone());
                    }

                    // If the import target's last segment differs from the symbol's name,
                    // it was imported by short name - add that name too
                    let import_last_seg =
                        import_target.rsplit("::").next().unwrap_or(import_target);
                    if import_last_seg != sym.name.as_ref() {
                        vis.add_import(Arc::from(import_last_seg), sym.qualified_name.clone());
                    }
                }
            }
        }
    }

    /// Simple import target resolution (used in lazy visibility building).
    /// Handles both regular names and short names in the target.
    fn resolve_import_target_simple(&self, scope: &str, target: &str) -> String {
        // If already qualified, check as-is
        if target.contains("::") && self.by_qualified_name.contains_key(target) {
            return target.to_string();
        }

        // Check if the last segment is a short name
        // e.g., "ParametersOfInterestMetadata::mop" where "mop" is the short name of "MeasureOfPerformance"
        if target.contains("::") {
            if let Some((parent, last_segment)) = target.rsplit_once("::") {
                // Resolve the parent scope
                let parent_qualified = self.resolve_import_target_simple(scope, parent);

                // Check if last_segment is a short name in that scope
                if let Some(children) = self
                    .by_parent_scope
                    .get(&Arc::from(parent_qualified.as_str()))
                {
                    for &idx in children {
                        if let Some(sym) = self.symbols.get(idx) {
                            if sym.short_name.as_ref().map(|s| s.as_ref()) == Some(last_segment) {
                                return sym.qualified_name.to_string();
                            }
                        }
                    }
                }
            }
        }

        // Try relative to scope and parent scopes
        let mut current = scope.to_string();
        loop {
            let candidate = if current.is_empty() {
                target.to_string()
            } else {
                format!("{}::{}", current, target)
            };

            if self.by_qualified_name.contains_key(&candidate as &str) {
                return candidate;
            }

            if let Some(idx) = current.rfind("::") {
                current = current[..idx].to_string();
            } else if !current.is_empty() {
                current = String::new();
            } else {
                break;
            }
        }

        target.to_string()
    }

    /// Build visibility maps for all scopes (full rebuild for initial load).
    ///
    /// This is the main entry point for constructing visibility information.
    /// It performs:
    /// 1. Single-pass scope collection and direct definition grouping
    /// 2. Inheritance propagation (supertypes' members become visible)
    /// 3. Import processing with transitive public re-export handling
    fn build_visibility_maps(&mut self) {
        // First ensure parent index is built
        self.ensure_parent_index();

        // 1. Single pass: collect scopes AND group symbols by parent scope
        // This is O(symbols) instead of O(scopes × symbols)
        self.visibility_map.clear();

        // Pre-create root scope
        self.visibility_map
            .insert(Arc::from(""), ScopeVisibility::new(""));

        for symbol in &self.symbols {
            // Skip symbols that have been removed (not in by_qualified_name lookup)
            if !self.by_qualified_name.contains_key(&symbol.qualified_name) {
                continue;
            }

            // Ensure this symbol's scope exists (for namespace-creating symbols)
            // Include usages too - they can have nested members and need inherited members from their type
            if symbol.kind == SymbolKind::Package
                || symbol.kind.is_definition()
                || symbol.kind.is_usage()
            {
                self.visibility_map
                    .entry(symbol.qualified_name.clone())
                    .or_insert_with(|| ScopeVisibility::new(symbol.qualified_name.clone()));
            }

            // Skip adding import symbols as direct definitions - they're processed separately
            // and shouldn't shadow global packages with the same name
            if symbol.kind == SymbolKind::Import {
                continue;
            }

            // Add symbol to its parent scope's direct definitions
            let parent_scope: Arc<str> = Self::parent_scope(&symbol.qualified_name)
                .map(Arc::from)
                .unwrap_or_else(|| Arc::from(""));

            // Ensure parent scope exists
            let vis = self
                .visibility_map
                .entry(parent_scope.clone())
                .or_insert_with(|| ScopeVisibility::new(parent_scope.clone()));

            vis.add_direct(symbol.name.clone(), symbol.qualified_name.clone());

            // Also register by short_name if available
            if let Some(ref short_name) = symbol.short_name {
                vis.add_direct(short_name.clone(), symbol.qualified_name.clone());
            }

            // Register anonymous redefining symbols under their base name.
            // Pattern: `<:>>speedSensor#77@L789>` should be accessible as `speedSensor`
            // This enables chains like `speedSensor.speedSensorPort.sensedSpeedSent` to resolve
            // through the local redefining symbol rather than the inherited definition.
            if symbol.name.starts_with("<:>>") {
                // Extract base name: `<:>>speedSensor#77@L789>` -> `speedSensor`
                if let Some(hash_pos) = symbol.name.find('#') {
                    let base_name: Arc<str> = Arc::from(&symbol.name[4..hash_pos]);
                    vis.add_direct(base_name, symbol.qualified_name.clone());
                }
            }

            // If the parent scope is anonymous (contains `<` which indicates generated names),
            // also add this symbol to the grandparent scope so it's accessible from siblings.
            // This handles cases like `then action foo { ... }` where `foo` needs to be visible
            // from the enclosing scope, not just from the anonymous succession scope.
            if parent_scope.contains('<') {
                if let Some(grandparent) = Self::parent_scope(&parent_scope) {
                    let grandparent_arc: Arc<str> = Arc::from(grandparent);
                    let gp_vis = self
                        .visibility_map
                        .entry(grandparent_arc.clone())
                        .or_insert_with(|| ScopeVisibility::new(grandparent_arc));
                    gp_vis.add_direct(symbol.name.clone(), symbol.qualified_name.clone());
                    if let Some(ref short_name) = symbol.short_name {
                        gp_vis.add_direct(short_name.clone(), symbol.qualified_name.clone());
                    }
                    // Also register anonymous redefining symbols in grandparent
                    if symbol.name.starts_with("<:>>") {
                        if let Some(hash_pos) = symbol.name.find('#') {
                            let base_name: Arc<str> = Arc::from(&symbol.name[4..hash_pos]);
                            gp_vis.add_direct(base_name, symbol.qualified_name.clone());
                        }
                    }
                }
            }
        }

        // 3. Process all imports FIRST (needed for inheritance to resolve types via imports)
        let t_imports_start = std::time::Instant::now();
        let mut visited: HashSet<(Arc<str>, Arc<str>)> = HashSet::new();
        let scope_keys: Vec<_> = self.visibility_map.keys().cloned().collect();

        for scope in &scope_keys {
            self.process_imports_recursive(scope, &mut visited);
        }
        let t_imports = t_imports_start.elapsed();

        // 4. Propagate inherited members from supertypes (can now resolve types via imports)
        let t_inherit_start = std::time::Instant::now();
        self.propagate_inherited_members();
        let t_inherit = t_inherit_start.elapsed();

        tracing::info!(
            "build_visibility_maps: {} scopes, imports={:?}, inheritance={:?}",
            scope_keys.len(),
            t_imports,
            t_inherit
        );
    }

    /// Propagate inherited members from supertypes into scope visibility maps.
    /// When `Shape :> Path`, members of `Path` become visible in `Shape`.
    ///
    /// Uses topological ordering by scope depth: shallower scopes are processed first.
    /// This ensures that when processing `Shape::tfe` (which inherits from `edges`),
    /// `Shape` has already inherited `edges` from `Path`.
    fn propagate_inherited_members(&mut self) {
        // Collect symbols with their unresolved supertypes and parent scope for later resolution
        // Format: (qualified_name, parent_scope, unresolved_supertype_name)
        let mut inheritance_edges: Vec<(Arc<str>, Arc<str>, Arc<str>)> = Vec::new();

        for symbol in &self.symbols {
            // Skip symbols that have been removed
            if !self.by_qualified_name.contains_key(&symbol.qualified_name) {
                continue;
            }

            if !symbol.supertypes.is_empty() {
                let scope = &symbol.qualified_name;
                let parent_scope: Arc<str> = Self::parent_scope(scope)
                    .map(Arc::from)
                    .unwrap_or_else(|| Arc::from(""));

                for supertype in &symbol.supertypes {
                    inheritance_edges.push((
                        scope.clone(),
                        parent_scope.clone(),
                        supertype.clone(),
                    ));
                }
            }
        }

        // Sort edges by scope depth (shallowest first)
        // This provides a rough topological order for most cases
        inheritance_edges.sort_by_key(|(scope, _, _)| scope.matches("::").count());

        // Process edges iteratively until no more progress
        // This handles cyclic dependencies and ensures all resolvable edges are processed
        let mut max_iterations = 100; // Safety limit
        let mut made_progress = true;

        while made_progress && max_iterations > 0 {
            made_progress = false;
            max_iterations -= 1;

            for (scope, parent_scope, supertype) in &inheritance_edges {
                // Try to resolve the supertype from the parent scope's context
                // Exclude the current scope to avoid self-references when resolving redefining supertypes
                if let Some(resolved) =
                    self.resolve_supertype_for_inheritance(supertype, parent_scope, Some(scope))
                {
                    // Get members from the resolved supertype's visibility
                    let parent_members: Vec<(Arc<str>, Arc<str>)> = self
                        .visibility_map
                        .get(&*resolved)
                        .map(|vis| {
                            vis.direct_defs
                                .iter()
                                .map(|(k, v)| (k.clone(), v.clone()))
                                .collect()
                        })
                        .unwrap_or_default();

                    // Add to child's visibility if not already present
                    if let Some(child_vis) = self.visibility_map.get_mut(&**scope) {
                        for (name, qname) in parent_members {
                            child_vis.direct_defs.entry(name).or_insert_with(|| {
                                made_progress = true;
                                qname
                            });
                        }
                    }
                }
            }
        }
    }

    /// Resolve a supertype reference for inheritance propagation.
    /// Uses visibility maps (including imports) for resolution.
    /// `exclude_scope` is used to avoid self-references when resolving redefining supertypes.
    fn resolve_supertype_for_inheritance(
        &self,
        name: &str,
        starting_scope: &str,
        exclude_scope: Option<&Arc<str>>,
    ) -> Option<Arc<str>> {
        // Try qualified lookup first
        if let Some(sym) = self.lookup_qualified(name) {
            // If this matches the excluded scope, skip it
            if let Some(excluded) = exclude_scope {
                if &sym.qualified_name == excluded {
                    // Don't return - fall through to scope-walking
                } else {
                    return Some(sym.qualified_name.clone());
                }
            } else {
                return Some(sym.qualified_name.clone());
            }
        }

        // Walk up scopes looking for the name
        let mut current_scope = starting_scope;
        loop {
            // Try direct qualified name in this scope
            let qname = if current_scope.is_empty() {
                name.to_string()
            } else {
                format!("{}::{}", current_scope, name)
            };

            if let Some(sym) = self.lookup_qualified(&qname) {
                // Skip if this is the excluded scope
                if let Some(excluded) = exclude_scope {
                    if &sym.qualified_name == excluded {
                        // Don't return, continue walking up
                        if current_scope.is_empty() {
                            break;
                        }
                        current_scope = Self::parent_scope(current_scope).unwrap_or("");
                        continue;
                    }
                }
                return Some(sym.qualified_name.clone());
            }

            // Check visibility map for this scope (both direct defs AND imports)
            if let Some(vis) = self.visibility_map.get(current_scope) {
                // Check direct definitions first
                if let Some(resolved) = vis.direct_defs.get(name) {
                    // Skip if this points to the excluded scope
                    if let Some(excluded) = exclude_scope {
                        if resolved == excluded {
                            // Don't return, continue walking up
                            if current_scope.is_empty() {
                                break;
                            }
                            current_scope = Self::parent_scope(current_scope).unwrap_or("");
                            continue;
                        }
                    }
                    return Some(resolved.clone());
                }
                // Also check imports (important for types imported via `import X::*`)
                if let Some(resolved) = vis.imports.get(name) {
                    // Skip if this points to the excluded scope
                    if let Some(excluded) = exclude_scope {
                        if resolved == excluded {
                            if current_scope.is_empty() {
                                break;
                            }
                            current_scope = Self::parent_scope(current_scope).unwrap_or("");
                            continue;
                        }
                    }
                    return Some(resolved.clone());
                }
            }

            if current_scope.is_empty() {
                break;
            }
            current_scope = Self::parent_scope(current_scope).unwrap_or("");
        }
        None
    }

    /// Helper to check if a symbol passes a given list of filters.
    fn symbol_passes_filters_list(&self, symbol_qname: &str, filters: &[Arc<str>]) -> bool {
        // Find the symbol by qualified name
        let symbol = match self.by_qualified_name.get(symbol_qname) {
            Some(&idx) => &self.symbols[idx],
            None => return true, // If we can't find the symbol, let it through
        };

        // Check if symbol has ALL required metadata
        for required_metadata in filters {
            let has_metadata = symbol
                .metadata_annotations
                .iter()
                .any(|ann| ann.as_ref() == required_metadata.as_ref());
            if !has_metadata {
                return false;
            }
        }
        true
    }

    /// Process imports for a scope recursively, handling transitive public re-exports.
    fn process_imports_recursive(
        &mut self,
        scope: &str,
        visited: &mut HashSet<(Arc<str>, Arc<str>)>,
    ) {
        let scope_arc: Arc<str> = Arc::from(scope);

        // Find import symbols in this scope using the parent index (much faster than scanning all symbols)
        let imports_to_process: Vec<(Arc<str>, Arc<str>, bool)> = self
            .by_parent_scope
            .get(&scope_arc)
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&idx| self.symbols.get(idx))
                    .filter(|s| s.kind == SymbolKind::Import)
                    .map(|s| (s.name.clone(), s.qualified_name.clone(), s.is_public))
                    .collect()
            })
            .unwrap_or_default();

        for (import_name, import_qname, is_public) in imports_to_process {
            let is_wildcard = import_name.ends_with("::*") && !import_name.ends_with("::**");
            let is_recursive = import_name.ends_with("::**");

            // Trim the wildcard/recursive suffix to get the base target
            let import_target = if is_recursive {
                import_name.trim_end_matches("::**")
            } else {
                import_name.trim_end_matches("::*")
            };

            // For specific imports like `import KerML::Element`, we need to ensure the
            // parent package (KerML) has had its imports processed first, so that
            // Element is visible via KerML's visibility map.
            // Use a special marker in visited to track scope processing
            if !is_wildcard && !is_recursive && import_target.contains("::") {
                if let Some(parent_pkg) = import_target.rsplit_once("::").map(|(p, _)| p) {
                    // Check if we've already processed this parent
                    let marker = (Arc::from(parent_pkg), Arc::from("__scope_processed__"));
                    if !visited.contains(&marker) {
                        visited.insert(marker);
                        // Recursively process the parent package first
                        self.process_imports_recursive(parent_pkg, visited);
                    }
                }
            }

            let resolved_target = self.resolve_import_target(scope, import_target);

            if is_wildcard || is_recursive {
                // Wildcard or recursive import: import symbols from target scope

                // Skip if already visited this (scope, target) pair
                let key = (Arc::from(scope), Arc::from(resolved_target.as_str()));
                if visited.contains(&key) {
                    continue;
                }
                visited.insert(key);

                // Recursively process the target's imports first (to get transitive symbols)
                self.process_imports_recursive(&resolved_target, visited);

                // Get filter info - both scope filters and import-specific filters
                let scope_filters = self.scope_filters.get(scope).cloned();
                let import_filters = self.import_filters.get(import_qname.as_ref()).cloned();

                // Combine filters: import filters take precedence, then scope filters
                let active_filters = import_filters.or(scope_filters);

                // Now copy symbols from target to this scope
                if let Some(target_vis) = self.visibility_map.get(&resolved_target as &str).cloned()
                {
                    // Collect symbols to import (applying filter)
                    let direct_defs_to_import: Vec<_> = target_vis
                        .direct_defs()
                        .filter(|(_, qname)| {
                            // Apply filter if present
                            if let Some(ref filters) = active_filters {
                                if !filters.is_empty() {
                                    return self.symbol_passes_filters_list(qname, filters);
                                }
                            }
                            true
                        })
                        .map(|(n, q)| (n.clone(), q.clone()))
                        .collect();

                    let vis = self
                        .visibility_map
                        .get_mut(scope)
                        .expect("scope must exist");

                    // Copy direct definitions (filtered)
                    for (name, qname) in direct_defs_to_import {
                        vis.add_import(name, qname);
                    }

                    // Only copy imports that come from publicly re-exported namespaces
                    // Private imports should NOT be transitively visible
                    let public_reexports = target_vis.public_reexports();
                    for (name, qname) in target_vis.imports() {
                        // Check if this import comes from a publicly re-exported namespace
                        let is_from_public_reexport = public_reexports.iter().any(|ns| {
                            qname.starts_with(ns.as_ref())
                                && (qname.len() == ns.len()
                                    || qname.as_bytes().get(ns.len()) == Some(&b':'))
                        });
                        if is_from_public_reexport {
                            vis.add_import(name.clone(), qname.clone());
                        }
                    }

                    if is_public {
                        vis.add_public_reexport(Arc::from(resolved_target.as_str()));
                        // Also propagate the target's public reexports for transitive chains
                        for reexport in public_reexports {
                            vis.add_public_reexport(reexport.clone());
                        }
                    }
                }

                // For recursive imports, also import all descendants
                if is_recursive {
                    self.import_descendants(scope, &resolved_target, &active_filters);
                }
            } else {
                // Specific import: import a single symbol
                // E.g., `import EngineDefs::Engine;` makes `Engine` visible as `EngineDefs::Engine`
                // Also handles short name imports: `import Pkg::mop` where mop is a short name
                // for MeasureOfPerformance - both `mop` and `MeasureOfPerformance` become visible

                // Get the resolved symbol's simple name (last component of resolved path)
                let simple_name = resolved_target
                    .rsplit("::")
                    .next()
                    .unwrap_or(&resolved_target);

                // Get the import's last segment (may differ if importing via short name)
                let import_last_seg = import_target.rsplit("::").next().unwrap_or(import_target);

                // Add to this scope's imports
                if let Some(vis) = self.visibility_map.get_mut(scope) {
                    // Always add the resolved symbol's name
                    vis.add_import(Arc::from(simple_name), Arc::from(resolved_target.as_str()));

                    // If imported via a different name (e.g., short name), add that too
                    if import_last_seg != simple_name {
                        vis.add_import(
                            Arc::from(import_last_seg),
                            Arc::from(resolved_target.as_str()),
                        );
                    }
                }
            }
        }
    }

    /// Import all descendants of a scope (for recursive imports like ::**).
    ///
    /// This imports all symbols that are nested under the target scope,
    /// not just direct children.
    fn import_descendants(
        &mut self,
        importing_scope: &str,
        target_scope: &str,
        filters: &Option<Vec<Arc<str>>>,
    ) {
        let target_prefix = format!("{}::", target_scope);

        // Find all symbols that are descendants of target_scope
        let descendant_symbols: Vec<(Arc<str>, Arc<str>)> = self
            .symbols
            .iter()
            .filter(|s| {
                // Skip imports, they're processed separately
                if s.kind == SymbolKind::Import || !s.qualified_name.starts_with(&target_prefix) {
                    return false;
                }
                // Apply filter if present
                if let Some(filter_list) = filters {
                    if !filter_list.is_empty() {
                        return self.symbol_passes_filters_list_static(
                            &s.metadata_annotations,
                            filter_list,
                        );
                    }
                }
                true
            })
            .map(|s| (s.name.clone(), s.qualified_name.clone()))
            .collect();

        // Add each descendant to the importing scope
        if let Some(vis) = self.visibility_map.get_mut(importing_scope) {
            for (simple_name, qualified_name) in descendant_symbols {
                vis.add_import(simple_name, qualified_name);
            }
        }
    }

    /// Check if a symbol passes filters given its metadata annotations directly.
    /// This avoids lookup by qualified name since we already have the symbol.
    fn symbol_passes_filters_list_static(
        &self,
        metadata_annotations: &[Arc<str>],
        filters: &[Arc<str>],
    ) -> bool {
        // Check if symbol has ALL required metadata
        for required_metadata in filters {
            let has_metadata = metadata_annotations
                .iter()
                .any(|ann| ann.as_ref() == required_metadata.as_ref());
            if !has_metadata {
                return false;
            }
        }
        true
    }

    /// Resolve an import target relative to a scope.
    ///
    /// According to SysML spec, after importing a namespace with `import P1::*`,
    /// the imported members become visible by their simple names. So subsequent
    /// imports like `import C::*` should resolve `C` through prior imports.
    ///
    /// Resolution order:
    /// 1. Check if target is already fully qualified and exists
    /// 2. Check current scope's visibility map (direct defs + imports)
    /// 3. Walk up parent scopes
    /// 4. Fall back to target as-is
    fn resolve_import_target(&self, scope: &str, target: &str) -> String {
        // If already qualified with ::, check as-is first
        if target.contains("::") && self.visibility_map.contains_key(target) {
            return target.to_string();
        }

        // For qualified paths like "Pkg::member", check if the last segment is a short name
        // E.g., "ParametersOfInterestMetadata::mop" where mop is short for MeasureOfPerformance
        if target.contains("::") {
            if let Some(last_sep_idx) = target.rfind("::") {
                let parent_part = &target[..last_sep_idx];
                let last_segment = &target[last_sep_idx + 2..];

                // First check if parent resolves directly
                let parent_qualified = if self.visibility_map.contains_key(parent_part) {
                    parent_part.to_string()
                } else {
                    // Try resolving parent from current scope
                    self.resolve_import_target(scope, parent_part)
                };

                // Check if last_segment is a direct child (by name)
                let direct_child = format!("{}::{}", parent_qualified, last_segment);
                if self.visibility_map.contains_key(&direct_child as &str) {
                    return direct_child;
                }

                // Check if last_segment matches a child's short_name
                if let Some(children) = self
                    .by_parent_scope
                    .get(&Arc::from(parent_qualified.as_str()))
                {
                    for &idx in children {
                        if let Some(sym) = self.symbols.get(idx) {
                            if sym.short_name.as_ref().map(|s| s.as_ref()) == Some(last_segment) {
                                return sym.qualified_name.to_string();
                            }
                        }
                    }
                }

                // Check if last_segment is visible via imports in parent's visibility map
                // This handles transitive public re-exports like:
                // ISQ has "public import ISQBase::*", so ISQ::DurationValue resolves
                // to ISQBase::DurationValue via ISQ's visibility map
                if let Some(vis) = self.visibility_map.get(&parent_qualified as &str) {
                    if let Some(resolved_qname) = vis.lookup(last_segment) {
                        return resolved_qname.to_string();
                    }
                }
            }
        }

        // For simple names (no ::), first check if it's visible via imports in current scope
        // This handles the SysML pattern: import P1::*; import C::*;
        // where C was imported from P1
        if !target.contains("::") {
            if let Some(vis) = self.visibility_map.get(scope) {
                // Check if target is visible (either as direct def or import)
                if let Some(resolved_qname) = vis.lookup(target) {
                    // Found it - return the qualified name
                    return resolved_qname.to_string();
                }
            }
        }

        // Try relative to scope and parent scopes (nested namespace lookup)
        let mut current = scope.to_string();
        loop {
            let candidate = if current.is_empty() {
                target.to_string()
            } else {
                format!("{}::{}", current, target)
            };

            if self.visibility_map.contains_key(&candidate as &str) {
                return candidate;
            }

            // Move up
            if let Some(idx) = current.rfind("::") {
                current = current[..idx].to_string();
            } else if !current.is_empty() {
                current = String::new();
            } else {
                break;
            }
        }

        // Fall back to target as-is (might be global)
        target.to_string()
    }

    /// Get the parent scope of a qualified name.
    ///
    /// "A::B::C" -> Some("A::B")
    /// "A" -> Some("")
    /// "" -> None
    /// "A::B::<anon>" -> Some("A::B") (anonymous scopes are skipped)
    fn parent_scope(qualified_name: &str) -> Option<&str> {
        if qualified_name.is_empty() {
            return None;
        }
        // Handle import qualified names: "Scope::import:Path" -> parent is "Scope"
        if let Some(import_pos) = qualified_name.find("::import:") {
            if import_pos == 0 {
                return Some(""); // Root level import
            }
            return Some(&qualified_name[..import_pos]);
        }
        // Handle root-level imports: "import:Path" (starts with import:, no :: before it)
        if qualified_name.starts_with("import:") {
            return Some(""); // Root level import
        }

        // Handle anonymous scopes like `<perform:...>` or `<anon#...>`
        // For `A::B::<perform:C::D>`, we want parent `A::B`
        // Find the last `::` that isn't inside angle brackets
        let mut depth = 0;
        let mut last_separator_outside_brackets = None;
        let bytes = qualified_name.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'<' {
                depth += 1;
            } else if bytes[i] == b'>' {
                if depth > 0 {
                    depth -= 1;
                }
            } else if depth == 0 && i + 1 < bytes.len() && bytes[i] == b':' && bytes[i + 1] == b':'
            {
                last_separator_outside_brackets = Some(i);
                i += 1; // Skip the second ':'
            }
            i += 1;
        }

        match last_separator_outside_brackets {
            Some(idx) => Some(&qualified_name[..idx]),
            None => Some(""), // Root level
        }
    }

    /// Build a resolver for the given scope.
    ///
    /// The resolver uses pre-computed visibility maps for efficient resolution.
    /// No need to manually collect imports - they're already in the visibility map.
    pub fn resolver_for_scope(&self, scope: &str) -> Resolver<'_> {
        Resolver::new(self).with_scope(scope)
    }
}

// ============================================================================
// SYMBOL KIND HELPERS
// ============================================================================

impl SymbolKind {
    /// Check if this is a definition kind (vs usage).
    pub fn is_definition(&self) -> bool {
        matches!(
            self,
            SymbolKind::Package
                | SymbolKind::PartDefinition
                | SymbolKind::ItemDefinition
                | SymbolKind::ActionDefinition
                | SymbolKind::PortDefinition
                | SymbolKind::AttributeDefinition
                | SymbolKind::ConnectionDefinition
                | SymbolKind::InterfaceDefinition
                | SymbolKind::AllocationDefinition
                | SymbolKind::RequirementDefinition
                | SymbolKind::ConstraintDefinition
                | SymbolKind::StateDefinition
                | SymbolKind::CalculationDefinition
                | SymbolKind::UseCaseDefinition
                | SymbolKind::AnalysisCaseDefinition
                | SymbolKind::ConcernDefinition
                | SymbolKind::ViewDefinition
                | SymbolKind::ViewpointDefinition
                | SymbolKind::RenderingDefinition
                | SymbolKind::EnumerationDefinition
                | SymbolKind::MetadataDefinition
                | SymbolKind::Interaction
        )
    }

    /// Check if this is a usage kind.
    pub fn is_usage(&self) -> bool {
        matches!(
            self,
            SymbolKind::PartUsage
                | SymbolKind::ItemUsage
                | SymbolKind::ActionUsage
                | SymbolKind::PortUsage
                | SymbolKind::AttributeUsage
                | SymbolKind::ConnectionUsage
                | SymbolKind::InterfaceUsage
                | SymbolKind::AllocationUsage
                | SymbolKind::RequirementUsage
                | SymbolKind::ConstraintUsage
                | SymbolKind::StateUsage
                | SymbolKind::CalculationUsage
                | SymbolKind::ReferenceUsage
                | SymbolKind::OccurrenceUsage
                | SymbolKind::FlowConnectionUsage
        )
    }

    /// Get the corresponding definition kind for a usage.
    pub fn to_definition_kind(&self) -> Option<SymbolKind> {
        match self {
            SymbolKind::PartUsage => Some(SymbolKind::PartDefinition),
            SymbolKind::ItemUsage => Some(SymbolKind::ItemDefinition),
            SymbolKind::ActionUsage => Some(SymbolKind::ActionDefinition),
            SymbolKind::PortUsage => Some(SymbolKind::PortDefinition),
            SymbolKind::AttributeUsage => Some(SymbolKind::AttributeDefinition),
            SymbolKind::ConnectionUsage => Some(SymbolKind::ConnectionDefinition),
            SymbolKind::InterfaceUsage => Some(SymbolKind::InterfaceDefinition),
            SymbolKind::AllocationUsage => Some(SymbolKind::AllocationDefinition),
            SymbolKind::RequirementUsage => Some(SymbolKind::RequirementDefinition),
            SymbolKind::ConstraintUsage => Some(SymbolKind::ConstraintDefinition),
            SymbolKind::StateUsage => Some(SymbolKind::StateDefinition),
            SymbolKind::CalculationUsage => Some(SymbolKind::CalculationDefinition),
            _ => None,
        }
    }
}

// ============================================================================
// RESOLUTION RESULT
// ============================================================================

/// Result of resolving a reference.
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum ResolveResult {
    /// Successfully resolved to a single symbol.
    Found(HirSymbol),
    /// Resolved to multiple candidates (ambiguous).
    Ambiguous(Vec<HirSymbol>),
    /// Could not resolve the reference.
    NotFound,
}

impl ResolveResult {
    /// Get the resolved symbol if unambiguous.
    pub fn symbol(&self) -> Option<&HirSymbol> {
        match self {
            ResolveResult::Found(s) => Some(s),
            _ => None,
        }
    }

    /// Check if resolution was successful.
    pub fn is_found(&self) -> bool {
        matches!(self, ResolveResult::Found(_))
    }

    /// Check if the reference was ambiguous.
    pub fn is_ambiguous(&self) -> bool {
        matches!(self, ResolveResult::Ambiguous(_))
    }
}

// ============================================================================
// RESOLVER
// ============================================================================

/// Resolver for name lookups using pre-computed visibility maps.
///
/// The resolver uses visibility maps built during index construction,
/// so there's no need to manually configure imports.
#[derive(Clone, Debug)]
pub struct Resolver<'a> {
    /// The symbol index to search.
    index: &'a SymbolIndex,
    /// Current scope prefix (e.g., "Vehicle::Powertrain").
    current_scope: Arc<str>,
}

impl<'a> Resolver<'a> {
    /// Create a new resolver.
    pub fn new(index: &'a SymbolIndex) -> Self {
        Self {
            index,
            current_scope: Arc::from(""),
        }
    }

    /// Set the current scope.
    pub fn with_scope(mut self, scope: impl Into<Arc<str>>) -> Self {
        self.current_scope = scope.into();
        self
    }

    /// Resolve a name using pre-computed visibility maps.
    pub fn resolve(&self, name: &str) -> ResolveResult {
        // 1. Handle qualified paths like "ISQ::TorqueValue"
        if name.contains("::") {
            // For qualified paths, try exact match first
            if let Some(symbol) = self.index.lookup_qualified(name) {
                return ResolveResult::Found(symbol.clone());
            }
            return self.resolve_qualified_path(name);
        }

        // 2. For simple names, try scope walking FIRST (finds local Requirements before global)
        let mut current = self.current_scope.to_string();
        let mut scopes_checked = Vec::new();
        loop {
            scopes_checked.push(current.clone());
            if let Some(vis) = self.index.visibility_for_scope(&current) {
                // Check direct definitions first (higher priority)
                if let Some(qname) = vis.lookup_direct(name) {
                    tracing::trace!(
                        "[RESOLVE] Found '{}' as direct def in scope '{}' -> {}",
                        name,
                        current,
                        qname
                    );
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return ResolveResult::Found(sym.clone());
                    }
                }

                // Check imports
                if let Some(qname) = vis.lookup_import(name) {
                    tracing::trace!(
                        "[RESOLVE] Found '{}' as import in scope '{}' -> {}",
                        name,
                        current,
                        qname
                    );
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return ResolveResult::Found(sym.clone());
                    }
                }
            }

            // For usages AND definitions in scope, check inherited members from supertypes
            // E.g., missionContext: MissionContext has spatialCF via inheritance from Context
            // E.g., use case def MyUseCase has start/done via inheritance from Actions::Action
            if !current.is_empty() {
                if let Some(scope_sym) = self.index.lookup_qualified(&current) {
                    // Check inherited members for both usages and definitions
                    // (both can have supertypes that define members like start/done)
                    if !scope_sym.supertypes.is_empty() {
                        if let Some(result) = self.resolve_inherited_member(scope_sym, name) {
                            return result;
                        }
                    }
                }
            }

            // Move up to parent scope
            if let Some(idx) = current.rfind("::") {
                current = current[..idx].to_string();
            } else if !current.is_empty() {
                current = String::new(); // Try root scope
            } else {
                break;
            }
        }

        tracing::debug!(
            "[RESOLVE] '{}' not found in any of {} scopes: {:?}",
            name,
            scopes_checked.len(),
            scopes_checked.first()
        );

        // 3. Fall back to exact qualified match for simple names
        // This handles cases like a global package named exactly "Requirements"
        if let Some(symbol) = self.index.lookup_qualified(name) {
            return ResolveResult::Found(symbol.clone());
        }

        ResolveResult::NotFound
    }

    /// Resolve a qualified path like "ISQ::TorqueValue" using visibility maps.
    ///
    /// This handles cases where:
    /// - ISQ is a package with `public import ISQSpaceTime::*`
    /// - TorqueValue is defined in ISQSpaceTime
    fn resolve_qualified_path(&self, path: &str) -> ResolveResult {
        let (first, rest) = match path.find("::") {
            Some(idx) => (&path[..idx], &path[idx + 2..]),
            None => return ResolveResult::NotFound,
        };

        // Resolve the first segment (it's a simple name, so resolve() won't recurse here)
        let first_sym = self.resolve(first);

        if let ResolveResult::Found(first_symbol) = first_sym {
            // Get the target scope (follow alias if needed)
            let target_scope = if first_symbol.kind == SymbolKind::Alias {
                if let Some(target) = first_symbol.supertypes.first() {
                    target.as_ref()
                } else {
                    first_symbol.qualified_name.as_ref()
                }
            } else {
                first_symbol.qualified_name.as_ref()
            };

            // Handle nested qualified paths (e.g., "A::B::C" where rest="B::C")
            if rest.contains("::") {
                // Recursively resolve with target scope
                let nested_resolver = Resolver::new(self.index).with_scope(target_scope);
                return nested_resolver.resolve(rest);
            }

            // Look up 'rest' in target scope's visibility map
            if let Some(vis) = self.index.visibility_for_scope(target_scope) {
                // Check direct definitions first
                if let Some(qname) = vis.lookup_direct(rest) {
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return ResolveResult::Found(sym.clone());
                    }
                }

                // Check imports (handles public import ISQSpaceTime::*)
                if let Some(qname) = vis.lookup_import(rest) {
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return ResolveResult::Found(sym.clone());
                    }
                }
            }

            // Try direct qualified lookup (might be nested definition)
            let full_path = format!("{}::{}", target_scope, rest);
            if let Some(sym) = self.index.lookup_qualified(&full_path) {
                return ResolveResult::Found(sym.clone());
            }
        }

        ResolveResult::NotFound
    }

    /// Resolve a member name inherited through a usage's type hierarchy.
    ///
    /// E.g., if `missionContext: MissionContext` and `MissionContext :> Context`
    /// and `Context` has `spatialCF`, this will find it.
    ///
    /// Also handles redefinition chains: if `obj :>> Case::obj` and `Case::obj` has
    /// type `RequirementCheck`, this will look for members in `RequirementCheck`.
    fn resolve_inherited_member(
        &self,
        usage_sym: &HirSymbol,
        member_name: &str,
    ) -> Option<ResolveResult> {
        // Collect all types to search through (handles multiple supertypes and redefinitions)
        let mut types_to_search: Vec<HirSymbol> = Vec::new();
        let mut visited = std::collections::HashSet::new();
        visited.insert(usage_sym.qualified_name.clone());

        // Start by resolving the usage's supertypes
        let usage_scope = SymbolIndex::parent_scope(&usage_sym.qualified_name).unwrap_or("");
        for type_name in &usage_sym.supertypes {
            if let Some(type_sym) = self.resolve_without_inheritance(type_name, usage_scope) {
                if !visited.contains(&type_sym.qualified_name) {
                    visited.insert(type_sym.qualified_name.clone());
                    types_to_search.push(type_sym);
                }
            }
        }

        // Also check SemanticMetadata baseType for metadata annotations
        // If an element has `#systemdd` annotation, and SysDDMetadata has `baseType = global_systemsdd : SysDD`,
        // then we should also search in SysDD for inherited members.
        for annotation in &usage_sym.metadata_annotations {
            if let Some(basetype_qname) =
                self.resolve_semantic_metadata_basetype(annotation, usage_scope)
            {
                if let Some(basetype_sym) =
                    self.resolve_without_inheritance(&basetype_qname, usage_scope)
                {
                    if !visited.contains(&basetype_sym.qualified_name) {
                        visited.insert(basetype_sym.qualified_name.clone());
                        types_to_search.push(basetype_sym);
                    }
                }
            }
        }

        // Walk through all types, following the hierarchy
        while let Some(current_type) = types_to_search.pop() {
            // If current_type is a feature (not a definition), we need to get ITS types
            // This handles redefinition chains like `obj :>> Case::obj` where Case::obj has type RequirementCheck
            if !current_type.kind.is_definition() {
                let feature_scope =
                    SymbolIndex::parent_scope(&current_type.qualified_name).unwrap_or("");
                for supertype in &current_type.supertypes {
                    if let Some(super_sym) =
                        self.resolve_without_inheritance(supertype, feature_scope)
                    {
                        if !visited.contains(&super_sym.qualified_name) {
                            visited.insert(super_sym.qualified_name.clone());
                            types_to_search.push(super_sym);
                        }
                    }
                }
                continue; // Don't look for members in usages, only in their types
            }

            // Check if current_type defines this member
            let member_qname = format!("{}::{}", current_type.qualified_name, member_name);
            if let Some(member_sym) = self.index.lookup_qualified(&member_qname) {
                return Some(ResolveResult::Found(member_sym.clone()));
            }

            // Add parent types to search queue
            let parent_scope =
                SymbolIndex::parent_scope(&current_type.qualified_name).unwrap_or("");
            for parent_type_name in &current_type.supertypes {
                if let Some(parent_type) =
                    self.resolve_without_inheritance(parent_type_name, parent_scope)
                {
                    if !visited.contains(&parent_type.qualified_name) {
                        visited.insert(parent_type.qualified_name.clone());
                        types_to_search.push(parent_type);
                    }
                }
            }
        }

        None
    }

    /// Resolve a name without checking inherited members (to avoid recursion).
    fn resolve_without_inheritance(&self, name: &str, starting_scope: &str) -> Option<HirSymbol> {
        // Handle qualified paths
        if name.contains("::") {
            if let Some(symbol) = self.index.lookup_qualified(name) {
                return Some(symbol.clone());
            }
            // Try qualified path resolution without recursion
            return self.resolve_qualified_without_inheritance(name, starting_scope);
        }

        // For simple names, do scope walking without inheritance check
        let mut current = starting_scope.to_string();
        loop {
            if let Some(vis) = self.index.visibility_for_scope(&current) {
                if let Some(qname) = vis.lookup_direct(name) {
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return Some(sym.clone());
                    }
                }
                if let Some(qname) = vis.lookup_import(name) {
                    if let Some(sym) = self.index.lookup_qualified(qname) {
                        return Some(sym.clone());
                    }
                }
            }

            if let Some(idx) = current.rfind("::") {
                current = current[..idx].to_string();
            } else if !current.is_empty() {
                current = String::new();
            } else {
                break;
            }
        }

        // Fall back to exact qualified match
        self.index.lookup_qualified(name).cloned()
    }

    /// Resolve the baseType from a SemanticMetadata definition (uses cached lookup).
    /// Given an annotation name like "systemdd", returns the baseType's type (e.g., "SysDD").
    /// This implements SysML v2 SemanticMetadata where annotated elements implicitly specialize baseType's type.
    fn resolve_semantic_metadata_basetype(
        &self,
        annotation_name: &str,
        _starting_scope: &str,
    ) -> Option<String> {
        // Use the cached lookup in SymbolIndex
        self.index
            .get_metadata_basetype(annotation_name)
            .map(|s| s.to_string())
    }

    /// Resolve a qualified path without inheritance check (to avoid recursion).
    fn resolve_qualified_without_inheritance(
        &self,
        path: &str,
        starting_scope: &str,
    ) -> Option<HirSymbol> {
        let (first, rest) = match path.find("::") {
            Some(idx) => (&path[..idx], &path[idx + 2..]),
            None => return None,
        };

        // Resolve first segment
        let first_symbol = self.resolve_without_inheritance(first, starting_scope)?;
        let target_scope = first_symbol.qualified_name.as_ref();

        if rest.contains("::") {
            return self.resolve_qualified_without_inheritance(rest, target_scope);
        }

        // Look up rest in target scope
        if let Some(vis) = self.index.visibility_for_scope(target_scope) {
            if let Some(qname) = vis.lookup_direct(rest) {
                if let Some(sym) = self.index.lookup_qualified(qname) {
                    return Some(sym.clone());
                }
            }
            if let Some(qname) = vis.lookup_import(rest) {
                if let Some(sym) = self.index.lookup_qualified(qname) {
                    return Some(sym.clone());
                }
            }
        }

        // Try direct qualified lookup
        let full_path = format!("{}::{}", target_scope, rest);
        self.index.lookup_qualified(&full_path).cloned()
    }

    /// Resolve a type reference (for : Type annotations).
    pub fn resolve_type(&self, name: &str) -> ResolveResult {
        let result = self.resolve(name);

        // Filter to only definition kinds
        match result {
            ResolveResult::Found(ref symbol) if symbol.kind.is_definition() => result,
            ResolveResult::Found(_) => ResolveResult::NotFound,
            ResolveResult::Ambiguous(symbols) => {
                let defs: Vec<_> = symbols
                    .into_iter()
                    .filter(|s| s.kind.is_definition())
                    .collect();
                match defs.len() {
                    0 => ResolveResult::NotFound,
                    1 => ResolveResult::Found(defs.into_iter().next().unwrap()),
                    _ => ResolveResult::Ambiguous(defs),
                }
            }
            ResolveResult::NotFound => ResolveResult::NotFound,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hir::new_element_id;

    fn make_symbol(name: &str, qualified: &str, kind: SymbolKind, file: u32) -> HirSymbol {
        HirSymbol {
            name: Arc::from(name),
            short_name: None,
            qualified_name: Arc::from(qualified),
            element_id: new_element_id(),
            kind,
            file: FileId::new(file),
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
            short_name_start_line: None,
            short_name_start_col: None,
            short_name_end_line: None,
            short_name_end_col: None,
            doc: None,
            supertypes: Vec::new(),
            relationships: Vec::new(),
            type_refs: Vec::new(),
            is_public: false,
            view_data: None,
            metadata_annotations: Vec::new(),
            is_abstract: false,
            is_variation: false,
            is_readonly: false,
            is_derived: false,
            is_parallel: false,
            is_individual: false,
            is_end: false,
            is_default: false,
            is_ordered: false,
            is_nonunique: false,
            is_portion: false,
            direction: None,
            multiplicity: None,
        }
    }

    #[test]
    fn test_symbol_index_basic() {
        let mut index = SymbolIndex::new();

        let symbols = vec![
            make_symbol("Vehicle", "Vehicle", SymbolKind::Package, 0),
            make_symbol("Car", "Vehicle::Car", SymbolKind::PartDefinition, 0),
            make_symbol("engine", "Vehicle::Car::engine", SymbolKind::PartUsage, 0),
        ];

        index.add_file(FileId::new(0), symbols);

        assert_eq!(index.len(), 3);
        assert!(index.lookup_qualified("Vehicle::Car").is_some());
        assert!(index.lookup_qualified("Vehicle::Car::engine").is_some());
        assert!(index.lookup_definition("Vehicle::Car").is_some());
        assert!(index.lookup_definition("Vehicle::Car::engine").is_none()); // Usage, not def
    }

    #[test]
    fn test_symbol_index_remove_file() {
        let mut index = SymbolIndex::new();

        index.add_file(
            FileId::new(0),
            vec![make_symbol("A", "A", SymbolKind::PartDefinition, 0)],
        );
        index.add_file(
            FileId::new(1),
            vec![make_symbol("B", "B", SymbolKind::PartDefinition, 1)],
        );

        assert_eq!(index.len(), 2);

        index.remove_file(FileId::new(0));

        assert_eq!(index.len(), 1);
        assert!(index.lookup_qualified("A").is_none());
        assert!(index.lookup_qualified("B").is_some());
    }

    #[test]
    fn test_resolver_qualified_name() {
        let mut index = SymbolIndex::new();
        index.add_file(
            FileId::new(0),
            vec![make_symbol(
                "Car",
                "Vehicle::Car",
                SymbolKind::PartDefinition,
                0,
            )],
        );

        let resolver = Resolver::new(&index);
        let result = resolver.resolve("Vehicle::Car");

        assert!(result.is_found());
        assert_eq!(result.symbol().unwrap().name.as_ref(), "Car");
    }

    #[test]
    fn test_resolver_with_scope() {
        let mut index = SymbolIndex::new();
        index.add_file(
            FileId::new(0),
            vec![
                make_symbol("Car", "Vehicle::Car", SymbolKind::PartDefinition, 0),
                make_symbol("engine", "Vehicle::Car::engine", SymbolKind::PartUsage, 0),
            ],
        );
        index.ensure_visibility_maps();

        let resolver = Resolver::new(&index).with_scope("Vehicle::Car");
        let result = resolver.resolve("engine");

        assert!(result.is_found());
    }

    #[test]
    fn test_resolver_with_visibility_maps() {
        let mut index = SymbolIndex::new();
        // Create a package ISQ with Real defined inside
        index.add_file(
            FileId::new(0),
            vec![
                make_symbol("ISQ", "ISQ", SymbolKind::Package, 0),
                make_symbol("Real", "ISQ::Real", SymbolKind::AttributeDefinition, 0),
            ],
        );
        // Create an import from another scope
        let mut import_sym = make_symbol("ISQ::*", "TestPkg::import:ISQ::*", SymbolKind::Import, 1);
        import_sym.is_public = false;
        index.add_file(
            FileId::new(1),
            vec![
                make_symbol("TestPkg", "TestPkg", SymbolKind::Package, 1),
                import_sym,
            ],
        );
        index.ensure_visibility_maps();

        // Resolver from TestPkg should find Real via import
        let resolver = Resolver::new(&index).with_scope("TestPkg");
        let result = resolver.resolve("Real");

        assert!(result.is_found());
        assert_eq!(
            result.symbol().unwrap().qualified_name.as_ref(),
            "ISQ::Real"
        );
    }

    #[test]
    fn test_symbol_kind_is_definition() {
        assert!(SymbolKind::PartDefinition.is_definition());
        assert!(SymbolKind::ActionDefinition.is_definition());
        assert!(!SymbolKind::PartUsage.is_definition());
        assert!(!SymbolKind::Import.is_definition());
    }

    #[test]
    fn test_symbol_kind_is_usage() {
        assert!(SymbolKind::PartUsage.is_usage());
        assert!(SymbolKind::ActionUsage.is_usage());
        assert!(!SymbolKind::PartDefinition.is_usage());
        assert!(!SymbolKind::Package.is_usage());
    }

    #[test]
    fn test_debug_message_chain_resolution() {
        use crate::hir::symbols::extract_symbols_unified;
        use crate::syntax::SyntaxFile;

        let source = r#"
package Test {
    part def Sequence;
    part def Driver {
        action turnVehicleOn;
    }
    part def Vehicle {
        action trigger1;
    }
    part def IgnitionCmd;
    
    part sequence : Sequence {
        part driver : Driver;
        part vehicle : Vehicle;
        message of ignitionCmd:IgnitionCmd from driver.turnVehicleOn to vehicle.trigger1;
    }
}
"#;
        let file_id = FileId::new(0);
        let syntax = SyntaxFile::sysml(source);
        let symbols = extract_symbols_unified(file_id, &syntax);

        let mut index = SymbolIndex::new();
        index.add_file(file_id, symbols);
        index.ensure_visibility_maps();

        // Now resolve all type refs (this is what happens in the semantic analysis pass)
        index.resolve_all_type_refs();

        // Check what's in various scopes
        println!("\n=== Symbols and their type_refs ===");
        for sym in index.symbols_in_file(file_id) {
            println!("  {} ({:?})", sym.qualified_name, sym.kind);
            for (i, tr) in sym.type_refs.iter().enumerate() {
                println!("    type_ref[{}]: {:?}", i, tr);
            }
        }

        // Find ignitionCmd and check its chain type_refs
        let ignition_cmd = index
            .lookup_qualified("Test::sequence::ignitionCmd")
            .expect("ignitionCmd should exist");
        println!("\n=== ignitionCmd type_refs ===");
        for (i, trk) in ignition_cmd.type_refs.iter().enumerate() {
            match trk {
                crate::hir::TypeRefKind::Chain(chain) => {
                    println!("  Chain[{}]:", i);
                    for (j, part) in chain.parts.iter().enumerate() {
                        println!(
                            "    part[{}]: {} -> resolved: {:?}",
                            j, part.target, part.resolved_target
                        );
                    }
                }
                crate::hir::TypeRefKind::Simple(tr) => {
                    println!(
                        "  Simple[{}]: {} -> resolved: {:?}",
                        i, tr.target, tr.resolved_target
                    );
                }
            }
        }

        // Check that driver.turnVehicleOn chain resolved correctly
        // The first part (driver) should resolve to Test::sequence::driver
        // The second part (turnVehicleOn) should resolve to Test::Driver::turnVehicleOn (via typing)
        let mut found_driver_chain = false;
        let mut turn_vehicle_on_tr: Option<&crate::hir::TypeRef> = None;
        for trk in &ignition_cmd.type_refs {
            if let crate::hir::TypeRefKind::Chain(chain) = trk {
                if chain.parts.len() >= 2 && chain.parts[0].target.as_ref() == "driver" {
                    found_driver_chain = true;
                    turn_vehicle_on_tr = Some(&chain.parts[1]);
                    assert!(
                        chain.parts[0].resolved_target.is_some(),
                        "driver (first part of chain) should be resolved"
                    );
                    assert_eq!(
                        chain.parts[0].resolved_target.as_deref(),
                        Some("Test::sequence::driver"),
                        "driver should resolve to Test::sequence::driver"
                    );
                    // turnVehicleOn should resolve to the action in Driver def
                    assert!(
                        chain.parts[1].resolved_target.is_some(),
                        "turnVehicleOn (second part of chain) should be resolved"
                    );
                }
            }
        }
        assert!(
            found_driver_chain,
            "Should have found driver.turnVehicleOn chain in ignitionCmd"
        );

        // Verify the turnVehicleOn part was found and resolved
        let _tr = turn_vehicle_on_tr.expect("Should have found turnVehicleOn");

        // NOTE: Hover on individual chain parts requires per-part position tracking,
        // which is a separate improvement. For now we verify chain resolution works.
    }
}