codingest 0.2.35

codingest — standalone extraction of KGLite's code-tree component: parse polyglot codebases into kglite knowledge graphs (tree-sitter parsers, call/type/route edges, docs pass, multi-rev merge)
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
//! USES_TYPE, CONTAINS, IMPORTS, FFI_EXPOSES edges.

use super::js_workspace::JsWorkspace;
use crate::models::{ClassInfo, ConstantInfo, EnumInfo, FileInfo, FunctionInfo, InterfaceInfo};
use crate::parsers::registry;
use aho_corasick::{AhoCorasick, MatchKind};
use rayon::prelude::*;
use std::collections::{BTreeMap, HashMap, HashSet};

fn get_separator(language: &str) -> &'static str {
    registry::edge_sep(language)
}

pub struct ContainsEdge {
    pub parent: String,
    pub child: String,
}

pub struct ImportEdge {
    pub file_path: String,
    pub module: String,
}

/// `File -[IMPORTS]-> File` — direct file-to-file dependency.
///
/// Sibling to `ImportEdge` (File → Module). Each source file's import strings
/// are resolved against the project's `module_path → file_path` reverse index
/// using the same longest-prefix walk as `build_import_edges`. Multiple
/// imports from the same source file resolving to the same target file are
/// aggregated into a single edge with `import_count` ≥ 1.
///
/// Powers transitive file-level impact analysis: "given changed files, which
/// other files are affected?" is one Cypher hop (e.g.
/// `MATCH (f:File)-[:IMPORTS]->(t:File {is_test: true}) ...`).
pub struct FileImportEdge {
    pub source: String,
    pub target: String,
    pub import_count: i64,
}

pub struct UsesTypeEdge {
    pub function: String,
    pub type_name: String,
    /// Target node type: "Struct" | "Class" | "Enum" | "Trait" | "Protocol" | "Interface"
    pub target_node_type: &'static str,
    /// Where in the function signature this type appears. Aggregates across
    /// all sites in the same function — a type used as both a parameter and
    /// a return value yields `"both"`. Values: `"parameter"` | `"receiver"` |
    /// `"return"` | `"both"` | `"signature"`. `"receiver"` is the implicit
    /// input of a method, kept distinct from an explicit parameter;
    /// `"signature"` is the fallback when the parser couldn't extract
    /// structured parameters (typically the AC scanner found the type embedded
    /// in the signature string).
    ///
    /// Cypher: `WHERE r.position IN ['parameter','receiver','both']` for "consumes T",
    /// `WHERE r.position IN ['return','both']` for "produces T".
    pub position: &'static str,
}

pub struct FfiExposesEdge {
    pub module_fn: String,
    pub target_qname: String,
    pub target_type: &'static str,
    pub py_name: String,
}

/// `Module -[CONTAINS]-> File` edges — one per file pointing to its leaf module.
///
/// `build_modules` synthesizes a Module node for every prefix of a file's
/// `module_path`; the leaf module's qualified_name equals `file.module_path`
/// exactly. Without this edge, "what's in module X" requires a string
/// `STARTS WITH` filter; with it, the natural top-down walk works:
///
/// ```cypher
/// MATCH (m:Module {qualified_name: 'crate::graph::cypher'})
///       -[:HAS_SUBMODULE*0..]->(:Module)-[:CONTAINS]->(f:File)-[:DEFINES]->(fn:Function)
/// RETURN fn.qualified_name
/// ```
pub struct ModuleContainsFileEdge {
    pub module: String,
    pub file_path: String,
}

pub fn build_module_contains_file_edges(files: &[FileInfo]) -> Vec<ModuleContainsFileEdge> {
    files
        .iter()
        .filter(|f| !f.module_path.is_empty())
        .map(|f| ModuleContainsFileEdge {
            module: f.module_path.clone(),
            file_path: f.path.clone(),
        })
        .collect()
}

/// Module CONTAINS Module edges from file submodule declarations.
pub fn build_contains_edges(files: &[FileInfo]) -> Vec<ContainsEdge> {
    let mut out = Vec::new();
    let mut implicit_seen = HashSet::new();
    for f in files {
        if registry::has_implicit_module_hierarchy(&f.language) {
            let sep = registry::module_sep(&f.language);
            let parts: Vec<_> = f.module_path.split(sep).collect();
            for end in 2..=parts.len() {
                let parent = parts[..end - 1].join(sep);
                let child = parts[..end].join(sep);
                if implicit_seen.insert((parent.clone(), child.clone())) {
                    out.push(ContainsEdge { parent, child });
                }
            }
        }

        let sep = get_separator(&f.language);
        for sub in &f.submodule_declarations {
            out.push(ContainsEdge {
                parent: f.module_path.clone(),
                child: format!("{}{}{}", f.module_path, sep, sub),
            });
        }
    }
    out
}

fn normalize_import_path(base: &str, raw: &str) -> Option<String> {
    let mut parts: Vec<&str> = base.split('/').filter(|part| !part.is_empty()).collect();
    for part in raw.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                parts.pop()?;
            }
            value => parts.push(value),
        }
    }
    (!parts.is_empty()).then(|| parts.join("/"))
}

fn path_import_candidates(file: &FileInfo, raw: &str) -> Vec<String> {
    if !registry::uses_path_imports(&file.language) {
        return Vec::new();
    }

    let trimmed = raw.trim();
    // A leading `<` is the C/C++ parser's system-include marker (`<vector>`
    // kept verbatim): the specifier names a toolchain header searched only on
    // the compiler's system path, so resolving it against project files would
    // manufacture an edge whenever a project path happens to share the name
    // (`<local.h>` vs a project-root `local.h`). Same no-edge outcome as any
    // other unresolvable import.
    if trimmed.is_empty()
        || trimmed.starts_with('<')
        || trimmed.starts_with('#')
        || trimmed.starts_with("//")
        || trimmed.contains("://")
        || trimmed.to_ascii_lowercase().starts_with("data:")
    {
        return Vec::new();
    }

    let without_suffix = trimmed
        .split(['?', '#'])
        .next()
        .unwrap_or("")
        .replace('\\', "/");
    if without_suffix.is_empty() {
        return Vec::new();
    }

    let mut candidates = Vec::new();
    let root_path = without_suffix.trim_start_matches('/');
    let root_absolute = without_suffix.starts_with('/');
    let parent = file.path.rsplit_once('/').map_or("", |(parent, _)| parent);
    if !root_absolute {
        if let Some(candidate) = normalize_import_path(parent, root_path) {
            candidates.push(candidate);
        }
    }
    // The project-root fallback, for every language EXCEPT C/C++.
    //
    // A quoted `#include "x.h"` is resolved by the compiler against the
    // including file's directory and then along the `-I` search path — never
    // against the project root. The graph records no `-I` flags, so an include
    // the file-relative try misses is a MISS BY DESIGN; that is the contract
    // the cJSON reconciliation measured and the one the angle/quoted split
    // exists to hold (0 false positives, misses only). The unconditional root
    // fallback broke it in one shape: a same-named file anchored at the
    // project root (`net/socket.c` including `"config.h"` while an unrelated
    // `config.h` sits at the root) manufactured an edge no compiler would ever
    // produce. Direction of failure stays "missed edge, never wrong edge".
    if !matches!(file.language.as_str(), "c" | "cpp") {
        if let Some(candidate) = normalize_import_path("", root_path) {
            if !candidates.contains(&candidate) {
                candidates.push(candidate);
            }
        }
    }
    // A leading `/` in an HTML/CSS reference is SERVED-root-absolute, and the
    // served root is not always the project root: a built site under `dist/`
    // is served with `dist/` as `/`, so `/_astro/app.css` names
    // `dist/_astro/app.css` — a file that IS in the graph, which the
    // project-root-only try could never reach. The project root stays first,
    // so every reference that resolves today keeps its answer; the linking
    // file's own directory is tried after it. The existence check downstream
    // still gates, so this can only ever resolve a target already in the
    // graph.
    if root_absolute && matches!(file.language.as_str(), "html" | "css") {
        if let Some(candidate) = normalize_import_path(parent, root_path) {
            if !candidates.contains(&candidate) {
                candidates.push(candidate);
            }
        }
    }

    if file.language == "css" {
        let extensionless: Vec<_> = candidates
            .iter()
            .filter(|candidate| {
                candidate
                    .rsplit_once('/')
                    .map_or(candidate.as_str(), |(_, name)| name)
                    .rsplit_once('.')
                    .is_none()
            })
            .map(|candidate| format!("{candidate}.css"))
            .collect();
        candidates.extend(extensionless);
    }
    candidates
}

/// Module-path suffixes a TS/JS specifier may carry. Stripped before matching,
/// with the same list `JstsParser::file_to_module_path` strips. The JS
/// suffixes matter for TS too: NodeNext resolution has source files import
/// each other by their *emitted* name (`import "./util.js"` resolving to
/// `util.ts`).
const MODULE_PATH_EXTENSIONS: &[&str] = crate::parsers::typescript::JSTS_MODULE_SUFFIXES;

/// Candidate module paths for one TS/JS import specifier, in fixed priority
/// order — first match wins, and the order IS the documented tie-break.
///
/// Relative specifiers only in this pass: `./x` and `../x` are normalized
/// against the importing file's directory, extension-stripped, and offered as
/// (1) the normalized path and (2) the same path with a trailing `/index`
/// segment removed, because `file_to_module_path` collapses `a/b/index.ts` to
/// module `a/b`. Bare and aliased specifiers fall through to the caller's
/// existing longest-prefix walk.
///
/// No filesystem probing and no extension guessing: the candidates are pure
/// string derivations, checked against the project's real module set by the
/// caller. That is what makes it impossible to manufacture an edge to a target
/// that does not exist.
fn module_path_import_candidates(
    file: &FileInfo,
    raw: &str,
    workspace: &JsWorkspace,
) -> Vec<String> {
    if !registry::uses_module_path_imports(&file.language) {
        return Vec::new();
    }
    let trimmed = raw.trim();
    let parent = file.path.rsplit_once('/').map_or("", |(parent, _)| parent);

    // Raw (still extension-carrying) paths, in priority order.
    let raw_paths: Vec<String> = if trimmed.starts_with("./")
        || trimmed.starts_with("../")
        || trimmed == "."
        || trimmed == ".."
    {
        normalize_import_path(parent, trimmed).into_iter().collect()
    } else {
        // Alias before workspace package: a tsconfig `paths` entry is an
        // explicit, file-scoped instruction, while package-name matching is a
        // convention-based probe.
        let mut paths = workspace.alias_targets(parent, trimmed);
        paths.extend(workspace.package_targets(trimmed));
        paths
    };

    let mut candidates: Vec<String> = Vec::new();
    let mut push = |candidate: String| {
        if !candidate.is_empty() && !candidates.contains(&candidate) {
            candidates.push(candidate);
        }
    };
    for path in raw_paths {
        let stripped = MODULE_PATH_EXTENSIONS
            .iter()
            .find_map(|ext| path.strip_suffix(ext))
            .unwrap_or(path.as_str())
            .to_string();
        // A bare root-level `index` collapses to nothing resolvable, so the
        // emptiness guard in `push` is load-bearing, not defensive.
        let without_index = stripped.strip_suffix("/index").map(str::to_string);
        push(stripped);
        if let Some(without_index) = without_index {
            push(without_index);
        }
    }
    candidates
}

/// The leading segments a parser's `file_to_module_path` prepended to this
/// file's module path but which import specifiers never carry.
///
/// Python's `file_to_module_path` prefixes every module path with the source
/// root's own directory name, so a checkout of `pkg/app.py` under `py_basic/`
/// gets module path `py_basic.pkg.app` while its own `from pkg.util import
/// helper` names `pkg.util`. The two can never meet in a raw prefix walk. The
/// prefix is recovered rather than assumed: render the file path the way the
/// parser does (drop the extension, drop a trailing `__init__`), join it with
/// the module separator, and subtract that tail from the module path. What is
/// left is exactly the segments the parser added.
///
/// Returns `None` when nothing was added — a clone layout
/// (`xarray/core/dataset.py` → `xarray.core.dataset`) subtracts to nothing, so
/// that layout provably generates no extra candidates at all.
///
/// The second return value is the file's own directory rendered in module form
/// (`src.mypkg` for `src/mypkg/app.py`); see [`module_path_prefix_candidates`],
/// which walks its prefixes as candidate import roots.
fn module_path_root_prefix(file: &FileInfo, sep: &str) -> Option<(String, Vec<String>)> {
    let mut segments: Vec<String> = file
        .path
        .split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect();
    if let Some(last) = segments.last_mut() {
        if let Some((stem, _ext)) = last.rsplit_once('.') {
            if !stem.is_empty() {
                *last = stem.to_string();
            }
        }
    }
    if segments.last().map(String::as_str) == Some("__init__") {
        segments.pop();
    }
    let module = file.module_path.as_str();
    let tail = segments.join(sep);
    // Everything above the file's own leaf segment: the directories an import
    // could plausibly be resolved relative to.
    let dirs: Vec<String> = segments
        .split_last()
        .map_or_else(Vec::new, |(_, rest)| rest.to_vec());
    if tail.is_empty() {
        // A root-level `__init__.py`: the whole module path is prefix.
        return (!module.is_empty()).then(|| (module.to_string(), dirs));
    }
    if module == tail {
        return None;
    }
    module
        .strip_suffix(&format!("{sep}{tail}"))
        .filter(|prefix| !prefix.is_empty())
        .map(|prefix| (prefix.to_string(), dirs))
}

/// Directories that hold a `src/` subdirectory containing at least one Python
/// file, rendered repo-relative with `/` separators (`""` is the project
/// root). Derived from the file set the builder already has — nothing here
/// touches the filesystem.
///
/// This is the evidence half of [`module_path_prefix_candidates`]'s
/// src-layout root. A `src/` layout puts the package somewhere no ancestor of
/// the importing file can reach: `tests/test_util.py` writing `from
/// pkg.util import helper` against `src/pkg/util.py` has ancestor roots
/// `<prefix>` and `<prefix>.tests`, and neither can ever spell
/// `<prefix>.src.pkg.util`. Offering `src` unconditionally would be the
/// resolver inventing a `sys.path` entry; offering it only where the file set
/// proves the directory exists keeps the cannot-invent-a-target property —
/// and the `known_modules` / `module_to_file` existence check downstream
/// still gates every candidate.
fn src_layout_dirs(files: &[FileInfo]) -> HashSet<String> {
    let mut out = HashSet::new();
    for file in files {
        if file.language != "python" {
            continue;
        }
        let segments: Vec<&str> = file.path.split('/').collect();
        // The final segment is the file name — a file *called* `src` is not a
        // source root.
        let dir_count = segments.len().saturating_sub(1);
        for (i, segment) in segments.iter().take(dir_count).enumerate() {
            if *segment == "src" {
                out.insert(segments[..i].join("/"));
            }
        }
    }
    out
}

/// Extra candidates for an absolute import whose specifier is root-relative
/// while the project's module paths carry a parser-added root prefix.
///
/// Scoped to Python deliberately: it is the one language here whose module
/// paths are derived from the source root's directory name rather than from a
/// declaration in the file (`package` in Java/Kotlin) or from the path itself
/// (TS/JS). Widening it is a change of behaviour for another language, not a
/// generalisation, so the gate is an explicit language check rather than a
/// registry predicate — `registry::uses_module_path_imports` also gates
/// JsWorkspace discovery in `builder/mod.rs` and must stay TS/JS-only.
///
/// A specifier is resolved relative to some `sys.path` entry, which the graph
/// does not record. The plausible entries are the importing file's own ancestor
/// directories — the project root (the overwhelmingly common case), a `src/`
/// layout's `src` dir, and, exactly as `python pkg/app.py` puts `sys.path[0]`,
/// the script's own directory. So the roots tried are the recovered prefix
/// extended by each leading run of the importer's directory segments,
/// shallowest first: `proj`, `proj.src`, `proj.src.mypkg` for
/// `src/mypkg/app.py`. Shallowest-first makes the project root win ties, which
/// is what keeps the common layout's answer stable.
///
/// The specifier is walked longest-first across all roots before any shortening
/// (mirroring the caller's raw walk), and it never shortens below one segment.
/// Shortening further would offer a bare root, which every module in the
/// project is a descendant of — `import functools` would then resolve to the
/// project root module. That is the manufactured-edge failure this whole
/// resolver is built to avoid.
/// Candidates for a **Rust** `use` path, rewritten into the same coordinate
/// system `file_to_module_path` stamps on files — the conversion whose absence
/// meant a `crate::` path could never match a derived `crate::src::…` module
/// path (mcp-servers report 2026-08-14, finding 1).
///
/// The importing file's own `module_path` carries everything needed:
/// * its **crate-root prefix** — the derived path up to and including the last
///   `src` segment (`crate::src`, or `crate::crates::<pkg>::src` in a
///   workspace layout). `crate::X` rewrites to `{prefix}::X`, which is exactly
///   where the target file's derived path lives. Stored module ids stay
///   untouched (globally unique across workspace members); only matching
///   changes coordinates.
/// * its **module chain** for `super::`/`self::`: `self` is the file's own
///   module; each `super` pops one segment.
///
/// Emitted longest→shortest so the caller's `find_map` lands on the deepest
/// real file: `crate::alpha::AlphaThing` tries `…::alpha::AlphaThing` (an
/// item, usually no file) before `…::alpha` (the file). No candidate is ever
/// shorter than the crate-root prefix itself — trimming past it would resolve
/// every import to the crate-root module, which is precisely the old bug's
/// output shape (every Rust IMPORTS edge landing on one Module "crate").
fn rust_import_candidates(file: &FileInfo, raw: &str) -> Vec<String> {
    if file.language != "rust" {
        return Vec::new();
    }
    let own: Vec<&str> = file.module_path.split("::").collect();
    // Crate-root prefix: up to and including the LAST `src` segment; a layout
    // with no `src` dir (rare, but `build.rs` or a flat corpus root) uses the
    // leading `crate` alone.
    let root_len = own
        .iter()
        .rposition(|seg| *seg == "src")
        .map(|i| i + 1)
        .unwrap_or(1);

    let trimmed = raw.trim();
    let rebased: Option<Vec<String>> = if let Some(rest) = trimmed.strip_prefix("crate::") {
        Some(
            own[..root_len]
                .iter()
                .map(|s| s.to_string())
                .chain(rest.split("::").map(str::to_string))
                .collect(),
        )
    } else if trimmed == "crate" {
        Some(own[..root_len].iter().map(|s| s.to_string()).collect())
    } else if trimmed.starts_with("super::")
        || trimmed == "super"
        || trimmed.starts_with("self::")
        || trimmed == "self"
    {
        // `self` = the file's own module; each `super` pops one segment.
        // Bare `self` is the anchor with nothing appended — the form
        // `RustParser::rebase_inline_mod_use` produces for `mod tests {
        // use super::*; }`, whose target is this very file.
        let mut base: Vec<String> = own.iter().map(|s| s.to_string()).collect();
        let mut rest = trimmed;
        while let Some(r) =
            rest.strip_prefix("super::")
                .or(if rest == "super" { Some("") } else { None })
        {
            if base.len() > root_len {
                base.pop();
            }
            rest = r;
        }
        if let Some(r) = rest.strip_prefix("self::") {
            rest = r;
        } else if rest == "self" {
            rest = "";
        }
        if !rest.is_empty() {
            base.extend(rest.split("::").map(str::to_string));
        }
        Some(base)
    } else {
        // A bare path (`alpha::Item` in a `pub use`, 2015-style, or an
        // external-crate name). Resolve it under the importer's own crate
        // root — a leading segment naming a real local module is a local
        // import (las-rs's `pub use api::…` shape, acceptance FN-2) — and
        // claim it EITHER WAY so it never reaches the raw walk: the walk
        // has no language anchor, and its first real-world catch was a
        // Rust `use codingest::…` resolving into a sibling PYTHON package
        // stub that shared the crate's name (acceptance FP-1, a wrong
        // edge). An external crate name that matches nothing local
        // correctly yields no edge; the workspace-sibling edge it *could*
        // mean is the Cargo-index program's job, not string matching's.
        Some(
            own[..root_len]
                .iter()
                .map(|s| s.to_string())
                .chain(trimmed.split("::").map(str::to_string))
                .collect(),
        )
    };

    let mut out = Vec::new();
    if let Some(parts) = rebased {
        // Longest→shortest, never shorter than the crate-root prefix.
        for end in (root_len..=parts.len()).rev() {
            let candidate = parts[..end].join("::");
            if !out.contains(&candidate) {
                out.push(candidate);
            }
        }
    }
    out
}

/// Candidates for a **Python** relative import (`from . import x`,
/// `from ..util import helper`), rewritten into the same coordinate system
/// `file_to_module_path` stamps on files — the conversion whose absence meant
/// every relative import produced no edge at all (mcp-servers report
/// 2026-08-14, finding 3: the parser returned `None` for `relative_import`).
///
/// The parser hands the form through verbatim, dots first (`.util`,
/// `..util.helper`); this mirrors B1's `rust_import_candidates` division of
/// labour. The importing file's own `module_path` is the anchor:
/// * one leading dot names the **containing package** — a regular module pops
///   its own leaf segment, while an `__init__` file's module path already *is*
///   its package (`file_to_module_path` popped the `__init__` segment), so it
///   pops nothing;
/// * each extra dot pops one more segment (`from ..util import helper` in
///   `pkg/sub/deeper.py` anchors at `…pkg`);
/// * the remainder is appended and the result emitted longest→shortest, so
///   `from .util import helper` tries `…pkg.util.helper` (a symbol, no file)
///   before `…pkg.util` (the file). The walk never shortens below the anchor
///   itself: the anchor is a real candidate (`from . import x` where `x` is a
///   symbol defined in `__init__.py` is a dependency on the package's
///   `__init__`), but nothing shorter can be named by a relative import.
///
/// Popping is clamped at one segment so a dot-count deeper than the file's
/// own package chain (broken at runtime anyway) cannot empty the anchor.
fn python_relative_import_candidates(file: &FileInfo, raw: &str) -> Vec<String> {
    if file.language != "python" {
        return Vec::new();
    }
    let trimmed = raw.trim();
    if !trimmed.starts_with('.') {
        return Vec::new();
    }
    let dots = trimmed.chars().take_while(|c| *c == '.').count();
    let rest = &trimmed[dots..];

    let mut base: Vec<String> = file
        .module_path
        .split('.')
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect();
    let leaf = file.path.rsplit('/').next().unwrap_or(&file.path);
    let is_init = matches!(leaf, "__init__.py" | "__init__.pyi");
    if !is_init && base.len() > 1 {
        base.pop();
    }
    for _ in 1..dots {
        if base.len() > 1 {
            base.pop();
        }
    }
    let anchor_len = base.len();
    base.extend(
        rest.split('.')
            .filter(|s| !s.is_empty())
            .map(str::to_string),
    );

    let mut out = Vec::new();
    for end in (anchor_len..=base.len()).rev() {
        let candidate = base[..end].join(".");
        if !candidate.is_empty() && !out.contains(&candidate) {
            out.push(candidate);
        }
    }
    out
}

fn module_path_prefix_candidates(
    file: &FileInfo,
    raw: &str,
    sep: &str,
    src_dirs: &HashSet<String>,
) -> Vec<String> {
    if file.language != "python" {
        return Vec::new();
    }
    let trimmed = raw.trim();
    // Relative imports (`from .util import x`) are owned by
    // `python_relative_import_candidates` and never reach this pass; the
    // guard keeps a leading dot from ever producing an empty first segment.
    if trimmed.is_empty() || trimmed.starts_with('.') {
        return Vec::new();
    }
    let Some((prefix, dirs)) = module_path_root_prefix(file, sep) else {
        return Vec::new();
    };
    let mut roots: Vec<String> = (0..=dirs.len())
        .map(|depth| {
            if depth == 0 {
                prefix.clone()
            } else {
                format!("{prefix}{sep}{}", dirs[..depth].join(sep))
            }
        })
        .collect();
    // src-layout: the package sits under `src/`, which is on `sys.path` at
    // install time but is NOT an ancestor of a test file. Offered only where
    // `src_layout_dirs` found the directory in the file set, and APPENDED
    // after every ancestor root, so a layout the existing roots already
    // resolve keeps its answer byte-for-byte.
    let src_roots: Vec<String> = (0..=dirs.len())
        .filter(|depth| src_dirs.contains(&dirs[..*depth].join("/")))
        .map(|depth| format!("{}{sep}src", roots[depth]))
        .collect();
    roots.extend(src_roots);
    let parts: Vec<&str> = trimmed.split(sep).collect();
    let mut out = Vec::new();
    for end in (1..=parts.len()).rev() {
        let specifier = parts[..end].join(sep);
        for root in &roots {
            let candidate = format!("{root}{sep}{specifier}");
            if !out.contains(&candidate) {
                out.push(candidate);
            }
        }
    }
    out
}

fn resolve_path_import(
    file: &FileInfo,
    raw: &str,
    file_to_module: &HashMap<&str, &str>,
) -> Option<(String, String)> {
    for candidate in path_import_candidates(file, raw) {
        if let Some(module) = file_to_module.get(candidate.as_str()) {
            return Some((candidate, (*module).to_string()));
        }
    }
    None
}

/// File IMPORTS Module edges — resolve each import string against known modules.
pub fn build_import_edges(
    files: &[FileInfo],
    known_modules: &HashSet<String>,
    workspace: &JsWorkspace,
) -> Vec<ImportEdge> {
    let mut out = Vec::new();
    let src_dirs = src_layout_dirs(files);
    let file_to_module: HashMap<&str, &str> = if files
        .iter()
        .any(|file| registry::uses_path_imports(&file.language))
    {
        files
            .iter()
            .map(|file| (file.path.as_str(), file.module_path.as_str()))
            .collect()
    } else {
        HashMap::new()
    };
    for f in files {
        let sep = get_separator(&f.language);
        for use_path in &f.imports {
            // C/C++ system include (`<...>` kept verbatim by the parser):
            // never resolvable to a project module or file, so it gets no
            // edge of either kind — not even via the raw prefix walk, whose
            // segment split could otherwise land `<sys/stat.h>` on a module
            // by accident. No other language emits a `<`-leading specifier.
            if use_path.starts_with('<') {
                continue;
            }
            if let Some((_, module)) = resolve_path_import(f, use_path, &file_to_module) {
                out.push(ImportEdge {
                    file_path: f.path.clone(),
                    module,
                });
                continue;
            }
            if let Some(module) = module_path_import_candidates(f, use_path, workspace)
                .into_iter()
                .find(|candidate| known_modules.contains(candidate))
            {
                out.push(ImportEdge {
                    file_path: f.path.clone(),
                    module,
                });
                continue;
            }
            let rust_candidates = rust_import_candidates(f, use_path);
            if !rust_candidates.is_empty() {
                // Same no-fallthrough rule as the file-edge pass: the raw walk
                // ends at the bare `crate` Module for every rewritable path.
                // And the same self-guard: `use self::helper` names the file's
                // own module — a dependency on yourself is not an edge.
                if let Some(module) = rust_candidates
                    .into_iter()
                    .find(|candidate| known_modules.contains(candidate))
                {
                    if module != f.module_path {
                        out.push(ImportEdge {
                            file_path: f.path.clone(),
                            module,
                        });
                    }
                }
                continue;
            }
            let relative_candidates = python_relative_import_candidates(f, use_path);
            if !relative_candidates.is_empty() {
                // A relative import is anchored to the importing file; the raw
                // prefix walk has nothing to say about it, so no fallthrough.
                // Self-guard as above: `from . import x` resolving to the
                // importer's own package `__init__` is not an edge.
                if let Some(module) = relative_candidates
                    .into_iter()
                    .find(|candidate| known_modules.contains(candidate))
                {
                    if module != f.module_path {
                        out.push(ImportEdge {
                            file_path: f.path.clone(),
                            module,
                        });
                    }
                }
                continue;
            }
            let parts: Vec<&str> = use_path.split(sep).collect();
            // How deep the Module-pass walk may trim, by language semantics:
            // * AGC `$FILE.agc` directives are literal filenames — exact or
            //   nothing. Trimming is what turned Apollo-11's two upstream
            //   typos into edges onto the parent program Module.
            // * Namespace-shaped languages (java/csharp/php/swift/go) may
            //   trim exactly ONE segment — the class/symbol name off its
            //   package. Deeper trims are what landed gson's jackson imports
            //   on ancestor Modules `com`/`com.google` (252 measured false
            //   edges). Listed explicitly, not by complement: TS/JS and the
            //   file-anchored languages keep their existing full walk, whose
            //   behavior the corpus goldens pin.
            let min_end = match f.language.as_str() {
                "agc" => parts.len(),
                "java" | "csharp" | "php" | "swift" | "go" => parts.len().saturating_sub(1).max(1),
                _ => 1,
            };
            let mut resolved = false;
            for end in (min_end..=parts.len()).rev() {
                let candidate = parts[..end].join(sep);
                // A leading-dot relative specifier this pass still sees —
                // julia's `using .Geometry`, whose dots the Python-only
                // relative route does not claim — splits to an EMPTY first
                // segment. The same guard the sibling
                // `python_relative_import_candidates` already applies: an
                // empty candidate names no module and must never be looked up.
                if candidate.is_empty() {
                    continue;
                }
                if known_modules.contains(&candidate) {
                    out.push(ImportEdge {
                        file_path: f.path.clone(),
                        module: candidate,
                    });
                    resolved = true;
                    break;
                }
            }
            if resolved {
                continue;
            }
            // Last resort: the specifier may be root-relative while this
            // project's module paths carry a parser-added root prefix. Tried
            // only here, so a layout the raw walk already resolves keeps its
            // existing answer byte-for-byte.
            if let Some(module) = module_path_prefix_candidates(f, use_path, sep, &src_dirs)
                .into_iter()
                .find(|candidate| known_modules.contains(candidate))
            {
                out.push(ImportEdge {
                    file_path: f.path.clone(),
                    module,
                });
            }
        }
    }
    out
}

/// `File -[IMPORTS]-> File` edges — resolve each import string to a project
/// file via the `module_path → file_path` reverse index.
///
/// Walks the import path from longest to shortest prefix (mirroring
/// `build_import_edges`'s module resolution) and lands on the first file
/// whose `module_path` matches a prefix candidate. Self-imports are skipped.
/// Multiple imports from the same source resolving to the same target are
/// aggregated into a single edge whose `import_count` records the multiplicity.
pub fn build_file_import_edges(
    files: &[FileInfo],
    module_to_file: &HashMap<String, String>,
    workspace: &JsWorkspace,
) -> Vec<FileImportEdge> {
    // The rows are fed directly to `add_connections`, so their order becomes
    // part of the persisted graph topology. Keep aggregation key-sorted to
    // make independently-built `.kgl` files byte-identical.
    let mut counts: BTreeMap<(String, String), i64> = BTreeMap::new();
    let src_dirs = src_layout_dirs(files);
    let file_to_module: HashMap<&str, &str> = if files
        .iter()
        .any(|file| registry::uses_path_imports(&file.language))
    {
        files
            .iter()
            .map(|file| (file.path.as_str(), file.module_path.as_str()))
            .collect()
    } else {
        HashMap::new()
    };
    for f in files {
        let sep = get_separator(&f.language);
        for use_path in &f.imports {
            // Mirror of `build_import_edges`: a `<system>` include is
            // unresolvable by definition and forms no File→File edge.
            if use_path.starts_with('<') {
                continue;
            }
            if let Some((target_file, _)) = resolve_path_import(f, use_path, &file_to_module) {
                if target_file != f.path {
                    *counts.entry((f.path.clone(), target_file)).or_insert(0) += 1;
                }
                continue;
            }
            if let Some(target_file) = module_path_import_candidates(f, use_path, workspace)
                .into_iter()
                .find_map(|candidate| module_to_file.get(&candidate))
            {
                if target_file != &f.path {
                    *counts
                        .entry((f.path.clone(), target_file.clone()))
                        .or_insert(0) += 1;
                }
                continue;
            }
            let rust_candidates = rust_import_candidates(f, use_path);
            if !rust_candidates.is_empty() {
                // A rewritten Rust path either resolves here or not at all —
                // falling through to the raw prefix walk would re-land on the
                // crate-root Module match the rewrite exists to prevent.
                if let Some(target_file) = rust_candidates
                    .into_iter()
                    .find_map(|candidate| module_to_file.get(&candidate))
                {
                    if target_file != &f.path {
                        *counts
                            .entry((f.path.clone(), target_file.clone()))
                            .or_insert(0) += 1;
                    }
                }
                continue;
            }
            let relative_candidates = python_relative_import_candidates(f, use_path);
            if !relative_candidates.is_empty() {
                // Anchored to the importer; resolves here or not at all — the
                // raw walk would split the dotted form into empty segments.
                // Self-guard as above.
                if let Some(target_file) = relative_candidates
                    .into_iter()
                    .find_map(|candidate| module_to_file.get(&candidate))
                {
                    if target_file != &f.path {
                        *counts
                            .entry((f.path.clone(), target_file.clone()))
                            .or_insert(0) += 1;
                    }
                }
                continue;
            }
            // The raw prefix walk may claim a FILE target only for languages
            // whose module coordinates are file-anchored — one module path,
            // one file. For namespace-shaped languages a module is MANY
            // files and `module_to_file` keeps one arbitrary winner, so the
            // walk manufactures wrong edges at scale: real-repo acceptance
            // (2026-08-15) measured Java 438/438 false (141 imports onto one
            // test file), PHP 146 src→tests inversions, C# 118
            // arbitrary-member picks. Python (absolute imports, Track D) and
            // AGC ($-directives) are the file-anchored proof cases — their
            // corpus goldens and real-repo sweeps hold through this gate.
            // Dart is file-anchored BY CONSTRUCTION since B4 (a normalized
            // package URI names exactly one lib/ file) and its dotted module
            // coordinates resolve here. Rust/TS/JS/C/C++ use their own routes.
            let file_anchored = matches!(f.language.as_str(), "python" | "agc" | "dart");
            let parts: Vec<&str> = use_path.split(sep).collect();
            // AGC directives are literal filenames in this pass too: exact
            // or nothing (see the Module-pass rationale).
            let file_min_end = if f.language == "agc" { parts.len() } else { 1 };
            let mut resolved = false;
            if file_anchored {
                for end in (file_min_end..=parts.len()).rev() {
                    let candidate = parts[..end].join(sep);
                    // Mirror of the Module pass: an empty candidate from a
                    // leading-dot specifier names nothing.
                    if candidate.is_empty() {
                        continue;
                    }
                    if let Some(target_file) = module_to_file.get(&candidate) {
                        if target_file != &f.path {
                            *counts
                                .entry((f.path.clone(), target_file.clone()))
                                .or_insert(0) += 1;
                        }
                        resolved = true;
                        break;
                    }
                }
            }
            if resolved {
                continue;
            }
            // Mirror of `build_import_edges`: root-prefixed candidates for a
            // root-relative specifier, tried only after the raw walk misses.
            // The self-import guard applies here exactly as above — and so
            // does the file-anchored gate: this fallback feeds the same
            // one-arbitrary-file map.
            if !file_anchored {
                continue;
            }
            if let Some(target_file) = module_path_prefix_candidates(f, use_path, sep, &src_dirs)
                .into_iter()
                .find_map(|candidate| module_to_file.get(&candidate))
            {
                if target_file != &f.path {
                    *counts
                        .entry((f.path.clone(), target_file.clone()))
                        .or_insert(0) += 1;
                }
            }
        }
    }
    counts
        .into_iter()
        .map(|((source, target), import_count)| FileImportEdge {
            source,
            target,
            import_count,
        })
        .collect()
}

/// USES_TYPE edges: scan function signature/return_type for known type names.
///
/// Returns a map from target node type → list of edges, because add_connections
/// must be called separately for each distinct target type.
pub fn build_uses_type_edges(
    functions: &[FunctionInfo],
    classes: &[ClassInfo],
    enums: &[EnumInfo],
    interfaces: &[InterfaceInfo],
) -> BTreeMap<&'static str, Vec<UsesTypeEdge>> {
    // Collect known type names → (qualified_name, node_type).
    let mut type_lookup: HashMap<String, (String, &'static str)> = HashMap::new();
    for c in classes {
        if c.name.chars().count() > 1 {
            let target = super::class_node_type(&c.kind);
            type_lookup.insert(c.name.clone(), (c.qualified_name.clone(), target));
        }
    }
    for e in enums {
        if e.name.chars().count() > 1 {
            type_lookup.insert(e.name.clone(), (e.qualified_name.clone(), "Enum"));
        }
    }
    for i in interfaces {
        if i.name.chars().count() > 1 {
            let target = match i.kind.as_str() {
                "trait" => "Trait",
                "protocol" => "Protocol",
                _ => "Interface",
            };
            type_lookup.insert(i.name.clone(), (i.qualified_name.clone(), target));
        }
    }

    if type_lookup.is_empty() {
        return BTreeMap::new();
    }

    // Flatten type names into a stable-ordered Vec so pattern IDs from
    // Aho-Corasick map back to the right (qname, node_type) tuple.
    // Longest-match-first so "MyCollection" wins over "Collection".
    let mut names: Vec<String> = type_lookup.keys().cloned().collect();
    names.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
    let pattern_meta: Vec<(String, &'static str)> = names
        .iter()
        .map(|n| {
            let (q, t) = type_lookup.get(n).unwrap();
            (q.clone(), *t)
        })
        .collect();

    let ac = match AhoCorasick::builder()
        .match_kind(MatchKind::LeftmostLongest)
        .build(&names)
    {
        Ok(ac) => ac,
        Err(_) => return BTreeMap::new(),
    };

    // Per-function scan in parallel. Scans signature/return_type/each parameter
    // separately, tracks the *set* of positions per pattern, then collapses to
    // a single position per (function, type) so we emit at most one USES_TYPE
    // edge per node pair. (The graph engine keys edges by (src, type, tgt) —
    // multiple edges with same nodes would overwrite.)
    //
    // Position bitset: bit 0 = parameter, bit 1 = return, bit 2 = signature,
    // bit 3 = receiver. Receiver is treated as an input position distinct
    // from `parameter` because `func (c *Call) lock()`-style methods consume
    // their receiver type implicitly — users querying "who consumes T" want
    // both parameter and receiver matches, but they're semantically different.
    const POS_PARAM: u8 = 1 << 0;
    const POS_RETURN: u8 = 1 << 1;
    const POS_SIGNATURE: u8 = 1 << 2;
    const POS_RECEIVER: u8 = 1 << 3;

    let per_fn: Vec<Vec<(u32, &'static str, String, &'static str)>> = functions
        .par_iter()
        .map(|fn_info| {
            // pat_id → bitset of positions seen in this function.
            let mut seen: HashMap<u32, u8> = HashMap::new();

            let scan = |text: &str, pos_bit: u8, seen: &mut HashMap<u32, u8>| {
                if text.is_empty() {
                    return;
                }
                let bytes = text.as_bytes();
                for m in ac.find_iter(text) {
                    let start = m.start();
                    let end = m.end();
                    let before_ok = start == 0
                        || !bytes[start - 1].is_ascii_alphanumeric() && bytes[start - 1] != b'_';
                    let after_ok = end == text.len()
                        || !bytes[end].is_ascii_alphanumeric() && bytes[end] != b'_';
                    if !before_ok || !after_ok {
                        continue;
                    }
                    let pat_id = m.pattern().as_usize() as u32;
                    *seen.entry(pat_id).or_insert(0) |= pos_bit;
                }
            };

            // 1. Each structured parameter type — clean per-position attribution.
            //    Receivers (Go `(c *Call)`, Rust `&self`) get POS_RECEIVER instead
            //    of POS_PARAM so the resulting edge is labeled `position="receiver"`.
            for p in &fn_info.parameters {
                if let Some(t) = &p.type_annotation {
                    let pos_bit = if p.kind == crate::models::ParameterKind::Receiver {
                        POS_RECEIVER
                    } else {
                        POS_PARAM
                    };
                    scan(t, pos_bit, &mut seen);
                }
            }
            // 2. Return type.
            if let Some(rt) = &fn_info.return_type {
                scan(rt, POS_RETURN, &mut seen);
            }
            // 3. Signature fallback — only when structured parameters are
            // empty (parser couldn't extract them). Without this, legacy
            // parses lose USES_TYPE coverage entirely. Tagged "signature"
            // so callers know it's a less-precise attribution.
            let has_param_types = fn_info
                .parameters
                .iter()
                .any(|p| p.type_annotation.is_some());
            if !has_param_types && !fn_info.signature.is_empty() {
                scan(&fn_info.signature, POS_SIGNATURE, &mut seen);
            }

            // Collapse bitset to a single label. {param, return, receiver} are
            // semantic positions; signature is the fallback. If two or more
            // semantic positions fire (e.g. receiver + return on a chaining
            // method), collapse to "both". Pure receiver-only stays "receiver".
            let mut matches: Vec<_> = seen
                .into_iter()
                .map(|(pat_id, bits)| {
                    let semantic_count = (bits & POS_PARAM != 0) as u8
                        + (bits & POS_RETURN != 0) as u8
                        + (bits & POS_RECEIVER != 0) as u8;
                    let position = if semantic_count >= 2 {
                        "both"
                    } else if bits & POS_RECEIVER != 0 {
                        "receiver"
                    } else if bits & POS_PARAM != 0 {
                        "parameter"
                    } else if bits & POS_RETURN != 0 {
                        "return"
                    } else if bits & POS_SIGNATURE != 0 {
                        "signature"
                    } else {
                        unreachable!("at least one position bit must be set");
                    };
                    let (qname, target) = &pattern_meta[pat_id as usize];
                    (pat_id, *target, qname.clone(), position)
                })
                .collect();
            // `seen` is a HashMap. Stable pattern order is required because
            // these rows are inserted into the graph in this sequence.
            matches.sort_unstable_by_key(|(pat_id, _, _, _)| *pat_id);
            matches
        })
        .collect();

    let mut by_target_type: BTreeMap<&'static str, Vec<UsesTypeEdge>> = BTreeMap::new();
    for (fn_info, matches) in functions.iter().zip(per_fn) {
        for (_pat_id, target, qname, position) in matches {
            by_target_type
                .entry(target)
                .or_default()
                .push(UsesTypeEdge {
                    function: fn_info.qualified_name.clone(),
                    type_name: qname,
                    target_node_type: target,
                    position,
                });
        }
    }

    by_target_type
}

pub struct ReferencesEdge {
    pub function: String,
    pub constant: String,
    /// Line number in the function body where the reference appears.
    pub line: u32,
    /// Optional aggregate site detail from typed parser references. Ordinary
    /// language references retain the legacy scalar `line` only.
    pub reference_lines: Option<String>,
    pub reference_count: Option<i64>,
    pub opcodes: Option<String>,
    pub accesses: Option<String>,
    pub has_read: Option<bool>,
    pub has_write: Option<bool>,
    pub has_address: Option<bool>,
}

pub struct ReferencesFnEdge {
    pub caller: String,
    pub callee: String,
    pub line: u32,
}

/// `Function -[DECORATES]-> Function` — resolved decorator-to-decoratee edges.
///
/// Per-language parsers already populate `FunctionInfo.decorators` with the
/// raw decorator strings (`"property"`, `"functools.wraps"`, `"app.route('/x')"`).
/// This pass strips any call-args, extracts the terminal segment as a bare
/// name, and resolves it against the project's Function set the same way
/// `build_call_edges` does for CALLS.
///
/// Direction: `decorator -[DECORATES]-> function` reads naturally as
/// "this decorator decorates that function". Third-party decorators
/// (`@pytest.fixture`, `@app.route` from a Flask app) that don't have a
/// matching Function node are silently dropped — the absence of an edge
/// is correct (we can't resolve into code we don't parse) and mirrors
/// `build_call_edges`'s same-file/global-fallback handling.
pub struct DecoratesEdge {
    pub decorator: String,
    pub function: String,
    /// Raw decorator string from source (e.g. `"functools.wraps"` or
    /// `"app.route('/users/{id}')"`). Preserved on the edge so callers
    /// who want the original literal don't have to reparse the
    /// Function.decorators property.
    pub decorator_name: String,
}

/// REFERENCES edges from `Function` to `Constant` — emit one row per
/// `(function, constant)` pair where the constant's terminal name
/// appears in the function body's identifier stream.
///
/// Per-language parsers populate `FunctionInfo.references` with
/// constant-style identifier candidates (the Rust parser uses
/// `SCREAMING_SNAKE_CASE` as the heuristic). This pass resolves each
/// candidate against the project's constant set and dedupes per
/// `(function, constant)` pair so a constant referenced N times in
/// one function still produces a single edge.
pub fn build_references_edges(
    functions: &[FunctionInfo],
    constants: &[ConstantInfo],
) -> Vec<ReferencesEdge> {
    if constants.is_empty() {
        return Vec::new();
    }

    // Name-keyed lookup: constant short-name → qualified_name. When two
    // constants share the same name (cross-module), we keep both —
    // emit edges to all matches. This mirrors how the type-name resolver
    // handles ambiguity (it doesn't disambiguate by import scope yet).
    let mut by_name: HashMap<&str, Vec<&str>> = HashMap::new();
    for c in constants {
        by_name
            .entry(c.name.as_str())
            .or_default()
            .push(c.qualified_name.as_str());
    }

    let mut out: Vec<ReferencesEdge> = Vec::new();
    for f in functions {
        if f.references.is_empty() {
            continue;
        }
        // Dedup per (function, constant_qname) — a function that uses
        // the same constant on three lines emits one edge.
        let mut seen: HashSet<&str> = HashSet::new();
        for (ident, line) in &f.references {
            let Some(matches) = by_name.get(ident.as_str()) else {
                continue;
            };
            for &qname in matches {
                if seen.insert(qname) {
                    out.push(ReferencesEdge {
                        function: f.qualified_name.clone(),
                        constant: qname.to_string(),
                        line: *line,
                        reference_lines: None,
                        reference_count: None,
                        opcodes: None,
                        accesses: None,
                        has_read: None,
                        has_write: None,
                        has_address: None,
                    });
                }
            }
        }
    }
    out
}

/// `Function -[REFERENCES_FN]-> Function` — bare/scoped identifiers
/// passed as arguments to higher-order calls (`iter.and_then(some_fn)`).
/// The referenced function isn't invoked at the reference site, so this
/// is intentionally a different edge type from `CALLS`. Dead-code
/// analysis can union the two: a function with `CALLS ∪ REFERENCES_FN`
/// = 0 inbound is genuinely uncalled.
///
/// Resolution mirrors `build_call_edges`'s name-keyed lookup: only
/// emit an edge when the identifier matches exactly one function in
/// the project (skip ambiguous matches to avoid noise from
/// argument-name collisions with unrelated functions) — and, per D3,
/// a closure-scoped definition is offered only to referrers in its own
/// file. `wrapper`, `inner` and `decorator` are the most common nested
/// names there are; without the gate a globally unique one of them
/// becomes a cross-file REFERENCES_FN target, which is the same
/// false-positive class D3 keeps out of CALLS.
pub fn build_references_fn_edges(functions: &[FunctionInfo]) -> Vec<ReferencesFnEdge> {
    if functions.is_empty() {
        return Vec::new();
    }
    let mut by_name: HashMap<&str, Vec<&str>> = HashMap::new();
    let mut nested_by_file: HashMap<&str, HashMap<&str, Vec<&str>>> = HashMap::new();
    for f in functions {
        let bucket = if super::call_edges::is_nested_function(f) {
            nested_by_file
                .entry(f.file_path.as_str())
                .or_default()
                .entry(f.name.as_str())
                .or_default()
        } else {
            by_name.entry(f.name.as_str()).or_default()
        };
        bucket.push(f.qualified_name.as_str());
    }

    let mut out: Vec<ReferencesFnEdge> = Vec::new();
    for f in functions {
        if f.function_refs.is_empty() {
            continue;
        }
        let caller = f.qualified_name.as_str();
        let local = nested_by_file.get(f.file_path.as_str());
        let mut seen: HashSet<&str> = HashSet::new();
        for (ident, line) in &f.function_refs {
            let mut storage: Vec<&str> = Vec::new();
            let matches = super::call_edges::merge_candidates(
                by_name.get(ident.as_str()),
                local.and_then(|m| m.get(ident.as_str())),
                &mut storage,
            );
            // Only emit on unambiguous matches — if the bare name maps
            // to multiple functions, skip rather than guess. Function
            // pointers passed as arguments don't carry receiver-type
            // info that the call-edge resolver could use to narrow.
            if matches.len() != 1 {
                continue;
            }
            let target = matches[0];
            if target == caller {
                continue;
            }
            if seen.insert(target) {
                out.push(ReferencesFnEdge {
                    caller: caller.to_string(),
                    callee: target.to_string(),
                    line: *line,
                });
            }
        }
    }
    out
}

/// `Function -[BINDS]-> Function` — Python wrapper to its underlying Rust impl.
///
/// PyO3 exposes a `#[pyclass]` Rust struct (e.g. `KnowledgeGraph`) and its
/// `#[pymethods]` block to Python. The Python class shows up in a `.pyi`
/// stub like `kglite.KnowledgeGraph.add_nodes`, while the Rust side has
/// `crate::graph::pyapi::*::KnowledgeGraph::add_nodes` (with
/// `metadata.is_pymethod == true`). Method names are 1:1 by PyO3 contract.
///
/// Closes the cross-language graph: `MATCH (py)-[:BINDS]->(rs)-[:CALLS*]->(impl)`
/// traces a request from the Python entry point down to deep Rust impl.
///
/// Resolution rules:
/// - Python side: Function whose `qualified_name` matches `<pkg>.<Class>.<method>`
///   *and* whose `is_method == true`.
/// - Rust side: Function whose name == `<method>`, owner == `<Class>`, and
///   `metadata["is_pymethod"] == true`.
/// - Skip ambiguous Rust matches (multiple pymethods with same `(Class, method)`)
///   to avoid guessing — wouldn't compile under PyO3 anyway, but be defensive.
pub struct PyO3BindsEdge {
    pub py_function: String,
    pub rust_function: String,
}

pub fn build_pyo3_binds_edges(functions: &[FunctionInfo]) -> Vec<PyO3BindsEdge> {
    // Index Rust pymethods by (parent_struct_short_name, method_short_name).
    let mut rust_idx: HashMap<(String, String), Vec<&str>> = HashMap::new();
    for f in functions {
        if !f
            .metadata
            .get("is_pymethod")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            continue;
        }
        // Derive parent struct short name from the qualified name.
        // Rust pymethod qnames look like `crate::a::b::KnowledgeGraph::add_nodes`.
        let parts: Vec<&str> = f.qualified_name.split("::").collect();
        if parts.len() < 2 {
            continue;
        }
        let parent = parts[parts.len() - 2].to_string();
        let method = parts[parts.len() - 1].to_string();
        rust_idx
            .entry((parent, method))
            .or_default()
            .push(f.qualified_name.as_str());
    }

    let mut out = Vec::new();
    for f in functions {
        // Python class methods come from `.pyi` stubs and look like
        // `kglite.KnowledgeGraph.add_nodes`. The split separator is `.`.
        if !f.qualified_name.contains('.') || !f.is_method {
            continue;
        }
        let parts: Vec<&str> = f.qualified_name.split('.').collect();
        if parts.len() < 3 {
            continue;
        }
        let py_class = parts[parts.len() - 2].to_string();
        let py_method = parts[parts.len() - 1].to_string();
        let Some(matches) = rust_idx.get(&(py_class, py_method)) else {
            continue;
        };
        if matches.len() != 1 {
            continue; // ambiguous — skip
        }
        out.push(PyO3BindsEdge {
            py_function: f.qualified_name.clone(),
            rust_function: matches[0].to_string(),
        });
    }
    out
}

/// `Function -[DECORATES]-> Function` — resolve each parsed decorator
/// string to its target function. Strips call-args (`@app.route('/x')` →
/// `app.route`) and the namespace prefix (`functools.wraps` → `wraps`)
/// before consulting a bare-name index built from every project Function.
///
/// Unambiguous matches (exactly one qualified-name candidate) emit an
/// edge. Ambiguous bare names are skipped — duplicating the call-edge
/// resolver's stance: without import-scope info we'd guess, and a wrong
/// edge is worse than a missing one for downstream queries that count
/// `WHERE (dec)-[:DECORATES]->(fn) RETURN dec.name`. Self-decoration is
/// suppressed (would only happen on malformed input).
pub fn build_decorates_edges(functions: &[FunctionInfo]) -> Vec<DecoratesEdge> {
    if functions.is_empty() {
        return Vec::new();
    }
    // bare name → list of qualified_names that share that short name.
    // D3, as in `build_call_edges` and `build_references_fn_edges`: a
    // closure-scoped definition is a candidate decorator only for functions
    // in its own file. A decorator factory's `def wrapper` is the archetypal
    // nested name, and resolving `@wrapper` in an unrelated file to it would
    // be a pure false positive.
    let mut by_name: HashMap<&str, Vec<&str>> = HashMap::new();
    let mut nested_by_file: HashMap<&str, HashMap<&str, Vec<&str>>> = HashMap::new();
    for f in functions {
        let bucket = if super::call_edges::is_nested_function(f) {
            nested_by_file
                .entry(f.file_path.as_str())
                .or_default()
                .entry(f.name.as_str())
                .or_default()
        } else {
            by_name.entry(f.name.as_str()).or_default()
        };
        bucket.push(f.qualified_name.as_str());
    }

    let mut out: Vec<DecoratesEdge> = Vec::new();
    for f in functions {
        if f.decorators.is_empty() {
            continue;
        }
        let function_qname = f.qualified_name.as_str();
        let local = nested_by_file.get(f.file_path.as_str());
        // Dedup per (decorator_qname → function) — a function with two
        // decorators that happen to resolve to the same target only
        // emits one edge. Carries the *first* raw decorator_name we
        // saw so the property remains stable.
        let mut seen: HashSet<&str> = HashSet::new();
        for raw in &f.decorators {
            // Strip call args: `app.route('/x', methods=['GET'])` → `app.route`.
            let head = raw.split('(').next().unwrap_or(raw).trim();
            if head.is_empty() {
                continue;
            }
            // Take the terminal segment after the last `.` or `::` — that's
            // the bare function name we look up. `functools.wraps` → `wraps`.
            let bare = head
                .rsplit_once("::")
                .map(|(_, t)| t)
                .or_else(|| head.rsplit_once('.').map(|(_, t)| t))
                .unwrap_or(head);
            let mut storage: Vec<&str> = Vec::new();
            let candidates = super::call_edges::merge_candidates(
                by_name.get(bare),
                local.and_then(|m| m.get(bare)),
                &mut storage,
            );
            if candidates.len() != 1 {
                continue; // ambiguous bare name — skip rather than guess
            }
            let target = candidates[0];
            if target == function_qname {
                continue; // self-decoration — defensive
            }
            if seen.insert(target) {
                out.push(DecoratesEdge {
                    decorator: target.to_string(),
                    function: function_qname.to_string(),
                    decorator_name: raw.clone(),
                });
            }
        }
    }
    out
}

/// FFI EXPOSES edges — #[pymodule] fn → each #[pyclass]/#[pyfunction] item.
pub fn build_ffi_exposes_edges(
    functions: &[FunctionInfo],
    classes: &[ClassInfo],
) -> Vec<FfiExposesEdge> {
    let pymodule_fns: Vec<&FunctionInfo> = functions
        .iter()
        .filter(|f| {
            f.metadata
                .get("is_pymodule")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        })
        .collect();
    if pymodule_fns.is_empty() {
        return Vec::new();
    }

    let pyclass_items: Vec<(&ClassInfo, String)> = classes
        .iter()
        .filter(|c| {
            c.metadata
                .get("is_pyclass")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        })
        .map(|c| {
            let py_name = c
                .metadata
                .get("py_name")
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| c.name.clone());
            (c, py_name)
        })
        .collect();

    let pyfunc_items: Vec<(&FunctionInfo, String)> = functions
        .iter()
        .filter(|f| {
            !f.is_method
                && !f
                    .metadata
                    .get("is_pymodule")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false)
                && f.metadata.get("ffi_kind").and_then(|v| v.as_str()) == Some("pyo3")
        })
        .map(|f| {
            let py_name = f
                .metadata
                .get("py_name")
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| f.name.clone());
            (f, py_name)
        })
        .collect();

    let mut out = Vec::new();
    for mod_fn in &pymodule_fns {
        for (c, py_name) in &pyclass_items {
            out.push(FfiExposesEdge {
                module_fn: mod_fn.qualified_name.clone(),
                target_qname: c.qualified_name.clone(),
                target_type: "Struct",
                py_name: py_name.clone(),
            });
        }
        for (f, py_name) in &pyfunc_items {
            out.push(FfiExposesEdge {
                module_fn: mod_fn.qualified_name.clone(),
                target_qname: f.qualified_name.clone(),
                target_type: "Function",
                py_name: py_name.clone(),
            });
        }
    }
    out
}

#[cfg(test)]
mod determinism_tests {
    use super::*;
    use crate::models::{ClassInfo, FileInfo, FunctionInfo, ParameterInfo};

    fn source_file(path: &str, module: &str, language: &str, imports: &[&str]) -> FileInfo {
        FileInfo {
            path: path.into(),
            module_path: module.into(),
            language: language.into(),
            imports: imports.iter().map(|value| (*value).to_string()).collect(),
            ..FileInfo::default()
        }
    }

    #[test]
    fn implicit_module_hierarchy_uses_parser_module_separator() {
        let files = vec![
            source_file("Foo/Bar.php", "Foo\\Bar", "php", &[]),
            source_file("Foo/Other.php", "Foo\\Bar", "php", &[]),
            source_file("src/net/client.c", "src/net/client", "c", &[]),
        ];
        let pairs: Vec<_> = build_contains_edges(&files)
            .into_iter()
            .map(|edge| (edge.parent, edge.child))
            .collect();
        assert_eq!(
            pairs,
            vec![
                ("Foo".into(), "Foo\\Bar".into()),
                ("src".into(), "src/net".into()),
                ("src/net".into(), "src/net/client".into()),
            ]
        );
    }

    #[test]
    fn path_imports_resolve_relative_root_and_extensionless_css() {
        let files = vec![
            source_file(
                "examples/main.c",
                "examples/main",
                "c",
                &["../include/header.h"],
            ),
            source_file("include/header.h", "include/header", "c", &[]),
            source_file(
                "index.html",
                "site.index",
                "html",
                &["styles/site.css?rev=1", "https://cdn.example/x.css"],
            ),
            source_file("styles/site.css", "site.site", "css", &["theme"]),
            source_file("styles/theme.css", "site.theme", "css", &[]),
        ];
        let known_modules: HashSet<_> = files.iter().map(|file| file.module_path.clone()).collect();
        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        let module_pairs: Vec<_> = module_edges
            .iter()
            .map(|edge| (edge.file_path.as_str(), edge.module.as_str()))
            .collect();
        assert_eq!(
            module_pairs,
            vec![
                ("examples/main.c", "include/header"),
                ("index.html", "site.site"),
                ("styles/site.css", "site.theme"),
            ]
        );

        let module_to_file = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let file_edges = build_file_import_edges(&files, &module_to_file, &JsWorkspace::default());
        let file_pairs: Vec<_> = file_edges
            .iter()
            .map(|edge| (edge.source.as_str(), edge.target.as_str()))
            .collect();
        assert_eq!(
            file_pairs,
            vec![
                ("examples/main.c", "include/header.h"),
                ("index.html", "styles/site.css"),
                ("styles/site.css", "styles/theme.css"),
            ]
        );
    }

    /// C/C++ `#include` resolution, asserted as exact edge sets. Mirrors the
    /// `cpp_include` corpus plus the two shapes it cannot pin without moving
    /// its golden: a root-level decoy proving the including file's own
    /// directory wins (the compiler's quoted-include order), and an angle
    /// include *colliding* with a real project file, which must still form no
    /// edge — the `<...>` marker, not luck, is what excludes it.
    #[test]
    fn cpp_quoted_includes_resolve_dir_first_and_angle_includes_never_do() {
        let files = vec![
            source_file(
                "main.cpp",
                "main",
                "cpp",
                // `<local.h>` collides with the project's own `local.h`;
                // `<vector>` collides with nothing. Neither may resolve.
                &["local.h", "util/helper.h", "<vector>", "<local.h>"],
            ),
            source_file("local.h", "local", "cpp", &[]),
            // Decoy: same basename as util/helper.h, at the root.
            source_file("helper.h", "helper", "cpp", &[]),
            source_file(
                "util/helper.cpp",
                "util/helper",
                "cpp",
                // Same-dir resolution from inside a subdirectory, and a
                // parent-relative path that must normalize the `..` away.
                &["helper.h", "../local.h"],
            ),
            source_file("util/helper.h", "util/helper", "cpp", &[]),
        ];

        let known_modules: HashSet<_> = files.iter().map(|file| file.module_path.clone()).collect();
        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        let module_pairs: Vec<_> = module_edges
            .iter()
            .map(|edge| (edge.file_path.as_str(), edge.module.as_str()))
            .collect();
        assert_eq!(
            module_pairs,
            vec![
                ("main.cpp", "local"),
                ("main.cpp", "util/helper"),
                // Dir-first: `"helper.h"` from util/ lands on util/helper,
                // not the root decoy's `helper` module.
                ("util/helper.cpp", "util/helper"),
                ("util/helper.cpp", "local"),
            ]
        );

        let module_to_file = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let file_edges = build_file_import_edges(&files, &module_to_file, &JsWorkspace::default());
        let file_pairs: Vec<_> = file_edges
            .iter()
            .map(|edge| (edge.source.as_str(), edge.target.as_str()))
            .collect();
        assert_eq!(
            file_pairs,
            vec![
                ("main.cpp", "local.h"),
                ("main.cpp", "util/helper.h"),
                ("util/helper.cpp", "local.h"),
                ("util/helper.cpp", "util/helper.h"),
            ]
        );
    }

    /// NEW-5. A leading-dot specifier the Python-only relative route does not
    /// claim — julia's `using .Geometry` — reaches the raw prefix walk, where
    /// `".Geometry".split('.')` yields an EMPTY first segment. An empty
    /// candidate names no module; looking it up is how a specifier resolves to
    /// something arbitrary. The sibling `python_relative_import_candidates`
    /// has always dropped empties; both raw walks now do too.
    ///
    /// The module sets below deliberately CONTAIN the empty name — the state
    /// that turns the missing guard from a wasted lookup into a wrong edge.
    #[test]
    fn a_leading_dot_specifier_never_resolves_to_the_empty_module() {
        let jl = vec![
            source_file("src/Main.jl", "pkg.src.Main", "julia", &[".Geometry"]),
            source_file("src/geometry.jl", "pkg.src.geometry", "julia", &[]),
        ];
        let mut known_modules: HashSet<String> =
            jl.iter().map(|file| file.module_path.clone()).collect();
        known_modules.insert(String::new());
        assert!(build_import_edges(&jl, &known_modules, &JsWorkspace::default()).is_empty());

        // The File pass mirrors the guard. Its raw walk runs only for the
        // file-anchored languages, so the same shape is asserted through one
        // of those.
        let dart = vec![
            source_file("lib/a.dart", "pkg.lib.a", "dart", &[".Geometry"]),
            source_file("lib/b.dart", "pkg.lib.b", "dart", &[]),
        ];
        let mut module_to_file: HashMap<String, String> = dart
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        module_to_file.insert(String::new(), "lib/b.dart".to_string());
        assert!(
            build_file_import_edges(&dart, &module_to_file, &JsWorkspace::default()).is_empty()
        );
    }

    /// NEW-4. A quoted `#include` is resolved by the compiler against the
    /// including file's directory and then along `-I`; the project root is
    /// never one of those places. The graph records no `-I` flags, so a miss
    /// stays a miss — the contract the cJSON reconciliation measured (0 false
    /// positives). The unconditional root fallback broke it: a same-named file
    /// anchored at the root manufactured an edge no compiler would produce.
    #[test]
    fn cpp_quoted_includes_never_fall_back_to_the_project_root() {
        let files = vec![
            // `net/socket.c` wants ITS OWN `config.h`, which does not exist.
            // The unrelated root-level `config.h` is not a substitute.
            source_file("net/socket.c", "net/socket", "c", &["config.h"]),
            source_file("config.h", "config", "c", &[]),
            source_file("gui/window.cpp", "gui/window", "cpp", &["theme.hpp"]),
            source_file("theme.hpp", "theme", "cpp", &[]),
        ];
        // The file-relative candidate is still produced — it simply does not
        // exist. What is gone is the root-anchored `config.h` / `theme.hpp`.
        assert_eq!(
            path_import_candidates(&files[0], "config.h"),
            vec!["net/config.h".to_string()]
        );
        assert_eq!(
            path_import_candidates(&files[2], "theme.hpp"),
            vec!["gui/theme.hpp".to_string()]
        );

        let known_modules: HashSet<_> = files.iter().map(|file| file.module_path.clone()).collect();
        assert!(build_import_edges(&files, &known_modules, &JsWorkspace::default()).is_empty());
        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        assert!(
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default()).is_empty()
        );

        // The fallback is dropped for C/C++ ONLY — every other path-import
        // language keeps it. A root-relative `source()` in R still resolves.
        let r_run = source_file("analysis/run.R", "analysis/run", "r", &["lib/helpers.R"]);
        assert_eq!(
            path_import_candidates(&r_run, "lib/helpers.R"),
            vec![
                "analysis/lib/helpers.R".to_string(),
                "lib/helpers.R".to_string()
            ]
        );
    }

    /// B6. A leading `/` in an HTML/CSS reference is SERVED-root-absolute, and
    /// a built site under `dist/` is served with `dist/` as `/`. The project
    /// root is still tried FIRST — so `/shared/reset.css`, which resolves
    /// there today, keeps its answer — and the linking file's own directory
    /// follows it.
    #[test]
    fn root_absolute_web_refs_also_try_the_linking_files_own_directory() {
        let html = source_file(
            "dist/index.html",
            "site.dist.index",
            "html",
            &["/_astro/app.css", "/shared/reset.css"],
        );
        assert_eq!(
            path_import_candidates(&html, "/_astro/app.css"),
            vec![
                "_astro/app.css".to_string(),
                "dist/_astro/app.css".to_string()
            ],
            "project root first, served root second"
        );

        let files = vec![
            html,
            source_file("dist/_astro/app.css", "site.dist._astro.app", "css", &[]),
            source_file("shared/reset.css", "site.shared.reset", "css", &[]),
        ];
        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let pairs: Vec<_> =
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.source, edge.target))
                .collect();
        assert_eq!(
            pairs,
            vec![
                (
                    "dist/index.html".to_string(),
                    "dist/_astro/app.css".to_string()
                ),
                (
                    "dist/index.html".to_string(),
                    "shared/reset.css".to_string()
                ),
            ]
        );

        // Web-only, and leading-'/'-only. A C include is unaffected in both
        // directions, and a RELATIVE web ref keeps exactly its old candidates.
        let c = source_file("net/socket.c", "net/socket", "c", &["/etc/config.h"]);
        assert!(path_import_candidates(&c, "/etc/config.h").is_empty());
        assert_eq!(
            path_import_candidates(&files[0], "css/app.css"),
            vec!["dist/css/app.css".to_string(), "css/app.css".to_string()]
        );
    }

    /// Julia's split import model, asserted as exact edge sets. Mirrors the
    /// `julia_basic` corpus in miniature: `include("…")` strings are FILE
    /// PATHS and must resolve through the path route (dir-relative, exact,
    /// extension carried), while `using`/`import` module references are
    /// namespace-shaped — julia is deliberately NOT in the raw prefix walk's
    /// file-anchored allowlist, so a `using Downloads` colliding with a
    /// project file `src/Downloads.jl` must form NO File→File edge, and a
    /// relative `using .Geometry` must resolve to nothing rather than
    /// something arbitrary.
    #[test]
    fn julia_includes_resolve_but_using_references_never_claim_files() {
        let files = vec![
            source_file(
                "src/Main.jl",
                "pkg.src.Main",
                "julia",
                // include, include, external-collision bait, local module ref.
                &["geometry.jl", "util.jl", "Downloads", ".Geometry"],
            ),
            source_file(
                "src/geometry.jl",
                "pkg.src.geometry",
                "julia",
                &["shapes/circle.jl"],
            ),
            source_file(
                "src/shapes/circle.jl",
                "pkg.src.shapes.circle",
                "julia",
                &[],
            ),
            source_file("src/util.jl", "pkg.src.util", "julia", &[]),
            // The bait: same name as the `using Downloads` reference.
            source_file("src/Downloads.jl", "pkg.src.Downloads", "julia", &[]),
        ];

        let known_modules: HashSet<_> = files.iter().map(|file| file.module_path.clone()).collect();
        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        let module_pairs: Vec<_> = module_edges
            .iter()
            .map(|edge| (edge.file_path.as_str(), edge.module.as_str()))
            .collect();
        // Only the includes resolve (to the included file's module); neither
        // `Downloads` nor `.Geometry` matches any known module.
        assert_eq!(
            module_pairs,
            vec![
                ("src/Main.jl", "pkg.src.geometry"),
                ("src/Main.jl", "pkg.src.util"),
                ("src/geometry.jl", "pkg.src.shapes.circle"),
            ]
        );

        let module_to_file = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let file_edges = build_file_import_edges(&files, &module_to_file, &JsWorkspace::default());
        let file_pairs: Vec<_> = file_edges
            .iter()
            .map(|edge| (edge.source.as_str(), edge.target.as_str()))
            .collect();
        assert_eq!(
            file_pairs,
            vec![
                ("src/Main.jl", "src/geometry.jl"),
                ("src/Main.jl", "src/util.jl"),
                ("src/geometry.jl", "src/shapes/circle.jl"),
            ]
        );
        // The failure this test exists to catch, stated explicitly: no edge
        // of either kind may land on the bait file.
        assert!(file_pairs.iter().all(|(_, t)| *t != "src/Downloads.jl"));
        assert!(module_pairs.iter().all(|(_, m)| *m != "pkg.src.Downloads"));
    }

    /// The TS/JS module-path branch, asserted as exact edge sets. Mirrors the
    /// `ts_monorepo` corpus in miniature so a break shows up here with a
    /// readable diff before it shows up as a moved golden digest.
    #[test]
    fn ts_relative_imports_resolve_against_the_module_set() {
        let files = vec![
            source_file(
                "packages/core/src/util.ts",
                "packages/core/src/util",
                "typescript",
                &[],
            ),
            source_file(
                "packages/core/src/nested/deep.ts",
                "packages/core/src/nested/deep",
                "typescript",
                &[],
            ),
            // A barrel: `index.ts` collapses to the directory's module path.
            source_file(
                "packages/core/src/index.ts",
                "packages/core/src",
                "typescript",
                &["./util", "./nested/deep"],
            ),
            source_file(
                "packages/core/src/consumer.ts",
                "packages/core/src/consumer",
                "typescript",
                // `./util.js` is TS NodeNext spelling for `util.ts`.
                &["./util.js"],
            ),
            // `/index`-strip case: the specifier names the barrel file, whose
            // module path has the `index` segment collapsed away.
            source_file(
                "packages/app/src/main.ts",
                "packages/app/src/main",
                "typescript",
                &["../../core/src/index"],
            ),
            // Directory specifier: matches the barrel's module path directly.
            source_file(
                "packages/app/src/widget.tsx",
                "packages/app/src/widget",
                "typescript",
                &["../../core/src"],
            ),
            // A specifier naming no real module must produce NO edge — the
            // resolver may not invent a target.
            source_file(
                "packages/app/src/dangling.ts",
                "packages/app/src/dangling",
                "typescript",
                &["./does-not-exist", "../../core/src/nope"],
            ),
            // Bare/scoped specifiers are not the relative branch's business.
            source_file(
                "packages/app/src/bare.ts",
                "packages/app/src/bare",
                "typescript",
                &["zod", "@scope/core"],
            ),
        ];
        let known_modules: HashSet<_> = files.iter().map(|file| file.module_path.clone()).collect();
        let module_pairs: Vec<_> =
            build_import_edges(&files, &known_modules, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.file_path, edge.module))
                .collect();
        assert_eq!(
            module_pairs,
            vec![
                (
                    "packages/core/src/index.ts".to_string(),
                    "packages/core/src/util".to_string()
                ),
                (
                    "packages/core/src/index.ts".to_string(),
                    "packages/core/src/nested/deep".to_string()
                ),
                (
                    "packages/core/src/consumer.ts".to_string(),
                    "packages/core/src/util".to_string()
                ),
                (
                    "packages/app/src/main.ts".to_string(),
                    "packages/core/src".to_string()
                ),
                (
                    "packages/app/src/widget.tsx".to_string(),
                    "packages/core/src".to_string()
                ),
            ]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let file_pairs: Vec<_> =
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.source, edge.target))
                .collect();
        assert_eq!(
            file_pairs,
            vec![
                (
                    "packages/app/src/main.ts".to_string(),
                    "packages/core/src/index.ts".to_string()
                ),
                (
                    "packages/app/src/widget.tsx".to_string(),
                    "packages/core/src/index.ts".to_string()
                ),
                (
                    "packages/core/src/consumer.ts".to_string(),
                    "packages/core/src/util.ts".to_string()
                ),
                (
                    "packages/core/src/index.ts".to_string(),
                    "packages/core/src/nested/deep.ts".to_string()
                ),
                (
                    "packages/core/src/index.ts".to_string(),
                    "packages/core/src/util.ts".to_string()
                ),
            ]
        );
    }

    /// Alias + workspace-package resolution, asserted as exact edge sets.
    /// Mirrors the `ts_monorepo` corpus's config layer.
    #[test]
    fn ts_alias_and_workspace_specifiers_resolve() {
        use super::super::js_workspace::TsPathsConfig;

        let files = vec![
            source_file(
                "packages/core/src/util.ts",
                "packages/core/src/util",
                "typescript",
                &[],
            ),
            // The core package's barrel: module path is the directory.
            source_file(
                "packages/core/src/index.ts",
                "packages/core/src",
                "typescript",
                &[],
            ),
            source_file(
                "packages/app/src/main.ts",
                "packages/app/src/main",
                "typescript",
                &[],
            ),
            source_file(
                "packages/app/src/consumer.ts",
                "packages/app/src/consumer",
                "typescript",
                &[
                    // tsconfig alias, governed by packages/app's own config
                    "@/main",
                    // bare workspace package -> the package's barrel
                    "@scope/core",
                    // workspace package subpath -> <pkgdir>/src/<rest>
                    "@scope/core/util",
                    // a package that does not exist
                    "@scope/nope/thing",
                    // an alias that resolves to no real module
                    "@/ghost",
                ],
            ),
        ];
        let workspace = JsWorkspace::from_raw(
            &[(
                "packages/app",
                TsPathsConfig {
                    base: "packages/app".into(),
                    paths: [("@/*".to_string(), vec!["./src/*".to_string()])]
                        .into_iter()
                        .collect(),
                },
            )],
            &[("@scope/core", "packages/core")],
        );

        let known_modules: HashSet<_> = files
            .iter()
            .map(|file| file.module_path.clone())
            // The prefix modules `build_modules` synthesizes for every path
            // segment — `<pkgdir>` is one of them, and it is what a bare
            // package specifier lands on at File→Module granularity.
            .chain(["packages/core".to_string(), "packages/app".to_string()])
            .collect();
        let module_pairs: Vec<_> = build_import_edges(&files, &known_modules, &workspace)
            .into_iter()
            .map(|edge| (edge.file_path, edge.module))
            .collect();
        assert_eq!(
            module_pairs,
            vec![
                (
                    "packages/app/src/consumer.ts".to_string(),
                    "packages/app/src/main".to_string()
                ),
                (
                    "packages/app/src/consumer.ts".to_string(),
                    "packages/core".to_string()
                ),
                (
                    "packages/app/src/consumer.ts".to_string(),
                    "packages/core/src/util".to_string()
                ),
            ]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|file| (file.module_path.clone(), file.path.clone()))
            .collect();
        let file_pairs: Vec<_> = build_file_import_edges(&files, &module_to_file, &workspace)
            .into_iter()
            .map(|edge| (edge.source, edge.target))
            .collect();
        assert_eq!(
            file_pairs,
            // File→File rows are (source, target)-sorted by construction, so
            // this order is the persisted topology, not encounter order.
            vec![
                (
                    "packages/app/src/consumer.ts".to_string(),
                    "packages/app/src/main.ts".to_string()
                ),
                (
                    "packages/app/src/consumer.ts".to_string(),
                    // `@scope/core` -> <pkgdir> is not a file's module, so the
                    // File→File probe falls through to the barrel.
                    "packages/core/src/index.ts".to_string()
                ),
                (
                    "packages/app/src/consumer.ts".to_string(),
                    "packages/core/src/util.ts".to_string()
                ),
            ]
        );
    }

    /// Without a workspace table the alias/package specifiers must resolve to
    /// nothing — proving the new edges come from the table, not from the bare
    /// prefix walk accidentally matching.
    #[test]
    fn alias_and_package_specifiers_need_the_workspace_table() {
        let files = vec![
            source_file(
                "packages/core/src/util.ts",
                "packages/core/src/util",
                "typescript",
                &[],
            ),
            source_file(
                "packages/app/src/consumer.ts",
                "packages/app/src/consumer",
                "typescript",
                &["@/main", "@scope/core/util"],
            ),
        ];
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        assert!(build_import_edges(&files, &known_modules, &JsWorkspace::default()).is_empty());
    }

    /// A plain absolute import (`from pkg.util import helper`) resolves even
    /// though the Python parser prefixes module paths with the source root's
    /// directory name while the specifier is root-relative. Asserted as exact
    /// edge sets on both edge builders.
    #[test]
    fn python_absolute_imports_resolve_across_the_root_prefix() {
        let files = vec![
            source_file("pkg/app.py", "root.pkg.app", "python", &["pkg.util"]),
            source_file("pkg/util.py", "root.pkg.util", "python", &[]),
        ];
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_pairs: Vec<_> =
            build_import_edges(&files, &known_modules, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.file_path, edge.module))
                .collect();
        assert_eq!(
            module_pairs,
            vec![("pkg/app.py".to_string(), "root.pkg.util".to_string())]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        let file_pairs: Vec<_> =
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.source, edge.target, edge.import_count))
                .collect();
        assert_eq!(
            file_pairs,
            vec![("pkg/app.py".to_string(), "pkg/util.py".to_string(), 1)]
        );
    }

    /// The prefixed candidates resolve against the real module set or not at
    /// all: an in-project module that does not exist and a stdlib module both
    /// yield nothing. No target is manufactured, and the walk never shortens
    /// far enough to land on the project root module.
    #[test]
    fn python_absolute_imports_do_not_manufacture_targets() {
        let files = vec![
            source_file(
                "pkg/app.py",
                "root.pkg.app",
                "python",
                &["pkg.nonexistent", "functools"],
            ),
            source_file("pkg/util.py", "root.pkg.util", "python", &[]),
        ];
        let mut known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        // The ancestor modules a real build materialises, including the root
        // prefix itself — the shape that makes an over-eager walk visible.
        known_modules.insert("root".into());
        known_modules.insert("root.pkg".into());

        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        assert_eq!(
            module_edges
                .iter()
                .map(|e| e.module.as_str())
                .collect::<Vec<_>>(),
            // `pkg.nonexistent` shortens to the real package `root.pkg`, the
            // same answer the raw walk gives every other language; `functools`
            // resolves to nothing at all.
            vec!["root.pkg"]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        // No file owns `root.pkg`, so the file-level pass emits nothing.
        assert!(
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default()).is_empty()
        );
    }

    /// A manifest src-layout adds TWO junk segments (`myproj.src.mypkg.util`);
    /// subtracting the file's own rendering recovers both.
    #[test]
    fn python_src_layout_imports_resolve() {
        let files = vec![
            source_file(
                "src/mypkg/app.py",
                "proj.src.mypkg.app",
                "python",
                &["mypkg.util"],
            ),
            source_file("src/mypkg/util.py", "proj.src.mypkg.util", "python", &[]),
        ];
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_pairs: Vec<_> =
            build_import_edges(&files, &known_modules, &JsWorkspace::default())
                .into_iter()
                .map(|edge| edge.module)
                .collect();
        assert_eq!(module_pairs, vec!["proj.src.mypkg.util".to_string()]);
    }

    /// Relative imports resolve against the importing file's own package —
    /// mcp-servers report 2026-08-14, finding 3. Covers the four anchor
    /// shapes: a regular module (`pkg/a.py` pops its `a` leaf), an `__init__`
    /// (its module path already is the package), a multi-dot pop
    /// (`..util.helper` from `pkg/sub/deeper.py` lands on `pkg/util.py`), and
    /// the longest→shortest walk that steps over a trailing symbol name
    /// (`.util.helper` → file `pkg/util.py`, not a phantom `helper` module).
    #[test]
    fn python_relative_imports_resolve_against_the_importers_package() {
        let files = vec![
            source_file("pkg/__init__.py", "root.pkg", "python", &[".util"]),
            source_file(
                "pkg/a.py",
                "root.pkg.a",
                "python",
                &[".util", ".util.helper", ".sub.deeper.deep_thing"],
            ),
            source_file("pkg/sub/__init__.py", "root.pkg.sub", "python", &[]),
            source_file(
                "pkg/sub/deeper.py",
                "root.pkg.sub.deeper",
                "python",
                &["..util.helper"],
            ),
            source_file("pkg/util.py", "root.pkg.util", "python", &[]),
        ];
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_pairs: Vec<_> =
            build_import_edges(&files, &known_modules, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.file_path, edge.module))
                .collect();
        assert_eq!(
            module_pairs,
            vec![
                ("pkg/__init__.py".to_string(), "root.pkg.util".to_string()),
                ("pkg/a.py".to_string(), "root.pkg.util".to_string()),
                ("pkg/a.py".to_string(), "root.pkg.util".to_string()),
                ("pkg/a.py".to_string(), "root.pkg.sub.deeper".to_string()),
                ("pkg/sub/deeper.py".to_string(), "root.pkg.util".to_string()),
            ]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        let file_pairs: Vec<_> =
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.source, edge.target, edge.import_count))
                .collect();
        assert_eq!(
            file_pairs,
            vec![
                ("pkg/__init__.py".to_string(), "pkg/util.py".to_string(), 1),
                ("pkg/a.py".to_string(), "pkg/sub/deeper.py".to_string(), 1),
                ("pkg/a.py".to_string(), "pkg/util.py".to_string(), 2),
                (
                    "pkg/sub/deeper.py".to_string(),
                    "pkg/util.py".to_string(),
                    1
                ),
            ]
        );
    }

    /// The anchor is the walk's floor and the self-guard holds there:
    /// `from . import <symbol>` inside an `__init__.py` names the importer's
    /// own package and produces no edge; the same form in a sibling module
    /// lands on the package `__init__` (a real dependency on it); and a
    /// dot-count deeper than the package chain clamps instead of emptying
    /// the anchor, resolving to nothing rather than to a manufactured root.
    #[test]
    fn python_relative_imports_floor_at_the_anchor_and_never_self_target() {
        let files = vec![
            source_file("pkg/__init__.py", "root.pkg", "python", &[".some_symbol"]),
            source_file(
                "pkg/a.py",
                "root.pkg.a",
                "python",
                &[".other_symbol", "...................nowhere"],
            ),
        ];
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_pairs: Vec<_> =
            build_import_edges(&files, &known_modules, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.file_path, edge.module))
                .collect();
        // `__init__` importing its own package: self, skipped. `a.py`'s
        // `.other_symbol` falls back to the package itself; the absurd
        // dot-run resolves to nothing.
        assert_eq!(
            module_pairs,
            vec![("pkg/a.py".to_string(), "root.pkg".to_string())]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        let file_pairs: Vec<_> =
            build_file_import_edges(&files, &module_to_file, &JsWorkspace::default())
                .into_iter()
                .map(|edge| (edge.source, edge.target, edge.import_count))
                .collect();
        assert_eq!(
            file_pairs,
            vec![("pkg/a.py".to_string(), "pkg/__init__.py".to_string(), 1)]
        );
    }

    /// The clone layout the parser already handles (`xarray/core/dataset.py` →
    /// `xarray.core.dataset`) has no root prefix to subtract, so it resolves on
    /// the raw walk alone and gains exactly nothing — no second, doubled edge.
    #[test]
    fn python_clone_layout_resolves_exactly_once() {
        let files = vec![
            source_file(
                "xarray/core/dataset.py",
                "xarray.core.dataset",
                "python",
                &["xarray.core"],
            ),
            source_file("xarray/core/__init__.py", "xarray.core", "python", &[]),
        ];
        assert!(module_path_root_prefix(&files[0], ".").is_none());
        assert!(
            module_path_prefix_candidates(&files[0], "xarray.core", ".", &HashSet::new())
                .is_empty()
        );

        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        assert_eq!(module_edges.len(), 1);
        assert_eq!(module_edges[0].module, "xarray.core");

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        let file_edges = build_file_import_edges(&files, &module_to_file, &JsWorkspace::default());
        assert_eq!(
            file_edges
                .iter()
                .map(|e| (e.source.as_str(), e.target.as_str(), e.import_count))
                .collect::<Vec<_>>(),
            vec![("xarray/core/dataset.py", "xarray/core/__init__.py", 1)]
        );
    }

    /// `src_layout_dirs` reads the FILE SET — no filesystem probing. It
    /// records the directory that *holds* a `src/`, `""` for a project-root
    /// `src/`, and only for Python files; a file merely NAMED `src` is not a
    /// source root, and a non-Python tree under `src/` is not evidence for a
    /// Python import root.
    #[test]
    fn src_layout_dirs_are_derived_from_the_file_set() {
        let files = vec![
            source_file("src/pkg/util.py", "root.src.pkg.util", "python", &[]),
            source_file(
                "apps/api/src/svc/db.py",
                "root.apps.api.src.svc.db",
                "python",
                &[],
            ),
            source_file("tests/test_util.py", "root.tests.test_util", "python", &[]),
            // A FILE called `src` — not a directory, so not a root.
            source_file("tools/src", "root.tools.src", "python", &[]),
            // A non-Python `src/` tree proves nothing about Python roots.
            source_file("web/src/app.ts", "web/src/app", "typescript", &[]),
        ];
        let dirs = src_layout_dirs(&files);
        assert_eq!(
            dirs,
            HashSet::from(["".to_string(), "apps/api".to_string()]),
            "only directories holding a Python-bearing `src/`"
        );
    }

    /// A src-layout project: `pkg` lives under `src/`, and `tests/` imports it
    /// by its absolute installed name. None of the importer's own ancestor
    /// roots (`root`, `root.tests`) can spell `root.src.pkg.util`, so before
    /// the src root the import resolved to nothing at all.
    #[test]
    fn python_src_layout_absolute_import_resolves_through_the_src_root() {
        let files = vec![
            source_file("src/pkg/__init__.py", "root.src.pkg", "python", &[]),
            source_file("src/pkg/util.py", "root.src.pkg.util", "python", &[]),
            source_file(
                "tests/test_util.py",
                "root.tests.test_util",
                "python",
                &["pkg.util"],
            ),
        ];
        let importer = &files[2];
        let src_dirs = src_layout_dirs(&files);

        // Without the evidence the candidate set is the old ancestor-only one.
        assert_eq!(
            module_path_prefix_candidates(importer, "pkg.util", ".", &HashSet::new()),
            vec![
                "root.pkg.util".to_string(),
                "root.tests.pkg.util".to_string(),
                "root.pkg".to_string(),
                "root.tests.pkg".to_string(),
            ]
        );
        // With it, `root.src` joins as a root — APPENDED after every ancestor
        // root, so each pre-existing candidate is still tried first.
        assert_eq!(
            module_path_prefix_candidates(importer, "pkg.util", ".", &src_dirs),
            vec![
                "root.pkg.util".to_string(),
                "root.tests.pkg.util".to_string(),
                "root.src.pkg.util".to_string(),
                "root.pkg".to_string(),
                "root.tests.pkg".to_string(),
                "root.src.pkg".to_string(),
            ]
        );

        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        let module_edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        assert_eq!(
            module_edges
                .iter()
                .map(|e| (e.file_path.as_str(), e.module.as_str()))
                .collect::<Vec<_>>(),
            vec![("tests/test_util.py", "root.src.pkg.util")]
        );

        let module_to_file: HashMap<String, String> = files
            .iter()
            .map(|f| (f.module_path.clone(), f.path.clone()))
            .collect();
        let file_edges = build_file_import_edges(&files, &module_to_file, &JsWorkspace::default());
        assert_eq!(
            file_edges
                .iter()
                .map(|e| (e.source.as_str(), e.target.as_str(), e.import_count))
                .collect::<Vec<_>>(),
            vec![("tests/test_util.py", "src/pkg/util.py", 1)]
        );
    }

    /// The gate is the evidence, not the spelling: the same import in a
    /// project with no `src/` directory anywhere in the file set gains no
    /// candidate and forms no edge. The resolver still cannot invent a target.
    #[test]
    fn no_src_directory_in_the_file_set_means_no_src_root() {
        let files = vec![
            source_file(
                "tests/test_util.py",
                "root.tests.test_util",
                "python",
                &["pkg.util"],
            ),
            source_file("other/pkg/util.py", "root.other.pkg.util", "python", &[]),
        ];
        let src_dirs = src_layout_dirs(&files);
        assert!(src_dirs.is_empty());
        assert!(
            !module_path_prefix_candidates(&files[0], "pkg.util", ".", &src_dirs)
                .iter()
                .any(|c| c.contains(".src.")),
            "no `src/` in the file set, no `src` root"
        );
        let known_modules: HashSet<_> = files.iter().map(|f| f.module_path.clone()).collect();
        assert!(build_import_edges(&files, &known_modules, &JsWorkspace::default()).is_empty());
    }

    /// The branch is language-gated: a relative specifier in a language that
    /// does not use module-path imports must not pick up the new behaviour.
    #[test]
    fn module_path_candidates_are_language_gated() {
        let ts = source_file("a/b.ts", "a/b", "typescript", &["./c"]);
        assert_eq!(
            module_path_import_candidates(&ts, "./c", &JsWorkspace::default()),
            vec!["a/c"]
        );

        // Python is not in the TS/JS relative-specifier branch and never joins
        // it: `./c` is not Python spelling, and relative imports are dropped at
        // parse time.
        let py = source_file("a/b.py", "root.a.b", "python", &["./c"]);
        assert!(module_path_import_candidates(&py, "./c", &JsWorkspace::default()).is_empty());
        assert!(module_path_prefix_candidates(&py, "./c", ".", &HashSet::new()).is_empty());
        // What Python DOES get is the separate root-prefix pass, on absolute
        // specifiers only: the full specifier under every candidate import root
        // (shallowest first) before any shortening, and never shortened below
        // one segment — the bare `root` is not a candidate.
        assert_eq!(
            module_path_prefix_candidates(&py, "c.d", ".", &HashSet::new()),
            vec![
                "root.c.d".to_string(),
                "root.a.c.d".to_string(),
                "root.c".to_string(),
                "root.a.c".to_string(),
            ]
        );
        // TS/JS get nothing from that pass, at any separator.
        assert!(module_path_prefix_candidates(&ts, "a/c", "/", &HashSet::new()).is_empty());

        let js = source_file("a/b.js", "a/b", "javascript", &["../d/index.js"]);
        assert_eq!(
            module_path_import_candidates(&js, "../d/index.js", &JsWorkspace::default()),
            vec!["d/index", "d"]
        );

        // Non-relative specifiers are left to the caller's prefix walk.
        assert!(module_path_import_candidates(&ts, "zod", &JsWorkspace::default()).is_empty());
        assert!(
            module_path_import_candidates(&ts, "@scope/core", &JsWorkspace::default()).is_empty()
        );
        // Escaping the project root yields nothing rather than a bogus path.
        assert!(
            module_path_import_candidates(&ts, "../../../outside", &JsWorkspace::default())
                .is_empty()
        );
    }

    #[test]
    fn swift_target_import_resolves_as_a_namespace() {
        let files = vec![source_file(
            "Sources/Helpers/Test.swift",
            "Helpers.Test",
            "swift",
            &["ArgumentParser"],
        )];
        let known_modules = HashSet::from(["ArgumentParser".to_string()]);
        let edges = build_import_edges(&files, &known_modules, &JsWorkspace::default());
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].module, "ArgumentParser");
    }

    /// Module-pass trim depth: a namespace language may shed exactly its
    /// class name; AGC directives are exact-or-nothing. Deep trims were the
    /// mechanism behind gson's 252 ancestor-Module edges and Apollo-11's
    /// typo'd directives landing on the parent program.
    #[test]
    fn module_walk_trim_depth_is_bounded_by_language_semantics() {
        let mut known = HashSet::new();
        known.insert("com".to_string());
        known.insert("com.example".to_string());
        let java = FileInfo {
            path: "src/App.java".into(),
            language: "java".into(),
            module_path: "com.example.app".into(),
            // external: only ancestors exist — one trim reaches
            // com.fasterxml.jackson.core, which is unknown → NO edge.
            imports: vec!["com.fasterxml.jackson.core.JsonFactory".into()],
            ..FileInfo::default()
        };
        let edges = build_import_edges(&[java], &known, &JsWorkspace::default());
        assert!(
            edges.is_empty(),
            "an external namespace import must not land on an ancestor Module: {:?}",
            edges.iter().map(|e| e.module.as_str()).collect::<Vec<_>>()
        );

        let mut known = HashSet::new();
        known.insert("com.example.util".to_string());
        let java_ok = FileInfo {
            path: "src/App.java".into(),
            language: "java".into(),
            module_path: "com.example.app".into(),
            imports: vec!["com.example.util.Helper".into()],
            ..FileInfo::default()
        };
        let edges = build_import_edges(&[java_ok], &known, &JsWorkspace::default());
        assert_eq!(
            edges.len(),
            1,
            "one trim to the real package must still resolve"
        );
        assert_eq!(edges[0].module, "com.example.util");

        // AGC: a typo'd directive must not fall back to the parent module.
        let mut known = HashSet::new();
        known.insert("Luminary099".to_string());
        let agc = FileInfo {
            path: "Luminary099/MAIN.agc".into(),
            language: "agc".into(),
            module_path: "Luminary099/MAIN".into(),
            imports: vec!["Luminary099/TRIM_GIMBAL_CNTROL_SYSTEM".into()],
            ..FileInfo::default()
        };
        let edges = build_import_edges(&[agc], &known, &JsWorkspace::default());
        assert!(
            edges.is_empty(),
            "a typo'd AGC directive must resolve to nothing, not the parent program"
        );
    }

    /// Namespace-shaped languages must not receive File→File edges from
    /// the raw prefix walk: a package/namespace is MANY files, the reverse
    /// map keeps one arbitrary winner, and real-repo acceptance measured the
    /// result (Java 438/438 false edges). Python keeps the walk — its module
    /// paths are file-anchored and Track D's real-repo sweep was 0 FP / 0 FN.
    #[test]
    fn namespace_languages_get_no_file_edges_from_the_raw_walk() {
        let java = FileInfo {
            path: "src/App.java".into(),
            language: "java".into(),
            module_path: "com.example.app".into(),
            imports: vec!["com.example.util.Helper".into()],
            ..FileInfo::default()
        };
        // The bait: the namespace resolves — to an arbitrary member file.
        let module_to_file = HashMap::from([(
            "com.example.util".to_string(),
            "src/util/Unrelated.java".to_string(),
        )]);
        let edges = build_file_import_edges(&[java], &module_to_file, &JsWorkspace::default());
        assert!(
            edges.is_empty(),
            "a namespace hit must not become a file edge (got {} edge(s), first: {} -> {})",
            edges.len(),
            edges.first().map(|e| e.source.as_str()).unwrap_or("-"),
            edges.first().map(|e| e.target.as_str()).unwrap_or("-"),
        );

        let python = FileInfo {
            path: "pkg/app.py".into(),
            language: "python".into(),
            module_path: "proj.pkg.app".into(),
            imports: vec!["proj.pkg.util".into()],
            ..FileInfo::default()
        };
        let module_to_file =
            HashMap::from([("proj.pkg.util".to_string(), "pkg/util.py".to_string())]);
        let edges = build_file_import_edges(&[python], &module_to_file, &JsWorkspace::default());
        assert_eq!(
            edges.len(),
            1,
            "file-anchored python must keep its raw-walk resolution"
        );
    }

    /// Acceptance FP-1/FN-2 (2026-08-15): a Rust bare path resolves under
    /// the importer's own crate root — and NEVER falls through to the raw
    /// walk, whose first real-world catch was a Rust `use codingest::…`
    /// landing on a sibling Python package stub of the same name.
    #[test]
    fn rust_bare_path_resolves_locally_and_never_falls_through() {
        use crate::parsers::rust_lang::RustParser;
        use std::path::Path;
        let root = Path::new("");
        let mp = |p: &str| RustParser::file_to_module_path(Path::new(p), root);
        let importer = FileInfo {
            path: "src/lib.rs".into(),
            language: "rust".into(),
            module_path: mp("src/lib.rs"),
            imports: vec![
                "api::Reader".into(),      // local module — must resolve (FN-2)
                "codingest::build".into(), // external crate name — no edge (FP-1)
            ],
            ..FileInfo::default()
        };
        let module_to_file = HashMap::from([
            (mp("src/api.rs"), "src/api.rs".to_string()),
            // the collision bait: a same-named NON-rust module in the map
            (
                "codingest".to_string(),
                "codingest/__init__.pyi".to_string(),
            ),
        ]);
        let edges = build_file_import_edges(&[importer], &module_to_file, &JsWorkspace::default());
        let pairs: Vec<_> = edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
            .collect();
        assert_eq!(
            pairs,
            vec![("src/lib.rs", "src/api.rs")],
            "bare local path must resolve; external-crate name must produce \
             no edge even when a same-named foreign module exists"
        );
    }

    #[test]
    fn file_import_edges_are_key_sorted() {
        // RE-FOUNDED 2026-08-15 (program B1). The old fixture hand-built
        // `module_to_file` as `"crate::alpha" -> "src/alpha.rs"` — a shape the
        // real builder never emitted (it derives `crate::src::alpha`), so the
        // test was green while production resolved nothing (mcp-servers
        // report, finding 8). Every module path below now comes from the REAL
        // `RustParser::file_to_module_path`, so this fixture cannot drift from
        // production again: if the derivation changes, this test sees it.
        use crate::parsers::rust_lang::RustParser;
        use std::path::Path;
        let root = Path::new("");
        let mp = |p: &str| RustParser::file_to_module_path(Path::new(p), root);
        let source = FileInfo {
            path: "src/lib.rs".into(),
            language: "rust".into(),
            module_path: mp("src/lib.rs"),
            imports: vec!["crate::beta".into(), "crate::alpha".into()],
            ..FileInfo::default()
        };
        let module_to_file = HashMap::from([
            (mp("src/alpha.rs"), "src/alpha.rs".to_string()),
            (mp("src/beta.rs"), "src/beta.rs".to_string()),
        ]);

        let edges = build_file_import_edges(&[source], &module_to_file, &JsWorkspace::default());
        let pairs: Vec<_> = edges
            .iter()
            .map(|edge| (edge.source.as_str(), edge.target.as_str()))
            .collect();
        assert_eq!(
            pairs,
            vec![
                ("src/lib.rs", "src/alpha.rs"),
                ("src/lib.rs", "src/beta.rs"),
            ]
        );
    }

    #[test]
    fn uses_type_edges_are_pattern_sorted() {
        let function = FunctionInfo {
            qualified_name: "crate::combine".into(),
            parameters: vec![
                ParameterInfo {
                    type_annotation: Some("Beta".into()),
                    ..ParameterInfo::default()
                },
                ParameterInfo {
                    type_annotation: Some("Alpha".into()),
                    ..ParameterInfo::default()
                },
            ],
            ..FunctionInfo::default()
        };
        let classes = vec![
            ClassInfo {
                name: "Beta".into(),
                qualified_name: "crate::beta::Beta".into(),
                kind: "struct".into(),
                ..ClassInfo::default()
            },
            ClassInfo {
                name: "Alpha".into(),
                qualified_name: "crate::alpha::Alpha".into(),
                kind: "struct".into(),
                ..ClassInfo::default()
            },
        ];

        let edges = build_uses_type_edges(&[function], &classes, &[], &[]);
        let targets: Vec<_> = edges["Struct"]
            .iter()
            .map(|edge| edge.type_name.as_str())
            .collect();
        assert_eq!(targets, vec!["crate::alpha::Alpha", "crate::beta::Beta"]);
    }
}

/// D3 is a property of every bare-name index over the function population,
/// not just `build_call_edges`. These two builders resolve a bare name to a
/// *globally unique* function, which is exactly the shape a nested `wrapper`
/// / `inner` / `decorator` satisfies — so before the gate they minted
/// cross-file edges into closure-scoped definitions that no caller in that
/// file can even see.
#[cfg(test)]
mod nested_visibility_tests {
    use super::*;
    use crate::models::FunctionInfo;

    fn top_level(qname: &str, file: &str, name: &str) -> FunctionInfo {
        FunctionInfo {
            name: name.into(),
            qualified_name: qname.into(),
            file_path: file.into(),
            ..FunctionInfo::default()
        }
    }

    fn nested(qname: &str, file: &str, name: &str) -> FunctionInfo {
        let mut f = top_level(qname, file, name);
        f.metadata
            .insert("nesting_depth".into(), serde_json::json!(1));
        f
    }

    #[test]
    fn a_nested_definition_is_not_a_cross_file_references_fn_target() {
        let mut referrer = top_level("b.consume", "b.py", "consume");
        referrer.function_refs = vec![("wrapper".into(), 4)];
        let functions = vec![referrer, nested("a.deco.wrapper", "a.py", "wrapper")];
        assert!(
            build_references_fn_edges(&functions).is_empty(),
            "a closure-scoped `wrapper` in another file is not referable"
        );
    }

    #[test]
    fn a_nested_definition_is_a_same_file_references_fn_target() {
        let mut referrer = top_level("a.deco", "a.py", "deco");
        referrer.function_refs = vec![("wrapper".into(), 4)];
        let functions = vec![referrer, nested("a.deco.wrapper", "a.py", "wrapper")];
        let pairs: Vec<_> = build_references_fn_edges(&functions)
            .into_iter()
            .map(|e| (e.caller, e.callee))
            .collect();
        assert_eq!(pairs, vec![("a.deco".into(), "a.deco.wrapper".into())]);
    }

    #[test]
    fn a_nested_definition_is_not_a_cross_file_decorator() {
        let mut decorated = top_level("b.handler", "b.py", "handler");
        decorated.decorators = vec!["wrapper".into()];
        let functions = vec![decorated, nested("a.deco.wrapper", "a.py", "wrapper")];
        assert!(
            build_decorates_edges(&functions).is_empty(),
            "a closure-scoped `wrapper` in another file cannot decorate"
        );
    }

    #[test]
    fn a_nested_definition_still_decorates_within_its_file() {
        let mut decorated = top_level("a.handler", "a.py", "handler");
        decorated.decorators = vec!["wrapper".into()];
        let functions = vec![decorated, nested("a.deco.wrapper", "a.py", "wrapper")];
        let pairs: Vec<_> = build_decorates_edges(&functions)
            .into_iter()
            .map(|e| (e.decorator, e.function))
            .collect();
        assert_eq!(pairs, vec![("a.deco.wrapper".into(), "a.handler".into())]);
    }

    /// The gate is by visibility, not by deletion: a nested name must not
    /// shadow an identically named top-level export for a cross-file
    /// referrer, nor make it look ambiguous.
    #[test]
    fn a_nested_name_does_not_disturb_the_global_index() {
        let mut referrer = top_level("b.consume", "b.py", "consume");
        referrer.function_refs = vec![("wrapper".into(), 4)];
        let functions = vec![
            referrer,
            top_level("c.wrapper", "c.py", "wrapper"),
            nested("a.deco.wrapper", "a.py", "wrapper"),
        ];
        let pairs: Vec<_> = build_references_fn_edges(&functions)
            .into_iter()
            .map(|e| (e.caller, e.callee))
            .collect();
        assert_eq!(pairs, vec![("b.consume".into(), "c.wrapper".into())]);
    }
}