agentstatedeveloper-python 1.4.9

Python language adapter for AgentStateDeveloper (tree-sitter-python)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
//! Python language adapter for AgentStateDeveloper.
//!
//! Implements [`LanguageAdapter`](agentstatedeveloper_core::LanguageAdapter)
//! on top of `tree-sitter-python`. Parses module-level functions, methods,
//! and classes, and runs a small substring-based effect inference pass.

use std::collections::{HashMap, HashSet};

use agentstatedeveloper_core::adapter::{
    CallEdge, DynamicDispatchHint, LanguageAdapter, ParsedSymbol, UnresolvedCall, WorkspaceSymbols,
};
use agentstatedeveloper_core::cross_service::{
    DetectedEndpoint, Direction, ServiceEndpoint, Transport, http_contract, pubsub_contract,
};
use agentstatedeveloper_core::dataflow::DetectedDataFlow;
use agentstatedeveloper_core::error::{AsdError, Result};
use agentstatedeveloper_core::schema::{Effect, EffectCategory, SymbolKind};
use serde_json::json;
use tree_sitter::{Node, Parser};

/// Python language adapter.
#[derive(Debug, Default, Clone, Copy)]
pub struct PythonAdapter;

impl PythonAdapter {
    pub fn new() -> Self {
        Self
    }
}

impl LanguageAdapter for PythonAdapter {
    fn language(&self) -> &str {
        "python"
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["py"]
    }

    fn parse_symbols(&self, file: &str, source: &str) -> Result<Vec<ParsedSymbol>> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .map_err(|e| AsdError::Parse(format!("failed to set python language: {e}")))?;

        let src_bytes = source.as_bytes();
        let tree = parser
            .parse(src_bytes, None)
            .ok_or_else(|| AsdError::Parse(format!("failed to parse {file}")))?;

        let module_prefix = module_qname_prefix(file);
        let root = tree.root_node();
        let mut out = Vec::new();
        walk(root, src_bytes, &module_prefix, &[], &mut out);
        Ok(out)
    }

    fn infer_effects(&self, _source: &str, symbol: &ParsedSymbol) -> Vec<Effect> {
        infer_effects_from_body(&symbol.body)
    }

    fn infer_service_endpoints(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
    ) -> Vec<DetectedEndpoint> {
        infer_service_endpoints_in_python(file, source, symbols)
    }

    fn resolve_endpoint_prefixes(
        &self,
        files: &[(String, String)],
        endpoints: &mut Vec<ServiceEndpoint>,
    ) {
        resolve_python_endpoint_prefixes(files, endpoints);
    }

    fn extract_dataflow(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
        _workspace: &WorkspaceSymbols,
    ) -> Vec<DetectedDataFlow> {
        infer_dataflow_in_python(file, source, symbols)
    }

    fn extract_call_edges(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
        workspace: &WorkspaceSymbols,
    ) -> Vec<CallEdge> {
        extract_call_edges_impl(file, source, symbols, workspace)
    }

    fn scan_dynamic_dispatch(&self, file: &str, source: &str) -> Vec<DynamicDispatchHint> {
        scan_dynamic_dispatch_in_python(file, source)
    }

    fn report_unresolved_calls(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
        workspace: &WorkspaceSymbols,
    ) -> Vec<UnresolvedCall> {
        report_unresolved_calls_in_python(file, source, symbols, workspace)
    }
}

/// Plan L t-006: walk a Python file's call nodes and report any that
/// the static resolver couldn't bind to a workspace qname. Includes
/// stdlib + third-party + dynamic — callers should treat the count
/// as "static-resolution gap," not "bug list."
///
/// Filters out a small known-stdlib allowlist so the output isn't
/// drowned in `print` / `len` / `range` calls. Anything else gets
/// reported, including third-party calls (which are useful to see —
/// they tell you "these dependencies sit outside the indexed scope").
pub fn report_unresolved_calls_in_python(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
    workspace: &WorkspaceSymbols,
) -> Vec<UnresolvedCall> {
    use std::collections::HashSet;

    // The Python builtins that aren't worth surfacing as gaps —
    // every program calls them and they're never going to resolve to
    // a workspace symbol. Keep this list tight; when in doubt, leave
    // the call OUT of the allowlist so it surfaces.
    let stdlib_allowlist: HashSet<&str> = [
        "print",
        "len",
        "range",
        "type",
        "isinstance",
        "super",
        "hasattr",
        "getattr",
        "setattr",
        "delattr",
        "callable",
        "iter",
        "next",
        "list",
        "dict",
        "set",
        "tuple",
        "str",
        "int",
        "float",
        "bool",
        "bytes",
        "bytearray",
        "frozenset",
        "min",
        "max",
        "sum",
        "abs",
        "round",
        "sorted",
        "reversed",
        "enumerate",
        "zip",
        "map",
        "filter",
        "any",
        "all",
        "open",
        "repr",
        "hash",
        "id",
        "vars",
        "dir",
        "format",
        "input",
        "ord",
        "chr",
        "hex",
        "oct",
        "bin",
        "pow",
        "divmod",
        "compile",
        "eval",
        "exec",
    ]
    .into_iter()
    .collect();

    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_python::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }
    let module_prefix = module_qname_prefix(file);
    let src_bytes = source.as_bytes();

    // Rebuild the same resolution context the call-graph walker uses.
    let mut by_simple: HashMap<String, String> = HashMap::new();
    let mut known: HashSet<&str> = HashSet::new();
    for sym in symbols {
        known.insert(sym.qname.as_str());
        if let Some(simple) = sym.qname.rsplit_once('.').map(|(_, s)| s) {
            by_simple.insert(simple.to_string(), sym.qname.clone());
        }
    }
    let imports = parse_imports(source, &mut parser, &module_prefix);

    let tree = match parser.parse(src_bytes, None) {
        Some(t) => t,
        None => return Vec::new(),
    };

    let mut line_starts: Vec<usize> = vec![0];
    for (i, b) in src_bytes.iter().enumerate() {
        if *b == b'\n' {
            line_starts.push(i + 1);
        }
    }
    let line_of = |off: usize| -> u32 {
        match line_starts.binary_search(&off) {
            Ok(i) => i as u32 + 1,
            Err(i) => i.max(1) as u32,
        }
    };

    let mut out = Vec::new();
    walk_unresolved_calls(
        tree.root_node(),
        src_bytes,
        &module_prefix,
        &by_simple,
        &known,
        &imports,
        workspace,
        &stdlib_allowlist,
        file,
        &line_of,
        &mut out,
    );
    out
}

#[allow(clippy::too_many_arguments)]
fn walk_unresolved_calls(
    node: Node<'_>,
    src: &[u8],
    module_prefix: &str,
    by_simple: &HashMap<String, String>,
    known: &HashSet<&str>,
    imports: &HashMap<String, ImportBinding>,
    workspace: &WorkspaceSymbols,
    stdlib_allowlist: &std::collections::HashSet<&str>,
    file: &str,
    line_of: &dyn Fn(usize) -> u32,
    out: &mut Vec<UnresolvedCall>,
) {
    if node.kind() == "call" {
        if let Some(func) = node.child_by_field_name("function") {
            let callee_text = node_text(func, src).unwrap_or_default();
            let resolved = resolve_callee(
                func,
                src,
                module_prefix,
                by_simple,
                known,
                imports,
                workspace,
                None, // enclosing_class — best-effort; we don't replay class scope
            );
            if resolved.is_none() {
                // Filter out trivial stdlib calls. Match on the FIRST
                // segment for chained attribute access (`foo.bar` →
                // check `foo` against the allowlist; this catches
                // `str.format`-style chains incidentally).
                let head = callee_text.split('.').next().unwrap_or(&callee_text).trim();
                if !stdlib_allowlist.contains(head) {
                    out.push(UnresolvedCall {
                        file: file.to_string(),
                        line: line_of(func.start_byte()),
                        callee_text: callee_text.trim().to_string(),
                    });
                }
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_unresolved_calls(
            child,
            src,
            module_prefix,
            by_simple,
            known,
            imports,
            workspace,
            stdlib_allowlist,
            file,
            line_of,
            out,
        );
    }
}

/// Walk path components and return the tail after the first `src` segment.
/// Falls back to the full path for projects without that convention.
///
/// Examples:
/// - `src/mypackage/module.py`  → `mypackage/module.py`
/// - `lib/src/utils.py`         → `utils.py`
/// - `mypackage/module.py`      → `mypackage/module.py`  (no `src`, unchanged)
fn strip_src_prefix(path: &str) -> &str {
    let mut offset = 0usize;
    for part in path.split('/') {
        if part == "src" {
            let after = offset + part.len() + 1;
            if after < path.len() {
                return &path[after..];
            }
        }
        offset += part.len() + 1;
    }
    path
}

/// Derive the dotted module prefix for a file path.
///
/// Anchors at the `src/` boundary for src-layout projects (PEP 517/518)
/// so the prefix is stable regardless of which directory `asd index` was
/// invoked from. Falls back to the full relative path for flat layouts.
///
/// `src/mypackage/module.py`        -> `mypackage.module`
/// `packages/mypkg/src/__init__.py` -> `mypkg.__init__`  (package-name disambiguates)
/// `foo/bar.py`                     -> `foo.bar`          (no src segment, fallback)
/// `./foo/bar.py`                   -> `foo.bar`
/// `bar.py`                         -> `bar`
fn module_qname_prefix(file: &str) -> String {
    let mut s = file;
    if let Some(stripped) = s.strip_prefix("./") {
        s = stripped;
    }
    let s = s.strip_suffix(".py").unwrap_or(s);
    let after_src = strip_src_prefix(s);
    // __init__.py at the root of a package's src/ dir is not unique across packages.
    // Prepend the package directory name (the segment before `src/`).
    if after_src == "__init__" {
        if let Some(pkg_name) = package_name_from_path(s) {
            return format!("{}.__init__", pkg_name.replace('-', "_"));
        }
    }
    after_src.replace('\\', "/").replace('/', ".")
}

/// Extract the package name from a path like `packages/my-pkg/src/__init__.py`
/// by finding the segment immediately before a `src` component.
fn package_name_from_path(path: &str) -> Option<&str> {
    let parts: Vec<&str> = path.split('/').collect();
    for (i, &part) in parts.iter().enumerate() {
        if part == "src" && i > 0 {
            return Some(parts[i - 1]);
        }
    }
    None
}

/// Recursive descent over the Python tree. We enumerate:
/// - `function_definition` -> Function or Method depending on scope
/// - `class_definition` -> Class
///
/// Nested functions get their enclosing function/class names in their qname.
fn walk(
    node: Node<'_>,
    src: &[u8],
    module_prefix: &str,
    scope: &[(String, ScopeKind)],
    out: &mut Vec<ParsedSymbol>,
) {
    let kind = node.kind();
    match kind {
        "function_definition" => {
            let name = node_field_text(node, "name", src).unwrap_or_else(|| "<anon>".to_string());
            let qname = build_qname(module_prefix, scope, &name);
            let symbol_kind = if scope.last().map(|s| s.1) == Some(ScopeKind::Class) {
                SymbolKind::Method
            } else {
                SymbolKind::Function
            };
            let signature = extract_function_signature(node, src, &name);
            out.push(make_parsed_symbol(node, src, qname, symbol_kind, signature));

            // Recurse into the body with this function pushed on the scope.
            let mut new_scope = scope.to_vec();
            new_scope.push((name, ScopeKind::Function));
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for child in body.children(&mut cursor) {
                    walk(child, src, module_prefix, &new_scope, out);
                }
            }
        }
        "class_definition" => {
            let name = node_field_text(node, "name", src).unwrap_or_else(|| "<anon>".to_string());
            let qname = build_qname(module_prefix, scope, &name);
            let signature = extract_class_signature(node, src, &name);
            out.push(make_parsed_symbol(
                node,
                src,
                qname,
                SymbolKind::Class,
                signature,
            ));

            let mut new_scope = scope.to_vec();
            new_scope.push((name, ScopeKind::Class));
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for child in body.children(&mut cursor) {
                    walk(child, src, module_prefix, &new_scope, out);
                }
            }
        }
        _ => {
            // Descend into other containers (module root, decorated_definition, etc.).
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                walk(child, src, module_prefix, scope, out);
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ScopeKind {
    Class,
    Function,
}

fn build_qname(module_prefix: &str, scope: &[(String, ScopeKind)], name: &str) -> String {
    let mut parts = Vec::with_capacity(scope.len() + 2);
    if !module_prefix.is_empty() {
        parts.push(module_prefix.to_string());
    }
    for (s, _) in scope {
        parts.push(s.clone());
    }
    parts.push(name.to_string());
    parts.join(".")
}

fn node_field_text(node: Node<'_>, field: &str, src: &[u8]) -> Option<String> {
    node.child_by_field_name(field)
        .and_then(|n| node_text(n, src))
}

fn node_text(node: Node<'_>, src: &[u8]) -> Option<String> {
    src.get(node.byte_range())
        .map(|b| String::from_utf8_lossy(b).into_owned())
}

fn make_parsed_symbol(
    node: Node<'_>,
    src: &[u8],
    qname: String,
    kind: SymbolKind,
    signature: Option<String>,
) -> ParsedSymbol {
    let start = node.start_position();
    let end = node.end_position();
    let body = node_text(node, src).unwrap_or_default();
    let doc = extract_python_doc(&body);
    ParsedSymbol {
        qname,
        kind,
        // tree-sitter positions are 0-based; ASD wants 1-based.
        start_line: (start.row as u32) + 1,
        start_col: (start.column as u32) + 1,
        end_line: (end.row as u32) + 1,
        end_col: (end.column as u32) + 1,
        body,
        signature,
        doc,
    }
}

fn extract_python_doc(body: &str) -> Option<String> {
    for quote in &[r#"""""#, "'''"] {
        if let Some(start) = body.find(quote) {
            let after = start + quote.len();
            if let Some(end_rel) = body[after..].find(quote) {
                let content = &body[after..after + end_rel];
                let cleaned = content
                    .lines()
                    .map(|l| l.trim())
                    .filter(|l| !l.is_empty())
                    .collect::<Vec<_>>()
                    .join(" ");
                if !cleaned.is_empty() {
                    return Some(truncate_doc(&cleaned));
                }
            }
        }
    }
    None
}

fn extract_function_signature(node: Node<'_>, src: &[u8], name: &str) -> Option<String> {
    let params = node.child_by_field_name("parameters")?;
    let params_text = node_text(params, src)?;
    Some(format!("def {name}{params_text}"))
}

fn extract_class_signature(node: Node<'_>, src: &[u8], name: &str) -> Option<String> {
    // `superclasses` is optional in the grammar.
    if let Some(sup) = node.child_by_field_name("superclasses") {
        if let Some(sup_text) = node_text(sup, src) {
            return Some(format!("class {name}{sup_text}"));
        }
    }
    Some(format!("class {name}"))
}

// -----------------------------------------------------------------------------
// Cross-service endpoint detection (t-002)
//
// Heuristic, line-based, matching the substring style of effect inference.
// Inbound: FastAPI/Flask route decorators. Outbound: requests/httpx client
// calls with a literal URL. Non-literal URLs (f-strings, variables) are skipped
// — without a literal we can't form a contract that would match a server route.
// Session/client-object calls and Django url routing are known coverage gaps.
// -----------------------------------------------------------------------------

const HTTP_VERBS: &[&str] = &["get", "post", "put", "patch", "delete", "head", "options"];

fn infer_service_endpoints_in_python(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
) -> Vec<DetectedEndpoint> {
    let mut out = Vec::new();
    // Plan Q t-004: resolve each router's prefix once per file so route contracts
    // are the full runtime path, not just the decorator arg. Covers same-file
    // `APIRouter(prefix=)` / `Blueprint(url_prefix=)` and same-file
    // `include_router`/`register_blueprint` mounts. (Cross-file/nested mount
    // trees are increment 2.)
    let router_prefixes = collect_router_prefixes(source);
    for (idx, raw) in source.lines().enumerate() {
        let line_no = (idx + 1) as u32;
        let line = raw.trim();

        // Inbound: route decorators (@app.get("/x"), @router.get("/x"), @bp.route(...)).
        let receiver_prefix = route_receiver(line).and_then(|r| router_prefixes.get(&r).cloned());
        for (method, path, conf) in parse_route_decorator(line) {
            if let Some(owner) = owner_for_decorator(symbols, line_no) {
                let full = match &receiver_prefix {
                    Some(pfx) => join_route(pfx, &path),
                    None => path.clone(),
                };
                out.push(DetectedEndpoint {
                    transport: Transport::Http,
                    direction: Direction::Inbound,
                    contract: http_contract(&method, &full),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: conf,
                    note: None,
                });
            }
        }

        // Outbound: requests/httpx client calls with a literal URL.
        for (method, url, conf) in parse_client_calls(line) {
            if let Some(owner) = owner_for_body_line(symbols, line_no) {
                out.push(DetectedEndpoint {
                    transport: Transport::Http,
                    direction: Direction::Outbound,
                    contract: http_contract(&method, &url),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: conf,
                    note: None,
                });
            }
        }

        // Pub-sub (Celery): a @shared_task/@app.task def is a listener; the task
        // function's name is the contract. `name.delay()/.apply_async()` is the
        // emit. The two match by task name.
        if is_celery_task_decorator(line) {
            if let Some(owner) = owner_for_decorator(symbols, line_no) {
                let task = simple_name(&owner.qname);
                out.push(DetectedEndpoint {
                    transport: Transport::PubSub,
                    direction: Direction::Inbound,
                    contract: pubsub_contract(task),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: 0.85,
                    note: Some("celery task".into()),
                });
            }
        }
        for task in parse_celery_emits(line) {
            if let Some(owner) = owner_for_body_line(symbols, line_no) {
                out.push(DetectedEndpoint {
                    transport: Transport::PubSub,
                    direction: Direction::Outbound,
                    contract: pubsub_contract(&task),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: 0.6,
                    note: Some("celery emit".into()),
                });
            }
        }
    }
    out
}

/// Last dotted segment of a qname (`a.b.process_order` → `process_order`).
fn simple_name(qname: &str) -> &str {
    qname.rsplit('.').next().unwrap_or(qname)
}

/// `@shared_task`, `@app.task`, `@celery.task(bind=True)`, `@<x>.task` — Celery
/// task definitions (which act as message consumers).
fn is_celery_task_decorator(line: &str) -> bool {
    let Some(body) = line.strip_prefix('@') else {
        return false;
    };
    let head = body.split('(').next().unwrap_or(body).trim();
    head == "shared_task" || head == "task" || head.ends_with(".task")
}

/// Task names invoked via `<name>.delay(` / `<name>.apply_async(`.
fn parse_celery_emits(line: &str) -> Vec<String> {
    let mut out = Vec::new();
    for suffix in [".delay(", ".apply_async("] {
        let mut from = 0;
        while let Some(rel) = line[from..].find(suffix) {
            let pos = from + rel;
            from = pos + suffix.len();
            let name: String = line[..pos]
                .chars()
                .rev()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            if !name.is_empty() && !out.contains(&name) {
                out.push(name);
            }
        }
    }
    out
}

/// The symbol whose line range contains `line`, innermost (largest start_line)
/// when nested (class + method).
fn owner_for_body_line(symbols: &[ParsedSymbol], line: u32) -> Option<&ParsedSymbol> {
    symbols
        .iter()
        .filter(|s| s.start_line <= line && line <= s.end_line)
        .max_by_key(|s| s.start_line)
}

/// The symbol a decorator on `line` decorates: the symbol containing the line,
/// else the nearest `def` starting just below it (decorators stack within a few
/// lines of the definition).
fn owner_for_decorator(symbols: &[ParsedSymbol], line: u32) -> Option<&ParsedSymbol> {
    if let Some(s) = owner_for_body_line(symbols, line) {
        return Some(s);
    }
    symbols
        .iter()
        .filter(|s| s.start_line > line && s.start_line <= line + 6)
        .min_by_key(|s| s.start_line)
}

/// Parse a route decorator line into `(METHOD, path, confidence)` pairs.
/// `@x.get("/p")` → one entry; `@x.route("/p", methods=["GET","POST"])` → one
/// per method (default GET when `methods=` is absent).
fn parse_route_decorator(line: &str) -> Vec<(String, String, f64)> {
    let Some(rest) = line.strip_prefix('@') else {
        return Vec::new();
    };
    // Need an `obj.attr(` shape.
    let Some(paren) = rest.find('(') else {
        return Vec::new();
    };
    let callee = rest[..paren].trim();
    let args = &rest[paren + 1..];
    let Some(attr) = callee.rsplit('.').next() else {
        return Vec::new();
    };
    // The attribute must be on something (a.b), not a bare `@decorator(`.
    if !callee.contains('.') {
        return Vec::new();
    }
    let attr = attr.trim();

    if HTTP_VERBS.contains(&attr) {
        if let Some(path) = first_string_arg(args) {
            return vec![(attr.to_uppercase(), path, 0.95)];
        }
        return Vec::new();
    }
    if attr == "route" {
        let Some(path) = first_string_arg(args) else {
            return Vec::new();
        };
        let methods = methods_kwarg(args);
        let methods = if methods.is_empty() {
            vec!["GET".to_string()]
        } else {
            methods
        };
        return methods
            .into_iter()
            .map(|m| (m, path.clone(), 0.9))
            .collect();
    }
    Vec::new()
}

// ── router-prefix resolution (Plan Q t-004) ────────────────────────────────

/// The receiver variable of a route decorator: `@router.get("/x")` → `router`,
/// `@app.route(...)` → `app`. `None` for bare `@decorator(` shapes.
fn route_receiver(line: &str) -> Option<String> {
    let rest = line.trim().strip_prefix('@')?;
    let paren = rest.find('(')?;
    let callee = rest[..paren].trim();
    let dot = callee.rfind('.')?;
    let recv = callee[..dot].trim();
    if recv.is_empty() {
        None
    } else {
        Some(recv.to_string())
    }
}

/// Map every router/blueprint variable in a file to its resolved prefix, from
/// same-file `APIRouter(prefix=)` / `Blueprint(url_prefix=)` definitions and
/// same-file `include_router(child, prefix=)` / `register_blueprint(child,
/// url_prefix=)` mounts. The mount prefix precedes the router's own prefix
/// (FastAPI/Flask ordering).
fn collect_router_prefixes(source: &str) -> HashMap<String, String> {
    let mut self_p: HashMap<String, String> = HashMap::new();
    let mut mount_p: HashMap<String, String> = HashMap::new();
    for raw in source.lines() {
        let line = raw.trim();
        // `<var> = APIRouter(... prefix="P" ...)` / `Blueprint(... url_prefix="P" ...)`.
        if let Some(eq) = line.find('=') {
            let var = line[..eq].trim();
            if is_ident(var) {
                let rhs = &line[eq + 1..];
                if let Some(a) = ctor_args(rhs, "APIRouter") {
                    if let Some(p) = string_kwarg(a, "prefix") {
                        self_p.insert(var.to_string(), p);
                    }
                } else if let Some(a) = ctor_args(rhs, "Blueprint") {
                    if let Some(p) = string_kwarg(a, "url_prefix") {
                        self_p.insert(var.to_string(), p);
                    }
                }
            }
        }
        // `<recv>.include_router(<child>, prefix="Q")` / `register_blueprint(<child>, url_prefix="Q")`.
        if let Some(a) = ctor_args(line, "include_router") {
            if let (Some(child), Some(q)) = (first_ident_arg(a), string_kwarg(a, "prefix")) {
                mount_p.entry(child).or_insert(q);
            }
        }
        if let Some(a) = ctor_args(line, "register_blueprint") {
            if let (Some(child), Some(q)) = (first_ident_arg(a), string_kwarg(a, "url_prefix")) {
                mount_p.entry(child).or_insert(q);
            }
        }
    }
    let keys: HashSet<String> = self_p.keys().chain(mount_p.keys()).cloned().collect();
    let mut out = HashMap::new();
    for k in keys {
        let full = normalize_prefix(&format!(
            "{}{}",
            mount_p.get(&k).map(String::as_str).unwrap_or(""),
            self_p.get(&k).map(String::as_str).unwrap_or("")
        ));
        if !full.is_empty() {
            out.insert(k, full);
        }
    }
    out
}

/// Args slice after `Name(` in `s`, respecting an identifier boundary before
/// `Name` (so `APIRouter` is not matched inside `MyAPIRouter`).
fn ctor_args<'a>(s: &'a str, name: &str) -> Option<&'a str> {
    let mut from = 0;
    while let Some(rel) = s[from..].find(name) {
        let pos = from + rel;
        from = pos + name.len();
        let before_ok = pos == 0
            || !s[..pos]
                .chars()
                .next_back()
                .map(|c| c.is_alphanumeric() || c == '_')
                .unwrap_or(false);
        let after = s[pos + name.len()..].trim_start();
        if before_ok {
            if let Some(args) = after.strip_prefix('(') {
                return Some(args);
            }
        }
    }
    None
}

/// A `key="value"` string kwarg, respecting an identifier boundary before `key`
/// (so `prefix` is not matched inside `url_prefix`).
fn string_kwarg(args: &str, key: &str) -> Option<String> {
    let mut from = 0;
    while let Some(rel) = args[from..].find(key) {
        let pos = from + rel;
        from = pos + key.len();
        let before_ok = pos == 0
            || !args[..pos]
                .chars()
                .next_back()
                .map(|c| c.is_alphanumeric() || c == '_')
                .unwrap_or(false);
        if !before_ok {
            continue;
        }
        let after = args[pos + key.len()..].trim_start();
        if let Some(after) = after.strip_prefix('=') {
            if let Some(s) = read_string_literal(after.trim_start()) {
                return Some(s);
            }
        }
    }
    None
}

/// First positional argument if it's a (possibly dotted) identifier.
fn first_ident_arg(args: &str) -> Option<String> {
    let s = args.trim_start();
    let end = s
        .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.'))
        .unwrap_or(s.len());
    let id = &s[..end];
    if id.is_empty() || id.starts_with('.') {
        None
    } else {
        Some(id.to_string())
    }
}

fn is_ident(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// Normalize a prefix: leading slash, no trailing slash, collapse `//`.
fn normalize_prefix(p: &str) -> String {
    let p = p.trim();
    if p.is_empty() {
        return String::new();
    }
    let mut s = p.to_string();
    while s.contains("//") {
        s = s.replace("//", "/");
    }
    if !s.starts_with('/') {
        s.insert(0, '/');
    }
    while s.len() > 1 && s.ends_with('/') {
        s.pop();
    }
    s
}

/// Join a resolved router prefix with a decorator path into the full route path.
fn join_route(prefix: &str, path: &str) -> String {
    if prefix.is_empty() {
        return path.to_string();
    }
    let p = prefix.trim_end_matches('/');
    if path.is_empty() || path == "/" {
        return p.to_string();
    }
    if path.starts_with('/') {
        format!("{p}{path}")
    } else {
        format!("{p}/{path}")
    }
}

// ── project-level mount-tree resolution (Plan Q t-004b/c) ───────────────────

/// Rewrite each inbound HTTP endpoint's contract to the full runtime path by
/// resolving the cross-file, nested router-mount chain
/// (`app.include_router(api, prefix="/api")` → `api.include_router(calc,
/// prefix="/calc")` → `@calc.get("/x")` = `/api/calc/x`). Routers are keyed by
/// their **qname** (`module.var`), so an `include_router(alias)` mount connects
/// to the aliased router's routes even across files and generic `router` names
/// (t-004c: aliases resolved via `from … import … as …`).
fn resolve_python_endpoint_prefixes(
    files: &[(String, String)],
    endpoints: &mut Vec<ServiceEndpoint>,
) {
    // Per-file module qname + import alias map (local name -> imported qname).
    let module_by_path: HashMap<&str, String> = files
        .iter()
        .map(|(p, _)| (p.as_str(), module_qname_prefix(p)))
        .collect();
    let imports_by_path: HashMap<&str, HashMap<String, String>> = files
        .iter()
        .map(|(p, s)| {
            (
                p.as_str(),
                file_import_qnames(s, &module_by_path[p.as_str()]),
            )
        })
        .collect();

    // Global router tables keyed by qname (globally unique — no ambiguity).
    let mut self_by_q: HashMap<String, String> = HashMap::new();
    let mut parent_of: HashMap<String, Vec<(String, String)>> = HashMap::new(); // child -> mounts
    let mut app_qs: HashSet<String> = HashSet::new();
    let mut known: HashSet<String> = HashSet::new();

    for (path, source) in files {
        let module = &module_by_path[path.as_str()];
        let imports = &imports_by_path[path.as_str()];
        for raw in source.lines() {
            let line = raw.trim();
            // `<var> = APIRouter(...)` / `Blueprint(...)` / `FastAPI()` / `Flask()`.
            if let Some(eq) = line.find('=') {
                let var = line[..eq].trim();
                if is_ident(var) {
                    let rhs = &line[eq + 1..];
                    let q = qualify(module, var); // a definition binds locally
                    if let Some(a) = ctor_args(rhs, "APIRouter") {
                        if let Some(p) = string_kwarg(a, "prefix") {
                            self_by_q.insert(q.clone(), normalize_prefix(&p));
                        }
                        known.insert(q);
                    } else if let Some(a) = ctor_args(rhs, "Blueprint") {
                        if let Some(p) = string_kwarg(a, "url_prefix") {
                            self_by_q.insert(q.clone(), normalize_prefix(&p));
                        }
                        known.insert(q);
                    } else if ctor_args(rhs, "FastAPI").is_some()
                        || ctor_args(rhs, "Flask").is_some()
                    {
                        app_qs.insert(q.clone());
                        known.insert(q);
                    }
                }
            }
            // `<parent>.include_router(<child>, prefix="Q")` / register_blueprint.
            for (fname, pkey) in [
                ("include_router", "prefix"),
                ("register_blueprint", "url_prefix"),
            ] {
                if let Some(a) = ctor_args(line, fname) {
                    if let (Some(child), Some(parent)) =
                        (first_ident_arg(a), mount_receiver(line, fname))
                    {
                        let m = string_kwarg(a, pkey)
                            .map(|s| normalize_prefix(&s))
                            .unwrap_or_default();
                        let child_q = resolve_name(&child, module, imports);
                        let parent_q = resolve_name(&parent, module, imports);
                        known.insert(child_q.clone());
                        known.insert(parent_q.clone());
                        let mounts = parent_of.entry(child_q).or_default();
                        let edge = (parent_q, m);
                        if !mounts.contains(&edge) {
                            mounts.push(edge);
                        }
                    }
                }
            }
        }
    }

    let mut cache: HashMap<String, Option<Vec<String>>> = HashMap::new();
    let mut local: HashMap<String, HashMap<String, String>> = HashMap::new();
    let src_by_path: HashMap<&str, &str> = files
        .iter()
        .map(|(p, s)| (p.as_str(), s.as_str()))
        .collect();
    // Routes served under >1 mount prefix produce extra endpoints (t-004d),
    // appended after the in-place rewrite pass.
    let mut additions: Vec<ServiceEndpoint> = Vec::new();

    for ep in endpoints.iter_mut() {
        if ep.transport != Transport::Http || ep.direction != Direction::Inbound {
            continue;
        }
        let Some(src) = src_by_path.get(ep.file.as_str()).copied() else {
            continue;
        };
        let Some(module) = module_by_path.get(ep.file.as_str()) else {
            continue;
        };
        let imports = &imports_by_path[ep.file.as_str()];
        let Some(line) = src.lines().nth(ep.line.saturating_sub(1) as usize) else {
            continue;
        };
        let line = line.trim();
        let Some(recv) = route_receiver(line) else {
            continue;
        };
        let decos = parse_route_decorator(line);
        let Some((_, raw_path, _)) = decos.first() else {
            continue;
        };
        let method = ep
            .contract
            .strip_prefix("http:")
            .and_then(|s| s.split(' ').next())
            .unwrap_or("GET")
            .to_string();

        let recv_q = resolve_name(&recv, module, imports);
        // Global mount-tree resolution for known routers; else file-local (t-004a).
        // A router mounted at N prefixes yields N full paths (t-004d).
        let prefixes: Vec<String> = if known.contains(&recv_q) {
            resolve_full_q(&recv_q, &self_by_q, &parent_of, &app_qs, &mut cache)
        } else {
            vec![
                local
                    .entry(ep.file.clone())
                    .or_insert_with(|| collect_router_prefixes(src))
                    .get(&recv)
                    .cloned()
                    .unwrap_or_default(),
            ]
        };
        let mut paths: Vec<String> = prefixes.iter().map(|p| join_route(p, raw_path)).collect();
        paths.sort();
        paths.dedup();
        if paths.is_empty() {
            paths.push(raw_path.clone());
        }
        ep.contract = http_contract(&method, &paths[0]);
        for extra in paths.iter().skip(1) {
            let mut dup = ep.clone();
            dup.contract = http_contract(&method, extra);
            additions.push(dup);
        }
    }
    endpoints.extend(additions);
}

/// `module.name`, or just `name` when module is empty.
fn qualify(module: &str, name: &str) -> String {
    if module.is_empty() {
        name.to_string()
    } else {
        format!("{module}.{name}")
    }
}

/// Resolve a local name to a qname: an imported alias resolves to the imported
/// symbol's qname; otherwise it's `module.name` (a local binding).
fn resolve_name(name: &str, module: &str, imports: &HashMap<String, String>) -> String {
    imports
        .get(name)
        .cloned()
        .unwrap_or_else(|| qualify(module, name))
}

/// Per-file import map: local name -> imported symbol qname, for
/// `from <mod> import a, b as c` (relative or absolute). Best-effort single-line
/// — enough to connect router aliases. Reuses [`resolve_relative_import`].
fn file_import_qnames(source: &str, module: &str) -> HashMap<String, String> {
    let mut out = HashMap::new();
    for raw in source.lines() {
        let line = raw.trim();
        let Some(rest) = line.strip_prefix("from ") else {
            continue;
        };
        let Some(imp) = rest.find(" import ") else {
            continue;
        };
        let module_raw = rest[..imp].trim();
        let resolved = if module_raw.starts_with('.') {
            match resolve_relative_import(module, module_raw) {
                Some(m) => m,
                None => continue,
            }
        } else {
            module_raw.to_string()
        };
        let names = rest[imp + " import ".len()..]
            .trim()
            .trim_start_matches('(')
            .trim_end_matches(')')
            .trim_end_matches('\\')
            .trim();
        for part in names.split(',') {
            let part = part.trim();
            if part.is_empty() || part == "*" {
                continue;
            }
            let (orig, local) = match part.split_once(" as ") {
                Some((o, l)) => (o.trim(), l.trim()),
                None => (part, part),
            };
            if is_ident(orig) && is_ident(local) {
                out.insert(local.to_string(), qualify(&resolved, orig));
            }
        }
    }
    out
}

/// Full mount-resolved prefixes for a router qname. A router included at several
/// mounts (or via a parent that is) yields several full paths — one per mount
/// path through the tree (`full(parent) + mount + self`). Memoized, cycle-guarded
/// (a cycle contributes no path), and deduped.
fn resolve_full_q(
    q: &str,
    self_by_q: &HashMap<String, String>,
    parent_of: &HashMap<String, Vec<(String, String)>>,
    app_qs: &HashSet<String>,
    cache: &mut HashMap<String, Option<Vec<String>>>,
) -> Vec<String> {
    if let Some(c) = cache.get(q) {
        return c.clone().unwrap_or_default(); // in-progress (None) → empty = cycle break
    }
    cache.insert(q.to_string(), None); // mark visiting
    let self_p = self_by_q.get(q).cloned().unwrap_or_default();
    let mut out: Vec<String> = if app_qs.contains(q) {
        vec![self_p.clone()]
    } else if let Some(parents) = parent_of.get(q) {
        let mut acc = Vec::new();
        for (parent, mount) in parents {
            let mut pfulls = resolve_full_q(parent, self_by_q, parent_of, app_qs, cache);
            if pfulls.is_empty() {
                pfulls.push(String::new());
            }
            for pf in pfulls {
                acc.push(normalize_prefix(&format!("{pf}{mount}{self_p}")));
            }
        }
        if acc.is_empty() {
            vec![self_p.clone()]
        } else {
            acc
        }
    } else {
        vec![self_p.clone()]
    };
    out.sort();
    out.dedup();
    cache.insert(q.to_string(), Some(out.clone()));
    out
}

/// The receiver before `.<fname>(` — `api_router.include_router(...)` →
/// `api_router`, `app.register_blueprint(...)` → `app`.
fn mount_receiver(line: &str, fname: &str) -> Option<String> {
    let pos = line.find(fname)?;
    let before = line[..pos].trim_end().strip_suffix('.')?;
    let start = before
        .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
        .map(|i| i + 1)
        .unwrap_or(0);
    let recv = &before[start..];
    if recv.is_empty() {
        None
    } else {
        Some(recv.to_string())
    }
}

/// Parse requests/httpx client calls on a line into `(METHOD, url, confidence)`.
/// Handles `requests.get("u")`, `httpx.post('u')`, and
/// `requests.request("POST", "u")`. Only literal URLs are returned.
fn parse_client_calls(line: &str) -> Vec<(String, String, f64)> {
    let mut out = Vec::new();
    for module in ["requests.", "httpx."] {
        let mut search_from = 0usize;
        while let Some(rel) = line[search_from..].find(module) {
            let start = search_from + rel;
            // Must be a call boundary, not a substring of a longer identifier.
            let preceded_ok = start == 0
                || !line[..start]
                    .chars()
                    .next_back()
                    .map(|c| c.is_alphanumeric() || c == '_' || c == '.')
                    .unwrap_or(false);
            let after = &line[start + module.len()..];
            search_from = start + module.len();
            if !preceded_ok {
                continue;
            }
            let Some(paren) = after.find('(') else {
                continue;
            };
            let attr = after[..paren].trim();
            let args = &after[paren + 1..];
            if HTTP_VERBS.contains(&attr) {
                if let Some(url) = first_string_arg(args) {
                    out.push((attr.to_uppercase(), url, 0.9));
                }
            } else if attr == "request" {
                // requests.request("POST", "url", ...)
                let parts = first_two_string_args(args);
                if let (Some(method), Some(url)) = parts {
                    out.push((method.to_uppercase(), url, 0.9));
                }
            }
        }
    }
    out
}

/// Extract the first string literal from an argument list. Returns `None` for
/// f-strings / b-strings (dynamic) so we never form a bogus contract; r-strings
/// (raw) are accepted. Leading whitespace and a `url=` kwarg name are skipped.
fn first_string_arg(args: &str) -> Option<String> {
    let s = args.trim_start();
    // Skip a leading `name=` kwarg label (e.g. url=, path=).
    let s = match s.find('=') {
        Some(eq)
            if s[..eq].chars().all(|c| c.is_alphanumeric() || c == '_')
                && !s[..eq].is_empty()
                && s.as_bytes().get(eq + 1) != Some(&b'=') =>
        {
            s[eq + 1..].trim_start()
        }
        _ => s,
    };
    read_string_literal(s)
}

fn first_two_string_args(args: &str) -> (Option<String>, Option<String>) {
    let first = read_string_literal(args.trim_start());
    // Advance past the first literal + comma, then read the second.
    let Some(comma) = args.find(',') else {
        return (first, None);
    };
    let second = first_string_arg(&args[comma + 1..]);
    (first, second)
}

/// Read a leading string literal, rejecting f/b-string prefixes. Returns the
/// inner text (without quotes).
fn read_string_literal(s: &str) -> Option<String> {
    let bytes = s.as_bytes();
    let mut i = 0;
    // Allow a raw-string prefix `r`/`R`; reject f/b (dynamic / bytes).
    if let Some(&c) = bytes.first() {
        match c {
            b'r' | b'R' => i = 1,
            b'f' | b'F' | b'b' | b'B' => return None,
            _ => {}
        }
    }
    let quote = *bytes.get(i)?;
    if quote != b'"' && quote != b'\'' {
        return None;
    }
    let inner = &s[i + 1..];
    let end = inner.find(quote as char)?;
    Some(inner[..end].to_string())
}

/// Parse a `methods=["GET", "POST"]` (or `=('GET',)`) kwarg into upper-cased
/// method names.
fn methods_kwarg(args: &str) -> Vec<String> {
    let Some(pos) = args.find("methods") else {
        return Vec::new();
    };
    let after = &args[pos + "methods".len()..];
    let after = after.trim_start();
    let Some(after) = after.strip_prefix('=') else {
        return Vec::new();
    };
    // Take up to the closing bracket/paren of the list.
    let after = after.trim_start();
    let open = after.chars().next();
    let close = match open {
        Some('[') => ']',
        Some('(') => ')',
        _ => return Vec::new(),
    };
    let Some(end) = after.find(close) else {
        return Vec::new();
    };
    let list = &after[1..end];
    let mut out = Vec::new();
    let mut rest = list;
    while let Some(m) = read_string_literal(rest.trim_start()) {
        out.push(m.to_uppercase());
        match rest.find(',') {
            Some(c) => rest = &rest[c + 1..],
            None => break,
        }
    }
    out
}

// -----------------------------------------------------------------------------
// Data-flow detection (t-002 slice 4)
//
// Conservative arg→param detection: only same-file function calls whose
// arguments are ALL bare identifiers. High precision over recall — cross-file
// resolution, method calls, literals, and kwargs are deliberately skipped
// (tracked as follow-up). The pipeline maps each arg position to the callee's
// parameter name from its signature.
// -----------------------------------------------------------------------------

fn infer_dataflow_in_python(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
) -> Vec<DetectedDataFlow> {
    use std::collections::HashMap;

    // Same-file function simple-name → qname. A name defined more than once is
    // ambiguous (mapped to None) and never resolved.
    let mut name_to_qname: HashMap<&str, Option<String>> = HashMap::new();
    for s in symbols {
        if s.kind == SymbolKind::Function {
            let last = s.qname.rsplit('.').next().unwrap_or(s.qname.as_str());
            name_to_qname
                .entry(last)
                .and_modify(|e| *e = None)
                .or_insert_with(|| Some(s.qname.clone()));
        }
    }

    let mut out = Vec::new();
    for (idx, raw) in source.lines().enumerate() {
        let line_no = (idx + 1) as u32;
        for (callee_name, args) in simple_calls(raw) {
            let Some(Some(callee_qname)) = name_to_qname.get(callee_name.as_str()) else {
                continue;
            };
            let Some(owner) = owner_for_body_line(symbols, line_no) else {
                continue;
            };
            for (i, arg) in args.iter().enumerate() {
                out.push(DetectedDataFlow {
                    caller_qname: owner.qname.clone(),
                    callee_qname: callee_qname.clone(),
                    arg_index: i,
                    arg: arg.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: 0.7,
                });
            }
        }
    }
    out
}

/// Find `name(args)` call sites on a line where the callee is a bare function
/// (not a method) and every argument is a simple identifier. Returns
/// `(callee_name, [arg_idents])`.
fn simple_calls(line: &str) -> Vec<(String, Vec<String>)> {
    let t = line.trim_start();
    if t.starts_with("def ")
        || t.starts_with("async def ")
        || t.starts_with("class ")
        || t.starts_with('@')
        || t.starts_with('#')
    {
        return Vec::new();
    }
    let chars: Vec<char> = line.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '(' {
            // Capture the identifier ending right before '('.
            let mut start = i;
            while start > 0 && (chars[start - 1].is_alphanumeric() || chars[start - 1] == '_') {
                start -= 1;
            }
            let is_method = start > 0 && chars[start - 1] == '.';
            let name: String = chars[start..i].iter().collect();
            let valid = name
                .chars()
                .next()
                .is_some_and(|c| c.is_alphabetic() || c == '_');
            if !is_method && valid {
                if let Some(close) = matching_close(&chars, i) {
                    let inner: String = chars[i + 1..close].iter().collect();
                    if let Some(args) = simple_args(&inner) {
                        out.push((name, args));
                    }
                    i = close;
                }
            }
        }
        i += 1;
    }
    out
}

fn matching_close(chars: &[char], open: usize) -> Option<usize> {
    let mut depth = 0i32;
    let mut i = open;
    while i < chars.len() {
        match chars[i] {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// `Some(args)` only when every comma-separated argument is a bare identifier
/// (no nested calls, literals, operators, or kwargs) and there is at least one.
fn simple_args(inner: &str) -> Option<Vec<String>> {
    let inner = inner.trim();
    if inner.is_empty() {
        return None;
    }
    let mut args = Vec::new();
    for part in inner.split(',') {
        let p = part.trim();
        let is_ident = p
            .chars()
            .next()
            .is_some_and(|c| c.is_alphabetic() || c == '_')
            && p.chars().all(|c| c.is_alphanumeric() || c == '_');
        if !is_ident || matches!(p, "True" | "False" | "None" | "self" | "cls") {
            return None;
        }
        args.push(p.to_string());
    }
    Some(args)
}

// -----------------------------------------------------------------------------
// Effect inference
// -----------------------------------------------------------------------------

fn infer_effects_from_body(body: &str) -> Vec<Effect> {
    let mut effects: Vec<Effect> = Vec::new();

    // Plan L t-002: detection runs on a copy with comments + string
    // literals masked to spaces, so an effect-like substring inside a
    // `# os.open(…)` comment or a `"os.open(…)"` literal no longer
    // produces a false-positive inference. We preserve byte length so
    // all the existing offset-based slicing (`&body[args_start..]`,
    // notes, path extraction) continues to read from the original
    // source — the mask only suppresses *matches*, not data.
    let masked = mask_comments_and_literals(body);
    let scan = masked.as_str();

    // open(...) -> IoFsRead (+ IoFsWrite when mode contains 'w' or 'a')
    for call_site in find_calls(scan, "open(") {
        let args = &body[call_site.args_start..call_site.args_end];
        effects.push(Effect {
            effect: EffectCategory::IoFsRead,
            qualifiers: extract_open_path(args)
                .map(|p| json!({ "paths": [p] }))
                .unwrap_or(serde_json::Value::Null),
            note: Some(trim_note(
                &body[call_site.call_start..call_site.args_end + 1],
            )),
            ..Default::default()
        });
        if mentions_write_mode(args) {
            effects.push(Effect {
                effect: EffectCategory::IoFsWrite,
                qualifiers: extract_open_path(args)
                    .map(|p| json!({ "paths": [p] }))
                    .unwrap_or(serde_json::Value::Null),
                note: Some(trim_note(
                    &body[call_site.call_start..call_site.args_end + 1],
                )),
                ..Default::default()
            });
        }
    }

    // print(...) / sys.stdout / sys.stderr / logging.* / log.* / logger.* -> Log
    let log_needles = [
        "print(",
        "sys.stdout",
        "sys.stderr",
        "logging.debug",
        "logging.info",
        "logging.warning",
        "logging.warn",
        "logging.error",
        "logging.critical",
        "logging.exception",
        "log.debug",
        "log.info",
        "log.warning",
        "log.warn",
        "log.error",
        "log.critical",
        "log.exception",
        "logger.debug",
        "logger.info",
        "logger.warning",
        "logger.warn",
        "logger.error",
        "logger.critical",
        "logger.exception",
    ];
    if log_needles.iter().any(|n| scan.contains(n)) {
        let note = first_matching_line(scan, body, &log_needles);
        effects.push(Effect {
            effect: EffectCategory::Log,
            qualifiers: serde_json::Value::Null,
            note,
            ..Default::default()
        });
    }

    // Database cursor/conn/db.execute(...) / .fetchone() / .commit()  -> IoDb*
    // Heuristic: inspect the SQL-like first arg of `.execute(` to decide
    // read vs write. Common names: db, conn, cursor, cur, session, c.
    let db_receivers = [
        "db.execute(",
        "conn.execute(",
        "cursor.execute(",
        "cur.execute(",
        "session.execute(",
        "c.execute(",
        "self.db.execute(",
        "self.conn.execute(",
    ];
    let mut seen_db_read = false;
    let mut seen_db_write = false;
    for recv in db_receivers {
        for call_site in find_calls(scan, recv) {
            let args = &body[call_site.args_start..call_site.args_end];
            let sql = args.trim_start_matches(|c: char| {
                c.is_whitespace() || c == '"' || c == '\'' || c == 'f' || c == 'r' || c == 'b'
            });
            let upper: String = sql.chars().take(16).collect::<String>().to_uppercase();
            let is_write = upper.starts_with("INSERT")
                || upper.starts_with("UPDATE")
                || upper.starts_with("DELETE")
                || upper.starts_with("REPLACE")
                || upper.starts_with("CREATE")
                || upper.starts_with("DROP")
                || upper.starts_with("ALTER")
                || upper.starts_with("TRUNCATE");
            let is_read = upper.starts_with("SELECT")
                || upper.starts_with("WITH")
                || upper.starts_with("SHOW");
            let note = Some(trim_note(
                &body[call_site.call_start..call_site.args_end + 1],
            ));
            if is_write && !seen_db_write {
                effects.push(Effect {
                    effect: EffectCategory::IoDbWrite,
                    qualifiers: serde_json::Value::Null,
                    note,
                    ..Default::default()
                });
                seen_db_write = true;
            } else if is_read && !seen_db_read {
                effects.push(Effect {
                    effect: EffectCategory::IoDbRead,
                    qualifiers: serde_json::Value::Null,
                    note,
                    ..Default::default()
                });
                seen_db_read = true;
            } else if !is_write && !is_read && !seen_db_read && !seen_db_write {
                // Unrecognized SQL — conservatively emit both.
                effects.push(Effect {
                    effect: EffectCategory::IoDbRead,
                    qualifiers: serde_json::Value::Null,
                    note: note.clone(),
                    ..Default::default()
                });
                effects.push(Effect {
                    effect: EffectCategory::IoDbWrite,
                    qualifiers: serde_json::Value::Null,
                    note,
                    ..Default::default()
                });
                seen_db_read = true;
                seen_db_write = true;
            }
        }
    }
    // .commit() implies a preceding write
    if !seen_db_write && (scan.contains(".commit()") || scan.contains("conn.commit")) {
        effects.push(Effect {
            effect: EffectCategory::IoDbWrite,
            qualifiers: serde_json::Value::Null,
            note: first_matching_line(scan, body, &[".commit()", "conn.commit"]),
            ..Default::default()
        });
    }

    // Network libraries -> IoNetOut
    let net_prefixes = ["requests.", "urllib.", "httpx.", "aiohttp."];
    let mut net_hosts: Vec<String> = Vec::new();
    let mut net_note: Option<String> = None;
    for prefix in net_prefixes {
        for call_site in find_prefixed_calls(scan, prefix) {
            let args = &body[call_site.args_start..call_site.args_end];
            if let Some(host) = extract_url_host(args) {
                if !net_hosts.contains(&host) {
                    net_hosts.push(host);
                }
            }
            if net_note.is_none() {
                net_note = Some(trim_note(
                    &body[call_site.call_start..call_site.args_end + 1],
                ));
            }
        }
    }
    if net_note.is_some() {
        let qualifiers = if net_hosts.is_empty() {
            serde_json::Value::Null
        } else {
            json!({ "hosts": net_hosts })
        };
        effects.push(Effect {
            effect: EffectCategory::IoNetOut,
            qualifiers,
            note: net_note,
            ..Default::default()
        });
    }

    // subprocess.* / os.system / os.exec* -> ProcSpawn
    let proc_patterns = ["subprocess.", "os.system(", "os.exec"];
    if let Some(note) = first_match_note(scan, body, &proc_patterns) {
        effects.push(Effect {
            effect: EffectCategory::ProcSpawn,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // os.environ / os.getenv -> EnvRead
    let env_patterns = ["os.environ", "os.getenv"];
    if let Some(note) = first_match_note(scan, body, &env_patterns) {
        let mut vars: Vec<String> = Vec::new();
        for call_site in find_calls(scan, "os.getenv(") {
            let args = &body[call_site.args_start..call_site.args_end];
            if let Some(v) = extract_first_string_literal(args) {
                if !vars.contains(&v) {
                    vars.push(v);
                }
            }
        }
        let qualifiers = if vars.is_empty() {
            serde_json::Value::Null
        } else {
            json!({ "vars": vars })
        };
        effects.push(Effect {
            effect: EffectCategory::EnvRead,
            qualifiers,
            note: Some(note),
            ..Default::default()
        });
    }

    // time.sleep -> TimeSleep
    if let Some(note) = first_match_note(scan, body, &["time.sleep"]) {
        effects.push(Effect {
            effect: EffectCategory::TimeSleep,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // time.time / time.monotonic / datetime.now -> TimeRead
    let time_read_patterns = [
        "time.time",
        "time.monotonic",
        "time.perf_counter",
        "datetime.now",
        "datetime.utcnow",
        "datetime.today",
    ];
    if let Some(note) = first_match_note(scan, body, &time_read_patterns) {
        effects.push(Effect {
            effect: EffectCategory::TimeRead,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // random.* / secrets.* -> Random
    let random_patterns = ["random.", "secrets.", "os.urandom("];
    if let Some(note) = first_match_note(scan, body, &random_patterns) {
        effects.push(Effect {
            effect: EffectCategory::Random,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // `raise ` statement -> Throw
    if has_raise_statement(scan) {
        let note = first_matching_line(scan, body, &["raise "]);
        effects.push(Effect {
            effect: EffectCategory::Throw,
            qualifiers: serde_json::Value::Null,
            note,
            ..Default::default()
        });
    }

    effects
}

/// Scan for a literal needle and return the lines we recognize as actual call
/// sites. We do not attempt to skip string literals — for M1 this is good
/// enough and matches the "plain substring" guidance.
#[derive(Debug, Clone, Copy)]
struct CallSite {
    call_start: usize,
    args_start: usize,
    args_end: usize,
}

/// Find all call sites where `needle` (which must end in `(`) appears in
/// `body`, returning the byte offsets of the opening identifier, the byte
/// after the `(`, and the matching `)`.
fn find_calls(body: &str, needle: &str) -> Vec<CallSite> {
    let mut out = Vec::new();
    if !needle.ends_with('(') {
        return out;
    }
    let bytes = body.as_bytes();
    let mut search_from = 0;
    while let Some(idx) = body[search_from..].find(needle) {
        let abs = search_from + idx;
        let args_start = abs + needle.len();
        if let Some(args_end) = find_matching_paren(bytes, args_start) {
            out.push(CallSite {
                call_start: abs,
                args_start,
                args_end,
            });
            search_from = args_end + 1;
        } else {
            search_from = args_start;
        }
    }
    out
}

#[allow(dead_code)]
fn contains_call(body: &str, needle: &str) -> bool {
    !find_calls(body, needle).is_empty()
}

/// Like [`find_calls`], but for a dotted module/receiver prefix that ends in
/// `.` (e.g. `"requests."`). Matches `prefix<identifier>(` — the dotted
/// prefix, a bare method identifier, then the call's parens — and returns a
/// [`CallSite`] whose `call_start` is the prefix start and whose
/// `args_start..args_end` span the parenthesised arguments.
///
/// `find_calls` requires its needle to end in `(`, so passing a varying-method
/// prefix like `"requests."` to it returns nothing (the guard rejects
/// non-`(` needles). That is exactly how the network-effect detection used to
/// silently no-op for `requests.get(...)` / `httpx.post(...)`; this helper
/// closes that gap.
fn find_prefixed_calls(body: &str, prefix: &str) -> Vec<CallSite> {
    let mut out = Vec::new();
    let bytes = body.as_bytes();
    let mut from = 0;
    while let Some(rel) = body[from..].find(prefix) {
        let abs = from + rel;
        let after = abs + prefix.len();
        from = after;
        // The method name must be a bare identifier immediately followed by '('.
        let rest = &body[after..];
        let name_len = rest
            .find(|c: char| !(c.is_alphanumeric() || c == '_'))
            .unwrap_or(rest.len());
        if name_len == 0 || rest.as_bytes().get(name_len) != Some(&b'(') {
            continue;
        }
        let args_start = after + name_len + 1;
        if let Some(args_end) = find_matching_paren(bytes, args_start) {
            out.push(CallSite {
                call_start: abs,
                args_start,
                args_end,
            });
            from = args_end + 1;
        }
    }
    out
}

/// Given the position just after `(`, find the matching `)`. Handles nested
/// parens and single/double quoted strings (non-raw). Returns the index of the
/// matching `)` byte.
fn find_matching_paren(bytes: &[u8], start: usize) -> Option<usize> {
    let mut depth: i32 = 1;
    let mut i = start;
    let mut in_string: Option<u8> = None;
    while i < bytes.len() {
        let c = bytes[i];
        if let Some(q) = in_string {
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == q {
                in_string = None;
            }
        } else {
            match c {
                b'"' | b'\'' => in_string = Some(c),
                b'(' => depth += 1,
                b')' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(i);
                    }
                }
                _ => {}
            }
        }
        i += 1;
    }
    None
}

fn mentions_write_mode(args: &str) -> bool {
    // Look for a mode string literal containing 'w' or 'a'. Very loose —
    // we just scan quoted sections.
    let bytes = args.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if c == b'"' || c == b'\'' {
            let q = c;
            let start = i + 1;
            let mut j = start;
            while j < bytes.len() && bytes[j] != q {
                if bytes[j] == b'\\' {
                    j += 2;
                    continue;
                }
                j += 1;
            }
            if j <= bytes.len() {
                let lit = &args[start..j.min(bytes.len())];
                if lit.len() <= 4 && (lit.contains('w') || lit.contains('a') || lit.contains('x')) {
                    return true;
                }
                i = j + 1;
                continue;
            }
        }
        i += 1;
    }
    false
}

/// Extract the first positional argument if it is a plain string literal.
fn extract_open_path(args: &str) -> Option<String> {
    extract_first_string_literal(args)
}

/// If the args start with a string literal, return its contents.
fn extract_first_string_literal(args: &str) -> Option<String> {
    let trimmed = args.trim_start();
    let bytes = trimmed.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let q = bytes[0];
    if q != b'"' && q != b'\'' {
        return None;
    }
    let mut j = 1;
    let mut out = String::new();
    while j < bytes.len() {
        let c = bytes[j];
        if c == b'\\' && j + 1 < bytes.len() {
            out.push(bytes[j + 1] as char);
            j += 2;
            continue;
        }
        if c == q {
            return Some(out);
        }
        out.push(c as char);
        j += 1;
    }
    None
}

/// Try to extract a host from args containing a URL literal.
fn extract_url_host(args: &str) -> Option<String> {
    // Find any `http://` or `https://` in the args text.
    let lower = args;
    for scheme in ["https://", "http://"] {
        if let Some(idx) = lower.find(scheme) {
            let tail = &lower[idx + scheme.len()..];
            let end = tail
                .find(|c: char| {
                    c == '/' || c == '"' || c == '\'' || c == ')' || c == '?' || c.is_whitespace()
                })
                .unwrap_or(tail.len());
            let host = &tail[..end];
            if !host.is_empty() {
                return Some(host.to_string());
            }
        }
    }
    None
}

/// Return a short, single-line note snippet.
/// Cap a doc string at 512 characters, trimming at a word boundary when possible.
fn truncate_doc(s: &str) -> String {
    const MAX: usize = 512;
    if s.len() <= MAX {
        return s.to_string();
    }
    // Try to break at a space before the limit.
    let truncated = &s[..MAX];
    match truncated.rfind(' ') {
        Some(pos) => format!("{}…", &truncated[..pos]),
        None => format!("{}…", truncated),
    }
}

fn trim_note(s: &str) -> String {
    let first_line = s.lines().next().unwrap_or("").trim();
    if first_line.len() > 120 {
        format!("{}...", &first_line[..120])
    } else {
        first_line.to_string()
    }
}

/// Plan L t-002: scan `scan` for a match (so comments / string literals
/// previously masked to spaces don't trigger), but return the matching
/// line from `body` so the note reflects the real source text. `scan`
/// and `body` MUST be the same byte length and split into the same
/// line count for the alignment to hold.
fn first_matching_line(scan: &str, body: &str, needles: &[&str]) -> Option<String> {
    for (i, scan_line) in scan.lines().enumerate() {
        for n in needles {
            if scan_line.contains(n) {
                return body.lines().nth(i).map(|l| l.trim().to_string());
            }
        }
    }
    None
}

/// Check each needle against the masked `scan`; return the first
/// matching line from the real `body` as a note.
fn first_match_note(scan: &str, body: &str, needles: &[&str]) -> Option<String> {
    for n in needles {
        if scan.contains(n) {
            return first_matching_line(scan, body, needles);
        }
    }
    None
}

/// Detect a `raise` statement (not `raises` in a docstring or attribute).
/// We check for `raise ` preceded by start-of-line or whitespace.
/// Operates on the masked `scan` so a `raise` inside a comment or
/// string literal doesn't trip the detector.
fn has_raise_statement(scan: &str) -> bool {
    for line in scan.lines() {
        let trimmed = line.trim_start();
        if trimmed.starts_with("raise ") || trimmed == "raise" {
            return true;
        }
    }
    false
}

/// Plan L t-005: scan Python source for call patterns the static
/// call-graph walker can't resolve. Returns one hint per detected
/// site so the indexer can surface a warning. The patterns we
/// flag are deliberately conservative — only the ones that are
/// unambiguously dynamic dispatch:
///
/// - `getattr(obj, "name")(args)` and `getattr(obj, name_var)(args)`
///   — runtime attribute lookup feeding a call.
/// - `__getattr__` / `__getattribute__` method definitions — the
///   class promises to resolve unknown attributes at runtime.
///
/// We deliberately do NOT flag plain `getattr(obj, "name")` (no
/// trailing call) — that's a read, not a dispatch, and gets
/// resolved by the property/attribute pass.
///
/// Detection runs against the masked source (Plan L t-002) so a
/// `# getattr(...)` in a comment doesn't generate a phantom warning.
pub fn scan_dynamic_dispatch_in_python(file: &str, source: &str) -> Vec<DynamicDispatchHint> {
    let masked = mask_comments_and_literals(source);
    let mut hints = Vec::new();
    let bytes = masked.as_bytes();
    let body = source.as_bytes();
    let mut line_starts: Vec<usize> = vec![0];
    for (i, b) in body.iter().enumerate() {
        if *b == b'\n' {
            line_starts.push(i + 1);
        }
    }
    let line_of = |off: usize| -> u32 {
        match line_starts.binary_search(&off) {
            Ok(i) => i as u32 + 1,
            Err(i) => i.max(1) as u32,
        }
    };
    let snippet_at = |off: usize| -> String {
        let line_idx = line_of(off).saturating_sub(1) as usize;
        let start = line_starts.get(line_idx).copied().unwrap_or(0);
        let end = line_starts
            .get(line_idx + 1)
            .copied()
            .unwrap_or(body.len())
            .saturating_sub(1);
        std::str::from_utf8(&body[start..end])
            .map(|s| s.trim().to_string())
            .unwrap_or_default()
    };

    // Pattern 1: getattr(obj, …)(…)  — the trailing `(` after the
    // outer `)` is the giveaway. We use find_calls + check the byte
    // right after args_end.
    for site in find_calls(&masked, "getattr(") {
        // Peek past the closing `)` for an opening `(` (allowing
        // whitespace / chained attribute reads in between is more
        // ambitious — for v1 we require an immediate call).
        let mut j = site.args_end + 1;
        while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
            j += 1;
        }
        if j < bytes.len() && bytes[j] == b'(' {
            hints.push(DynamicDispatchHint {
                file: file.to_string(),
                line: line_of(site.call_start),
                pattern: "getattr".into(),
                snippet: snippet_at(site.call_start),
            });
        }
    }

    // Pattern 2: `def __getattr__(self, …)` / `def __getattribute__(…)`
    // method definitions. Scan line by line; `mask_comments_and_literals`
    // preserves line splits so offsets align.
    for (i, line) in masked.lines().enumerate() {
        let trimmed = line.trim_start();
        if trimmed.starts_with("def __getattr__(") || trimmed.starts_with("def __getattribute__(") {
            let off = line_starts.get(i).copied().unwrap_or(0);
            hints.push(DynamicDispatchHint {
                file: file.to_string(),
                line: (i + 1) as u32,
                pattern: "__getattr__".into(),
                snippet: snippet_at(off),
            });
        }
    }

    hints
}

/// Plan L t-002: walk Python source and replace bytes inside `#`
/// line comments and string literals (single/double/triple, with
/// optional `r` / `b` / `f` prefixes) with ASCII space. Newlines and
/// every other byte stay where they are, so the output has the same
/// byte length AND the same line split as the input. Callers can
/// detect call patterns against the masked output and use byte
/// offsets to extract real text from the original body.
///
/// Limitations:
/// - F-string interpolations inside `f"{expr}"` are masked along
///   with the rest of the literal. An effect inside an f-string
///   interpolation will be missed. Acceptable trade — the bug being
///   fixed is comments and plain strings producing false positives;
///   under-detecting f-string interpolations is conservative.
/// - Raw strings (`r"..."`) are masked normally; backslashes don't
///   escape the closing quote.
fn mask_comments_and_literals(body: &str) -> String {
    let bytes = body.as_bytes();
    let mut out: Vec<u8> = bytes.to_vec();
    let n = bytes.len();
    let mut i = 0;
    while i < n {
        let c = bytes[i];
        // Line comment: `#` to end-of-line, but not inside an f-string
        // (we're not in a string here because we'd have entered the
        // literal branch below).
        if c == b'#' {
            let mut j = i;
            while j < n && bytes[j] != b'\n' {
                out[j] = b' ';
                j += 1;
            }
            i = j;
            continue;
        }
        // String literal start. Optional prefix: r/R/b/B/f/F (and
        // combinations like rb, fr, Rb…). The prefix bytes themselves
        // are NOT masked — they're identifiers as far as effect
        // detection is concerned, and erasing them could turn
        // `rb"…"` into `  "…"` which still parses as a literal but
        // changes column counts in error paths. Leave the prefix,
        // mask the literal body.
        let quote_start = find_quote_after_optional_prefix(bytes, i);
        if let Some(qi) = quote_start {
            let q = bytes[qi];
            // Triple quote?
            let triple = qi + 2 < n && bytes[qi + 1] == q && bytes[qi + 2] == q;
            let (literal_start, end_pos) = if triple {
                let inner_start = qi + 3;
                let end = find_triple_close(bytes, inner_start, q);
                (inner_start, end)
            } else {
                let inner_start = qi + 1;
                let end = find_single_close(bytes, inner_start, q);
                (inner_start, end)
            };
            // Mask the literal body (between the open and close
            // quotes). Quotes themselves stay so paren-matching and
            // any human-eyeballing of the masked source still reads.
            for k in literal_start..end_pos.min(n) {
                if out[k] != b'\n' {
                    out[k] = b' ';
                }
            }
            // Advance past the closing quote(s).
            i = end_pos + if triple { 3 } else { 1 };
            continue;
        }
        i += 1;
    }
    // Safety: byte length must be preserved for offset-based slicing
    // upstream. `out` was built from `bytes.to_vec()` and only mutated
    // in place, so length is identical to `body.len()`. The mutations
    // only ever swap a byte for ASCII space (0x20) or leave it alone,
    // both of which keep the buffer valid UTF-8.
    debug_assert_eq!(out.len(), bytes.len());
    String::from_utf8(out).unwrap_or_else(|_| body.to_string())
}

/// Skip optional Python string prefix bytes (`r`, `R`, `b`, `B`, `f`,
/// `F`, in 1- or 2-char combinations like `rb`/`Rb`/`fr`) starting at
/// `i`, returning the index of the opening quote if found. Only
/// activates when `bytes[i]` is one of the prefix bytes AND a quote
/// follows within two bytes — otherwise the caller's `i` is on a
/// normal identifier byte and we return None.
fn find_quote_after_optional_prefix(bytes: &[u8], i: usize) -> Option<usize> {
    let n = bytes.len();
    if i >= n {
        return None;
    }
    let c = bytes[i];
    if c == b'"' || c == b'\'' {
        return Some(i);
    }
    let is_prefix = |b: u8| matches!(b, b'r' | b'R' | b'b' | b'B' | b'f' | b'F');
    if !is_prefix(c) {
        return None;
    }
    // The byte before `i` must NOT be an identifier byte — otherwise
    // we're in the middle of a word like `_renderRequest`, not at a
    // string prefix. Treat any ASCII alphanumeric or underscore as
    // identifier-continuing.
    if i > 0 {
        let prev = bytes[i - 1];
        if prev.is_ascii_alphanumeric() || prev == b'_' {
            return None;
        }
    }
    // 1-char prefix: `r"…"`
    if i + 1 < n && (bytes[i + 1] == b'"' || bytes[i + 1] == b'\'') {
        return Some(i + 1);
    }
    // 2-char prefix: `rb"…"` / `fr"…"` / etc.
    if i + 2 < n && is_prefix(bytes[i + 1]) && (bytes[i + 2] == b'"' || bytes[i + 2] == b'\'') {
        return Some(i + 2);
    }
    None
}

/// Find the closing single-quote `q` starting from `start`. Honors
/// backslash escapes. Returns the index of the closing quote, or
/// `bytes.len()` if no close found (treat as "string runs to EOF").
/// A bare newline closes a non-triple string in Python — we honor
/// that so an unterminated literal doesn't mask the rest of the file.
fn find_single_close(bytes: &[u8], start: usize, q: u8) -> usize {
    let n = bytes.len();
    let mut j = start;
    while j < n {
        let b = bytes[j];
        if b == b'\\' {
            j += 2;
            continue;
        }
        if b == b'\n' {
            return j; // unterminated; stop at newline
        }
        if b == q {
            return j;
        }
        j += 1;
    }
    n
}

/// Find the closing `qqq` triple-quote sequence starting from `start`.
/// Returns the index of the FIRST quote in the closing triple, or
/// `bytes.len()` if the literal runs to EOF.
fn find_triple_close(bytes: &[u8], start: usize, q: u8) -> usize {
    let n = bytes.len();
    let mut j = start;
    while j + 2 < n {
        if bytes[j] == b'\\' {
            j += 2;
            continue;
        }
        if bytes[j] == q && bytes[j + 1] == q && bytes[j + 2] == q {
            return j;
        }
        j += 1;
    }
    n
}

// -----------------------------------------------------------------------------
// Call-edge extraction (intra- and cross-module)
// -----------------------------------------------------------------------------

/// Build the (caller_qname -> callee_qname) edge set for one file. Resolution
/// is best-effort and covers:
///
/// - `identifier()` -> intra-module `simple_name -> qname`, then imports
///   (`from foo import bar` / `import foo as f`).
/// - `Class.method()` -> resolve `<module>.Class.method`.
/// - `self.method()` inside `<module>.Class.<fn>` -> resolve to `<module>.Class.method`.
/// - `foo.bar()` where `foo` is an imported module -> resolve via the import
///   map to `<foo_prefix>.bar`, and emit only if that qname exists in the
///   workspace. This is how we capture cross-module calls like
///   `logger.write_log` from `_driver.py`.
///
/// Anything we can't resolve (subscripts, lambdas, star imports, relative
/// imports, dynamic dispatch) is silently skipped.
fn extract_call_edges_impl(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
    workspace: &WorkspaceSymbols,
) -> Vec<CallEdge> {
    let module_prefix = module_qname_prefix(file);

    // All known qnames in this file.
    let known: HashSet<&str> = symbols.iter().map(|s| s.qname.as_str()).collect();

    // simple_name -> qname for single-identifier resolution. If two symbols
    // share a simple name (e.g. method/function collision), we keep the first
    // module-level one we see; this is best-effort by design.
    let mut by_simple: HashMap<String, String> = HashMap::new();
    for s in symbols {
        let simple = s.qname.rsplit('.').next().unwrap_or(&s.qname).to_string();
        // Prefer module-level functions/classes over nested entries: only fill
        // if the qname has exactly module_prefix + "." + simple.
        let module_level = if module_prefix.is_empty() {
            s.qname == simple
        } else {
            s.qname == format!("{}.{}", module_prefix, simple)
        };
        if module_level {
            by_simple.insert(simple, s.qname.clone());
        } else {
            by_simple.entry(simple).or_insert_with(|| s.qname.clone());
        }
    }

    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_python::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }

    // Parse the full source once to extract top-level imports. We need the
    // file-level tree (not individual symbol bodies) so we can pick up
    // `import foo` / `from foo import bar` at module scope. module_prefix
    // is passed so relative imports (`from . import x`, `from .foo import y`)
    // can be resolved to absolute qnames — Plan D t-004.
    let imports = parse_imports(source, &mut parser, &module_prefix);

    let mut edges: HashSet<CallEdge> = HashSet::new();

    for sym in symbols {
        // Only function and method bodies can contain calls in a meaningful
        // sense; skip class/module symbols (their bodies' calls are usually
        // attributed to a wrapping function anyway).
        if !matches!(sym.kind, SymbolKind::Function | SymbolKind::Method) {
            continue;
        }

        let src_bytes = sym.body.as_bytes();
        let tree = match parser.parse(src_bytes, None) {
            Some(t) => t,
            None => continue,
        };

        // The parsed body is a `function_definition` at (or near) the root —
        // walk the whole tree and pick up every `call` node.
        let enclosing_class = enclosing_class_qname(&sym.qname, &module_prefix, &known);
        collect_calls(
            tree.root_node(),
            src_bytes,
            sym,
            &module_prefix,
            &by_simple,
            &known,
            &imports,
            workspace,
            enclosing_class.as_deref(),
            &mut edges,
        );
    }

    let mut out: Vec<CallEdge> = edges.into_iter().collect();
    out.sort_by(|a, b| {
        a.caller_qname
            .cmp(&b.caller_qname)
            .then_with(|| a.callee_qname.cmp(&b.callee_qname))
    });
    out
}

/// Imports discovered at module scope, keyed by the local binding.
///
/// Each entry records:
/// - `qname_prefix`: the qname (or qname prefix) the local name resolves to.
/// - `is_module`: whether the local name refers to a *module* (resolve
///   `local.attr` -> `qname_prefix.attr`) vs. a single imported symbol
///   (resolve `local.attr` -> `qname_prefix.attr` as well, but `local()`
///   resolves to `qname_prefix` directly).
#[derive(Debug, Clone)]
struct ImportBinding {
    qname_prefix: String,
    /// `true` for `import foo` / `import foo as f`; `false` for
    /// `from foo import bar`. Currently both forms resolve attribute access
    /// via the same path (`qname_prefix` + `.` + `attr`), but we keep the
    /// distinction so future resolvers (e.g., re-exports) can tell apart
    /// module handles from direct symbol bindings.
    #[allow(dead_code)]
    is_module: bool,
}

/// Walk the file's top-level statements and collect import bindings.
///
/// Supports:
/// - `import foo` -> `foo -> ("foo", module)`
/// - `import foo.bar` -> `foo -> ("foo", module)` (only the first segment binds)
/// - `import foo as f` -> `f -> ("foo", module)`
/// - `from foo import bar` -> `bar -> ("foo.bar", symbol)`
/// - `from foo import bar as b` -> `b -> ("foo.bar", symbol)`
/// - `from foo import (a, b, c)` -> each as above
/// - Plan D t-004: relative imports (`from . import x`, `from .foo import y`,
///   `from ..pkg import z`) — resolved against `module_prefix`.
///
/// - Plan L t-004: imports nested inside function bodies, class
///   bodies, and conditional blocks (`if TYPE_CHECKING:`, `try: …
///   except ImportError: …`) are also collected and merged into the
///   same flat map.
///
/// Skips:
/// - `from foo import *` — can't statically resolve members.
///
/// Nested-import scoping policy: we deliberately use a single flat
/// map rather than per-function scoping. Real Python code rarely
/// shadows module-scope imports inside a function under the same
/// local name; when it does (typically `try/except ImportError`
/// fallbacks), either branch resolving to the same prefix is the
/// behavior callers want. The trade-off: a function that genuinely
/// imports a different module under a colliding name would resolve
/// to whichever was inserted last. Acceptable for the call-edge
/// signal we're building.
fn parse_imports(
    source: &str,
    parser: &mut Parser,
    module_prefix: &str,
) -> HashMap<String, ImportBinding> {
    let mut out: HashMap<String, ImportBinding> = HashMap::new();
    let src_bytes = source.as_bytes();
    let tree = match parser.parse(src_bytes, None) {
        Some(t) => t,
        None => return out,
    };
    walk_imports(tree.root_node(), src_bytes, module_prefix, &mut out);
    out
}

/// Plan L t-004: recursively walk the tree picking up every
/// `import_statement` / `import_from_statement` node — module-scope
/// AND nested. Skipping non-import nodes is implicit; we just
/// recurse into every child and dispatch on `kind()`.
///
/// We don't prune at function/class boundaries on purpose: a
/// `if TYPE_CHECKING:` block sits at module scope, a body import
/// sits inside a function, a `try: import cPickle / except: import
/// pickle` sits inside a `try_statement`. Recursing everywhere
/// catches all three with one walk.
fn walk_imports(
    node: Node<'_>,
    src: &[u8],
    module_prefix: &str,
    out: &mut HashMap<String, ImportBinding>,
) {
    match node.kind() {
        "import_statement" => {
            collect_import_statement(node, src, out);
            return;
        }
        "import_from_statement" => {
            collect_import_from_statement(node, src, module_prefix, out);
            return;
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_imports(child, src, module_prefix, out);
    }
}

/// Plan D t-004: resolve a relative-import dot prefix against the importing
/// file's `module_prefix`. Returns the absolute module qname (e.g.
/// "crucible.agents.base") that the dots + optional suffix point to, or
/// None when the relative import escapes the workspace.
fn resolve_relative_import(module_prefix: &str, raw: &str) -> Option<String> {
    let dot_count = raw.chars().take_while(|c| *c == '.').count();
    if dot_count == 0 {
        return None;
    }
    let suffix = raw[dot_count..].trim().trim_matches('.');
    let parts: Vec<&str> = if module_prefix.is_empty() {
        Vec::new()
    } else {
        module_prefix.split('.').collect()
    };
    if dot_count > parts.len() {
        return None;
    }
    let keep = parts.len() - dot_count;
    let mut base = parts[..keep].join(".");
    if !suffix.is_empty() {
        if !base.is_empty() {
            base.push('.');
        }
        base.push_str(suffix);
    }
    if base.is_empty() { None } else { Some(base) }
}

/// Handle `import a, b as c, d.e`.
fn collect_import_statement(node: Node<'_>, src: &[u8], out: &mut HashMap<String, ImportBinding>) {
    // Tree-sitter-python emits each imported name as a `name` field (which
    // may appear multiple times), each being either `dotted_name` or
    // `aliased_import`.
    let mut cursor = node.walk();
    for child in node.children_by_field_name("name", &mut cursor) {
        match child.kind() {
            "dotted_name" => {
                // `import foo.bar.baz` -> local binding is the first segment,
                // but resolves to just that first segment (not the tail —
                // Python only binds the top package name).
                let full = node_text(child, src).unwrap_or_default();
                let full = full.trim().to_string();
                if full.is_empty() {
                    continue;
                }
                let first = full.split('.').next().unwrap_or(&full).to_string();
                out.insert(
                    first.clone(),
                    ImportBinding {
                        qname_prefix: first,
                        is_module: true,
                    },
                );
                // Also register the fully-dotted form so `foo.bar.baz(...)`
                // written explicitly can resolve to a module qname prefix.
                if full.contains('.') {
                    out.insert(
                        full.clone(),
                        ImportBinding {
                            qname_prefix: full,
                            is_module: true,
                        },
                    );
                }
            }
            "aliased_import" => {
                // `import foo as f` / `import foo.bar as fb`
                let name = child
                    .child_by_field_name("name")
                    .and_then(|n| node_text(n, src))
                    .unwrap_or_default();
                let alias = child
                    .child_by_field_name("alias")
                    .and_then(|n| node_text(n, src))
                    .unwrap_or_default();
                let name = name.trim().to_string();
                let alias = alias.trim().to_string();
                if name.is_empty() || alias.is_empty() {
                    continue;
                }
                out.insert(
                    alias,
                    ImportBinding {
                        qname_prefix: name,
                        is_module: true,
                    },
                );
            }
            _ => {}
        }
    }
}

/// Handle `from foo import a, b as c` and `from foo import (a, b)`.
fn collect_import_from_statement(
    node: Node<'_>,
    src: &[u8],
    module_prefix: &str,
    out: &mut HashMap<String, ImportBinding>,
) {
    // `module_name` field holds a `dotted_name` or `relative_import`.
    let module_node = node.child_by_field_name("module_name");
    let module_kind = module_node.map(|n| n.kind()).unwrap_or("");
    let module = if module_kind == "relative_import" {
        // Plan D t-004: resolve `.`/`..`/etc. against the importing file's
        // module_prefix. `from . import x` from crucible/agents/foo.py
        // resolves to module "crucible.agents".
        let raw = module_node
            .and_then(|n| node_text(n, src))
            .unwrap_or_default();
        match resolve_relative_import(module_prefix, raw.trim()) {
            Some(m) => m,
            None => return,
        }
    } else {
        let m = module_node
            .and_then(|n| node_text(n, src))
            .unwrap_or_default()
            .trim()
            .to_string();
        if m.is_empty() {
            return;
        }
        m
    };

    // Detect `from foo import *` — tree-sitter-python represents the `*` as
    // a `wildcard_import` child (not a `name` field). Skip in that case.
    let mut cursor_all = node.walk();
    for child in node.children(&mut cursor_all) {
        if child.kind() == "wildcard_import" {
            return;
        }
    }

    let mut cursor = node.walk();
    for child in node.children_by_field_name("name", &mut cursor) {
        match child.kind() {
            "dotted_name" => {
                let name = node_text(child, src).unwrap_or_default();
                let name = name.trim().to_string();
                if name.is_empty() {
                    continue;
                }
                let qname = format!("{module}.{name}");
                out.insert(
                    name,
                    ImportBinding {
                        qname_prefix: qname,
                        is_module: false,
                    },
                );
            }
            "aliased_import" => {
                let name = child
                    .child_by_field_name("name")
                    .and_then(|n| node_text(n, src))
                    .unwrap_or_default();
                let alias = child
                    .child_by_field_name("alias")
                    .and_then(|n| node_text(n, src))
                    .unwrap_or_default();
                let name = name.trim().to_string();
                let alias = alias.trim().to_string();
                if name.is_empty() || alias.is_empty() {
                    continue;
                }
                let qname = format!("{module}.{name}");
                out.insert(
                    alias,
                    ImportBinding {
                        qname_prefix: qname,
                        is_module: false,
                    },
                );
            }
            _ => {}
        }
    }
}

/// For a method qname like `mod.Class.m`, return `Some("mod.Class")` provided
/// `mod.Class` is a known symbol in this file. Otherwise `None`.
fn enclosing_class_qname(
    qname: &str,
    module_prefix: &str,
    known: &HashSet<&str>,
) -> Option<String> {
    let parts: Vec<&str> = qname.split('.').collect();
    if parts.len() < 2 {
        return None;
    }
    // Drop the function/method name; look for the deepest ancestor that is a
    // known symbol AND lives below `module_prefix`.
    for end in (1..parts.len()).rev() {
        let candidate = parts[..end].join(".");
        if !module_prefix.is_empty() && !candidate.starts_with(module_prefix) {
            continue;
        }
        if known.contains(candidate.as_str()) {
            return Some(candidate);
        }
    }
    None
}

#[allow(clippy::too_many_arguments)]
fn collect_calls(
    node: Node<'_>,
    src: &[u8],
    sym: &ParsedSymbol,
    module_prefix: &str,
    by_simple: &HashMap<String, String>,
    known: &HashSet<&str>,
    imports: &HashMap<String, ImportBinding>,
    workspace: &WorkspaceSymbols,
    enclosing_class: Option<&str>,
    out: &mut HashSet<CallEdge>,
) {
    if node.kind() == "call" {
        if let Some(func) = node.child_by_field_name("function") {
            if let Some(callee) = resolve_callee(
                func,
                src,
                module_prefix,
                by_simple,
                known,
                imports,
                workspace,
                enclosing_class,
            ) {
                out.insert(CallEdge {
                    caller_qname: sym.qname.clone(),
                    callee_qname: callee,
                });
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_calls(
            child,
            src,
            sym,
            module_prefix,
            by_simple,
            known,
            imports,
            workspace,
            enclosing_class,
            out,
        );
    }
}

/// Resolve the function-position node of a `call` to a fully-qualified name,
/// when possible. Precedence (LEGB-ish, for our purposes):
///
/// 1. Intra-module `simple_name -> qname` (local definitions shadow imports).
/// 2. Import map (`from foo import bar` / `import foo as f`).
/// 3. For attribute calls, try intra-module class resolution, then imports.
///
/// Cross-module resolutions are only emitted when the resolved qname is
/// present in `workspace.qnames`. This drops stdlib / third-party calls
/// whose symbols we didn't index.
#[allow(clippy::too_many_arguments)]
fn resolve_callee(
    func: Node<'_>,
    src: &[u8],
    module_prefix: &str,
    by_simple: &HashMap<String, String>,
    known: &HashSet<&str>,
    imports: &HashMap<String, ImportBinding>,
    workspace: &WorkspaceSymbols,
    enclosing_class: Option<&str>,
) -> Option<String> {
    match func.kind() {
        "identifier" => {
            let name = node_text(func, src)?;
            // 1) intra-module first (shadows imports)
            if let Some(q) = by_simple.get(&name) {
                return Some(q.clone());
            }
            // 2) import map (e.g., `from logger import write_log`)
            if let Some(binding) = imports.get(&name) {
                if workspace.contains(&binding.qname_prefix) {
                    return Some(binding.qname_prefix.clone());
                }
            }
            None
        }
        "attribute" => {
            // `<object>.<attribute>` — resolve `self.X`, `Class.X`, and
            // `<imported_module>.X`.
            let object = func.child_by_field_name("object")?;
            let attr = func.child_by_field_name("attribute")?;
            let attr_name = node_text(attr, src)?;

            match object.kind() {
                "identifier" => {
                    let obj_name = node_text(object, src)?;
                    if obj_name == "self" {
                        let class = enclosing_class?;
                        let candidate = format!("{class}.{attr_name}");
                        if known.contains(candidate.as_str()) {
                            return Some(candidate);
                        }
                        return None;
                    }

                    // Intra-module class attribute: `Foo.bar` -> `mod.Foo.bar`
                    let class_qname = if module_prefix.is_empty() {
                        obj_name.clone()
                    } else {
                        format!("{module_prefix}.{obj_name}")
                    };
                    if known.contains(class_qname.as_str()) {
                        let candidate = format!("{class_qname}.{attr_name}");
                        if known.contains(candidate.as_str()) {
                            return Some(candidate);
                        }
                    }

                    // Imported module or symbol: `logger.write_log` ->
                    // `<prefix>.write_log`, validated against workspace.
                    if let Some(binding) = imports.get(&obj_name) {
                        let candidate = format!("{}.{}", binding.qname_prefix, attr_name);
                        if workspace.contains(&candidate) {
                            return Some(candidate);
                        }
                    }
                    None
                }
                "attribute" => {
                    // Chained attribute like `foo.bar.baz(...)`. Try to
                    // flatten into a dotted path and match against imports.
                    let chain = flatten_attribute(object, src)?;
                    if let Some(binding) = imports.get(&chain) {
                        let candidate = format!("{}.{}", binding.qname_prefix, attr_name);
                        if workspace.contains(&candidate) {
                            return Some(candidate);
                        }
                    }
                    None
                }
                _ => None,
            }
        }
        _ => None,
    }
}

/// Flatten a nested `attribute` node back into its dotted text form.
/// Returns `None` if any inner node isn't an identifier/attribute chain.
fn flatten_attribute(node: Node<'_>, src: &[u8]) -> Option<String> {
    match node.kind() {
        "identifier" => node_text(node, src),
        "attribute" => {
            let object = node.child_by_field_name("object")?;
            let attr = node.child_by_field_name("attribute")?;
            let head = flatten_attribute(object, src)?;
            let tail = node_text(attr, src)?;
            Some(format!("{head}.{tail}"))
        }
        _ => None,
    }
}

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

    #[test]
    fn router_prefix_resolution_fastapi_and_flask() {
        // FastAPI: APIRouter(prefix=) on the router the decorator hangs on.
        let src = r#"
router = APIRouter(prefix="/api/notifications", tags=["x"])

@router.get("/unread")
def unread(): ...
"#;
        let p = collect_router_prefixes(src);
        assert_eq!(
            p.get("router").map(String::as_str),
            Some("/api/notifications")
        );
        assert_eq!(
            route_receiver("@router.get(\"/unread\")").as_deref(),
            Some("router")
        );
        assert_eq!(
            join_route("/api/notifications", "/unread"),
            "/api/notifications/unread"
        );

        // Flask blueprint url_prefix.
        let flask = r#"bp = Blueprint("acct", __name__, url_prefix="/accounts")"#;
        assert_eq!(
            collect_router_prefixes(flask).get("bp").map(String::as_str),
            Some("/accounts")
        );

        // Same-file mount: include_router prefix precedes the router's own prefix.
        let mounted = r#"
sub = APIRouter(prefix="/items")
app.include_router(sub, prefix="/api")
"#;
        assert_eq!(
            collect_router_prefixes(mounted)
                .get("sub")
                .map(String::as_str),
            Some("/api/items")
        );
    }

    #[test]
    fn router_prefix_edge_cases() {
        // `prefix` must not be matched inside `url_prefix`, and a plain FastAPI()
        // app with no prefix yields nothing.
        assert_eq!(string_kwarg(r#"url_prefix="/z""#, "prefix"), None);
        assert_eq!(
            string_kwarg(r#"url_prefix="/z""#, "url_prefix").as_deref(),
            Some("/z")
        );
        assert!(collect_router_prefixes("app = FastAPI()").is_empty());
        // join handles missing/extra slashes and root paths.
        assert_eq!(join_route("/api", "items"), "/api/items");
        assert_eq!(join_route("/api/", "/items"), "/api/items");
        assert_eq!(join_route("/api", "/"), "/api");
        assert_eq!(join_route("", "/items"), "/items");
        // ctor boundary: APIRouter not matched inside a longer identifier.
        assert!(ctor_args("x = MyAPIRouter(prefix=\"/a\")", "APIRouter").is_none());
    }

    fn ep(contract: &str, file: &str, line: u32) -> ServiceEndpoint {
        ServiceEndpoint {
            transport: Transport::Http,
            direction: Direction::Inbound,
            contract: contract.to_string(),
            repo_id: "r".into(),
            symbol_id: "s".into(),
            qname: "q".into(),
            file: file.into(),
            line,
            confidence: 0.95,
            note: None,
        }
    }

    #[test]
    fn cross_file_aliased_mount_tree_resolves_nested_prefix() {
        // The real-world shape: nested include_router across files, where the
        // mounted router is an ALIASED import and the decorator uses a generic
        // `router`. Qname identity (module.var) bridges the alias.
        //   main:  app=FastAPI(); app.include_router(api_router, "/api")
        //   api:   api_router=APIRouter(); include_router(calculators_router, "/calculators")
        //          (calculators_router is `from calc import router as calculators_router`)
        //   calc:  router=APIRouter(); @router.get("/budget")  → /api/calculators/budget
        let files = vec![
            (
                "main.py".to_string(),
                "from api import api_router\napp = FastAPI()\napp.include_router(api_router, prefix=\"/api\")\n".to_string(),
            ),
            (
                "api.py".to_string(),
                "from calc import router as calculators_router\napi_router = APIRouter()\napi_router.include_router(calculators_router, prefix=\"/calculators\")\n".to_string(),
            ),
            (
                "calc.py".to_string(),
                "router = APIRouter()\n\n@router.get(\"/budget\")\ndef budget(): ...\n".to_string(),
            ),
        ];
        let mut eps = vec![ep(&http_contract("GET", "/budget"), "calc.py", 3)];
        resolve_python_endpoint_prefixes(&files, &mut eps);
        assert_eq!(eps[0].contract, "http:GET /api/calculators/budget");
    }

    #[test]
    fn same_router_name_distinct_modules_resolve_independently() {
        // `router` in two files → distinct qnames (a.router, b.router), each
        // resolving to its own prefix (no cross-contamination).
        let files = vec![
            (
                "a.py".to_string(),
                "router = APIRouter(prefix=\"/api/notif\")\n\n@router.get(\"/x\")\ndef x(): ...\n"
                    .to_string(),
            ),
            (
                "b.py".to_string(),
                "router = APIRouter(prefix=\"/api/inst\")\n\n@router.get(\"/y\")\ndef y(): ...\n"
                    .to_string(),
            ),
        ];
        let mut eps = vec![
            ep(&http_contract("GET", "/x"), "a.py", 3),
            ep(&http_contract("GET", "/y"), "b.py", 3),
        ];
        resolve_python_endpoint_prefixes(&files, &mut eps);
        assert_eq!(eps[0].contract, "http:GET /api/notif/x");
        assert_eq!(eps[1].contract, "http:GET /api/inst/y");
    }

    #[test]
    fn multi_mount_emits_route_under_each_prefix() {
        // api_router mounted at BOTH /api/v1 and /api → route served at both.
        let files = vec![
            (
                "main.py".to_string(),
                "from api import api_router\napp = FastAPI()\napp.include_router(api_router, prefix=\"/api/v1\")\napp.include_router(api_router, prefix=\"/api\")\n".to_string(),
            ),
            (
                "api.py".to_string(),
                "api_router = APIRouter()\n\n@api_router.get(\"/health\")\ndef health(): ...\n".to_string(),
            ),
        ];
        let mut eps = vec![ep(&http_contract("GET", "/health"), "api.py", 3)];
        resolve_python_endpoint_prefixes(&files, &mut eps);
        let contracts: std::collections::HashSet<String> =
            eps.iter().map(|e| e.contract.clone()).collect();
        assert_eq!(eps.len(), 2, "{contracts:?}");
        assert!(
            contracts.contains("http:GET /api/v1/health"),
            "{contracts:?}"
        );
        assert!(contracts.contains("http:GET /api/health"), "{contracts:?}");
    }

    #[test]
    fn module_prefix_strips_py_and_leading_dot_slash() {
        // src/ anchor — stable for PEP 517 src-layout projects
        assert_eq!(
            module_qname_prefix("src/mypackage/module.py"),
            "mypackage.module"
        );
        assert_eq!(module_qname_prefix("src/utils.py"), "utils");
        // __init__.py at root of package src/ gets package-name prefix
        assert_eq!(
            module_qname_prefix("packages/mypkg/src/__init__.py"),
            "mypkg.__init__"
        );
        assert_eq!(
            module_qname_prefix("packages/my-pkg/src/__init__.py"),
            "my_pkg.__init__"
        );
        // no src segment — full relative path (fallback)
        assert_eq!(module_qname_prefix("foo/bar.py"), "foo.bar");
        assert_eq!(module_qname_prefix("./foo/bar.py"), "foo.bar");
        assert_eq!(module_qname_prefix("bar.py"), "bar");
    }

    #[test]
    fn strip_src_prefix_variants() {
        assert_eq!(strip_src_prefix("src/pkg/mod.py"), "pkg/mod.py");
        assert_eq!(strip_src_prefix("lib/src/utils.py"), "utils.py");
        assert_eq!(strip_src_prefix("pkg/mod.py"), "pkg/mod.py");
    }

    #[test]
    fn parses_module_function_and_class() {
        let src = "def top():\n    return 1\n\nclass C:\n    def m(self):\n        return 2\n";
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("x.py", src).unwrap();
        let qnames: Vec<_> = syms.iter().map(|s| s.qname.clone()).collect();
        assert!(qnames.contains(&"x.top".to_string()));
        assert!(qnames.contains(&"x.C".to_string()));
        assert!(qnames.contains(&"x.C.m".to_string()));
        let top = syms.iter().find(|s| s.qname == "x.top").unwrap();
        assert_eq!(top.kind, SymbolKind::Function);
        let m = syms.iter().find(|s| s.qname == "x.C.m").unwrap();
        assert_eq!(m.kind, SymbolKind::Method);
    }

    #[test]
    fn infers_fs_read_and_write_from_open() {
        let body = "def f():\n    with open('/tmp/a.txt', 'w') as f:\n        f.write('hi')\n";
        let effects = infer_effects_from_body(body);
        let cats: Vec<_> = effects.iter().map(|e| e.effect.clone()).collect();
        assert!(cats.contains(&EffectCategory::IoFsRead));
        assert!(cats.contains(&EffectCategory::IoFsWrite));
    }

    #[test]
    fn empty_when_no_patterns() {
        let body = "def f(x):\n    return x + 1\n";
        assert!(infer_effects_from_body(body).is_empty());
    }

    // ----- Plan L t-002: comment + string-literal false-positive guards -----

    #[test]
    fn comment_mentioning_open_does_not_infer_fs_effects() {
        // `open(` appears only in a comment; we must NOT infer fs.read.
        let body = "def f(x):\n    # consider open('/tmp/x') for cache\n    return x\n";
        let effects = infer_effects_from_body(body);
        let cats: Vec<_> = effects.iter().map(|e| e.effect.clone()).collect();
        assert!(
            !cats.contains(&EffectCategory::IoFsRead),
            "open() in a comment must not infer IoFsRead; got {cats:?}"
        );
    }

    #[test]
    fn string_literal_mentioning_open_does_not_infer_fs_effects() {
        // `open(` only inside a string literal — no real call.
        let body = "def f():\n    msg = 'use open(path) to load'\n    return msg\n";
        let effects = infer_effects_from_body(body);
        assert!(
            effects.is_empty(),
            "open() inside a string literal must not infer any effect; got {effects:?}"
        );
    }

    #[test]
    fn triple_string_docstring_mentioning_requests_does_not_infer_net() {
        // A docstring describing what `requests.get` would do — must
        // not infer IoNetOut.
        let body = r#"def f():
    """Pretend we call requests.get('https://example.com') here.

    But we don't actually.
    """
    return 42
"#;
        let effects = infer_effects_from_body(body);
        let cats: Vec<_> = effects.iter().map(|e| e.effect.clone()).collect();
        assert!(
            !cats.contains(&EffectCategory::IoNetOut),
            "requests.* in a docstring must not infer IoNetOut; got {cats:?}"
        );
    }

    #[test]
    fn real_requests_call_infers_net_out() {
        // The positive counterpart to the docstring test above. A live
        // `requests.get(url)` MUST infer IoNetOut. Regression guard for the
        // dead-code bug where `find_calls(scan, "requests.")` returned nothing
        // because the prefix didn't end in `(` — found by the cross-language
        // conformance matrix (effects column was blank for Python).
        for body in [
            "def f():\n    return requests.get('https://api.svc/x')\n",
            "def f():\n    return httpx.post('https://api.svc/x', json={})\n",
            "def f():\n    return requests.request('POST', 'https://api.svc/x')\n",
        ] {
            let cats: Vec<_> = infer_effects_from_body(body)
                .iter()
                .map(|e| e.effect.clone())
                .collect();
            assert!(
                cats.contains(&EffectCategory::IoNetOut),
                "expected IoNetOut for `{body}`; got {cats:?}"
            );
        }
    }

    #[test]
    fn real_open_still_fires_when_comment_also_mentions_it() {
        // The masking must not suppress a real call site that sits
        // next to a comment containing the same pattern.
        let body = "def f():\n    # open('/tmp/a') would also work\n    open('/tmp/b')\n";
        let effects = infer_effects_from_body(body);
        let cats: Vec<_> = effects.iter().map(|e| e.effect.clone()).collect();
        assert!(
            cats.contains(&EffectCategory::IoFsRead),
            "real open() must still infer IoFsRead even when a comment also mentions it; got {cats:?}"
        );
    }

    #[test]
    fn raise_inside_string_literal_does_not_infer_throw() {
        let body = "def f():\n    msg = 'do not raise here'\n    return msg\n";
        let effects = infer_effects_from_body(body);
        let cats: Vec<_> = effects.iter().map(|e| e.effect.clone()).collect();
        assert!(
            !cats.contains(&EffectCategory::Throw),
            "raise inside a string literal must not infer Throw; got {cats:?}"
        );
    }

    #[test]
    fn mask_preserves_byte_length_and_line_count() {
        // The downstream offset-based slicing relies on masked + body
        // being the same byte length AND splitting into the same lines.
        let body = "x = 'open(\"a\")'  # open(\"b\")\ny = 1\n";
        let masked = mask_comments_and_literals(body);
        assert_eq!(masked.len(), body.len(), "mask must preserve byte length");
        assert_eq!(
            masked.lines().count(),
            body.lines().count(),
            "mask must preserve line count"
        );
        // Spot check: `open(` inside the literal AND the comment must
        // be erased from the masked view.
        assert!(
            !masked.contains("open("),
            "masked source must not contain `open(` from literal or comment"
        );
    }

    #[test]
    fn mask_leaves_identifier_chars_alone() {
        // `request_open` is an identifier, not a string prefix —
        // masking must not eat the `r` thinking it's `r"…"`.
        let body = "request_open = 1\n";
        let masked = mask_comments_and_literals(body);
        assert_eq!(
            masked, body,
            "no comments/literals here; masked must equal original"
        );
    }

    #[test]
    fn mask_handles_raw_and_byte_string_prefixes() {
        let body = "x = r\"open('/tmp/a')\"\ny = b'open(\"b\")'\nz = rb\"open(\"c\")\"\n";
        let effects = infer_effects_from_body(body);
        assert!(
            effects.is_empty(),
            "raw/byte/raw-byte literals must mask their contents; got {effects:?}"
        );
    }

    /// Build a WorkspaceSymbols with just a set of qnames (kinds defaulted
    /// to Function). Tests don't currently exercise the kinds map.
    fn workspace_with(qnames: &[&str]) -> WorkspaceSymbols {
        let mut ws = WorkspaceSymbols::default();
        for q in qnames {
            ws.qnames.insert((*q).to_string());
            ws.kinds.insert((*q).to_string(), SymbolKind::Function);
        }
        ws
    }

    #[test]
    fn extracts_intra_module_call_edges() {
        let src = r#"
def helper(x):
    return x

def caller():
    return helper(1)

class C:
    def __init__(self):
        self.x = helper(2)

    def m(self):
        return self.__init__()
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("m.py", src).unwrap();
        let ws = workspace_with(&["m.helper", "m.caller", "m.C", "m.C.__init__", "m.C.m"]);
        let edges = a.extract_call_edges("m.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.contains(&("m.caller".to_string(), "m.helper".to_string())),
            "missing caller -> helper edge; got {pairs:?}",
        );
        assert!(
            pairs.contains(&("m.C.__init__".to_string(), "m.helper".to_string())),
            "missing C.__init__ -> helper edge; got {pairs:?}",
        );
        assert!(
            pairs.contains(&("m.C.m".to_string(), "m.C.__init__".to_string())),
            "missing C.m -> C.__init__ edge; got {pairs:?}",
        );
    }

    #[test]
    fn extracts_cross_module_edges_via_from_import() {
        // `from logger import write_log` — `write_log(...)` should resolve
        // to `logger.write_log`.
        let src = r#"
from logger import write_log

def foo():
    write_log("/tmp/x", "hi")
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("caller.py", src).unwrap();
        let ws = workspace_with(&["logger.write_log", "caller.foo"]);
        let edges = a.extract_call_edges("caller.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.contains(&("caller.foo".to_string(), "logger.write_log".to_string())),
            "missing foo -> logger.write_log edge; got {pairs:?}",
        );
    }

    #[test]
    fn extracts_cross_module_edges_via_module_import() {
        // `import logger` — `logger.write_log(...)` should resolve.
        let src = r#"
import logger

def foo():
    logger.write_log("/tmp/x", "hi")
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("caller.py", src).unwrap();
        let ws = workspace_with(&["logger.write_log", "caller.foo"]);
        let edges = a.extract_call_edges("caller.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.contains(&("caller.foo".to_string(), "logger.write_log".to_string())),
            "missing foo -> logger.write_log edge; got {pairs:?}",
        );
    }

    #[test]
    fn drops_unknown_imports() {
        // Workspace doesn't know about `stdlib_mod.thing` — no edge emitted.
        let src = r#"
import stdlib_mod

def foo():
    stdlib_mod.thing()
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("caller.py", src).unwrap();
        let ws = workspace_with(&["caller.foo"]);
        let edges = a.extract_call_edges("caller.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.is_empty(),
            "expected no edges for unknown imports; got {pairs:?}",
        );
    }

    #[test]
    fn import_alias_and_from_import_with_alias() {
        let src = r#"
import logger as lg
from greetings import hello as h

def foo():
    lg.write_log("/tmp/x", "hi")
    h("world")
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("caller.py", src).unwrap();
        let ws = workspace_with(&["logger.write_log", "greetings.hello", "caller.foo"]);
        let edges = a.extract_call_edges("caller.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.contains(&("caller.foo".to_string(), "logger.write_log".to_string())),
            "missing lg.write_log edge; got {pairs:?}",
        );
        assert!(
            pairs.contains(&("caller.foo".to_string(), "greetings.hello".to_string())),
            "missing h() edge; got {pairs:?}",
        );
    }

    #[test]
    fn local_definition_shadows_import() {
        // `helper` defined locally should win over `from x import helper`.
        let src = r#"
from other import helper

def helper(x):
    return x

def foo():
    helper(1)
"#;
        let a = PythonAdapter::new();
        let syms = a.parse_symbols("m.py", src).unwrap();
        let ws = workspace_with(&["other.helper", "m.helper", "m.foo"]);
        let edges = a.extract_call_edges("m.py", src, &syms, &ws);
        let pairs: Vec<(String, String)> = edges
            .iter()
            .map(|e| (e.caller_qname.clone(), e.callee_qname.clone()))
            .collect();
        assert!(
            pairs.contains(&("m.foo".to_string(), "m.helper".to_string())),
            "expected local helper to shadow import; got {pairs:?}",
        );
        assert!(
            !pairs.contains(&("m.foo".to_string(), "other.helper".to_string())),
            "expected imported helper to be shadowed; got {pairs:?}",
        );
    }

    #[test]
    fn default_extract_call_edges_returns_empty_for_unrelated_adapter() {
        // Sanity: ensure the trait method exists and the default returns empty.
        // This pins the behavior so callers can rely on it.
        struct Dummy;
        impl LanguageAdapter for Dummy {
            fn language(&self) -> &str {
                "dummy"
            }
            fn parse_symbols(&self, _f: &str, _s: &str) -> Result<Vec<ParsedSymbol>> {
                Ok(Vec::new())
            }
            fn infer_effects(&self, _s: &str, _p: &ParsedSymbol) -> Vec<Effect> {
                Vec::new()
            }
        }
        let d = Dummy;
        let ws = WorkspaceSymbols::default();
        assert!(d.extract_call_edges("x", "", &[], &ws).is_empty());
    }

    // -- Plan D t-004: relative-import resolver -----------------------------

    #[test]
    fn relative_dot_resolves_to_current_package() {
        // crucible/agents/litellm_agent.py → file qname = crucible.agents.litellm_agent
        // `from . import base` → "crucible.agents.base"
        let r = super::resolve_relative_import("crucible.agents.litellm_agent", ".").unwrap();
        assert_eq!(r, "crucible.agents");
    }

    #[test]
    fn relative_dot_with_suffix_appends_module() {
        let r = super::resolve_relative_import("crucible.agents.litellm_agent", ".base").unwrap();
        assert_eq!(r, "crucible.agents.base");
    }

    #[test]
    fn relative_double_dot_goes_up_one_more() {
        // `from ..util import x` from crucible/agents/litellm_agent.py
        // current package = crucible.agents; parent = crucible; "..util" → crucible.util
        let r = super::resolve_relative_import("crucible.agents.litellm_agent", "..util").unwrap();
        assert_eq!(r, "crucible.util");
    }

    #[test]
    fn relative_from_init_resolves_against_package() {
        // crucible/agents/__init__.py has module_prefix = crucible.agents.__init__
        // `from . import base` → drop 1 segment → crucible.agents; +"base" → crucible.agents.base
        let r = super::resolve_relative_import("crucible.agents.__init__", ".base").unwrap();
        assert_eq!(r, "crucible.agents.base");
    }

    #[test]
    fn relative_escaping_workspace_returns_none() {
        // Two dots when we only have one segment to drop.
        assert!(super::resolve_relative_import("crucible", "..foo").is_none());
    }

    // ---- Plan L t-006: unresolved-call reporter -----------------------

    #[test]
    fn unresolved_calls_reports_third_party_call() {
        // A call to a name that isn't in the workspace and isn't on
        // the stdlib allowlist should surface.
        use agentstatedeveloper_core::WorkspaceSymbols;
        let src = "import requests\n\ndef fetch(url):\n    return requests.get(url)\n";
        let parsed = vec![ParsedSymbol {
            qname: "app.client.fetch".into(),
            kind: SymbolKind::Function,
            start_line: 3,
            start_col: 0,
            end_line: 4,
            end_col: 30,
            signature: Some("def fetch(url)".into()),
            body: src.into(),
            doc: None,
        }];
        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("app.client.fetch".into());
        ws.kinds
            .insert("app.client.fetch".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let hits = report_unresolved_calls_in_python("app/client.py", src, &parsed, &ws);
        assert!(
            hits.iter().any(|h| h.callee_text.contains("requests")),
            "expected unresolved hint for requests.get; got {hits:?}"
        );
    }

    #[test]
    fn unresolved_calls_skips_stdlib_allowlist() {
        // print() / len() / range() must NOT show up as unresolved —
        // they're on the allowlist.
        use agentstatedeveloper_core::WorkspaceSymbols;
        let src = "def show(items):\n    print(len(items))\n    for i in range(3): pass\n";
        let parsed = vec![ParsedSymbol {
            qname: "app.show.show".into(),
            kind: SymbolKind::Function,
            start_line: 1,
            start_col: 0,
            end_line: 3,
            end_col: 30,
            signature: Some("def show(items)".into()),
            body: src.into(),
            doc: None,
        }];
        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("app.show.show".into());
        ws.kinds
            .insert("app.show.show".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let hits = report_unresolved_calls_in_python("app/show.py", src, &parsed, &ws);
        assert!(
            hits.is_empty(),
            "stdlib allowlist calls must not be reported; got {hits:?}"
        );
    }

    #[test]
    fn unresolved_calls_skips_resolved_internal_calls() {
        // A call to an internal symbol that resolves must NOT appear
        // in the unresolved list.
        use agentstatedeveloper_core::WorkspaceSymbols;
        let src = "def helper(): return 1\n\ndef use(): return helper()\n";
        let parsed = vec![
            ParsedSymbol {
                qname: "app.lib.helper".into(),
                kind: SymbolKind::Function,
                start_line: 1,
                start_col: 0,
                end_line: 1,
                end_col: 22,
                signature: Some("def helper()".into()),
                body: src.into(),
                doc: None,
            },
            ParsedSymbol {
                qname: "app.lib.use".into(),
                kind: SymbolKind::Function,
                start_line: 3,
                start_col: 0,
                end_line: 3,
                end_col: 25,
                signature: Some("def use()".into()),
                body: src.into(),
                doc: None,
            },
        ];
        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("app.lib.helper".into());
        ws.kinds
            .insert("app.lib.helper".into(), SymbolKind::Function);
        ws.qnames.insert("app.lib.use".into());
        ws.kinds.insert("app.lib.use".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let hits = report_unresolved_calls_in_python("app/lib.py", src, &parsed, &ws);
        assert!(
            !hits.iter().any(|h| h.callee_text == "helper"),
            "internal resolved call must not appear in unresolved list; got {hits:?}"
        );
    }

    // ---- Plan L t-005: dynamic-dispatch scanner -----------------------

    #[test]
    fn detects_getattr_call_pattern() {
        let src = "def dispatch(obj, name):\n    return getattr(obj, name)(42)\n";
        let hints = scan_dynamic_dispatch_in_python("app/dispatch.py", src);
        assert_eq!(hints.len(), 1, "expected 1 getattr hint; got {hints:?}");
        assert_eq!(hints[0].pattern, "getattr");
        assert_eq!(hints[0].line, 2);
        assert!(hints[0].snippet.contains("getattr(obj, name)(42)"));
    }

    #[test]
    fn getattr_without_trailing_call_is_not_flagged() {
        // A bare attribute read — not a dispatch — should NOT warn.
        let src = "def read(obj, name):\n    return getattr(obj, name, None)\n";
        let hints = scan_dynamic_dispatch_in_python("app/read.py", src);
        assert!(
            hints.is_empty(),
            "bare getattr (no trailing call) must not be flagged; got {hints:?}"
        );
    }

    #[test]
    fn detects_getattr_with_string_arg_then_call() {
        let src = "def go(obj):\n    return getattr(obj, 'method')(1, 2)\n";
        let hints = scan_dynamic_dispatch_in_python("app/go.py", src);
        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].pattern, "getattr");
    }

    #[test]
    fn detects_dunder_getattr_method_definition() {
        let src =
            "class Proxy:\n    def __getattr__(self, name):\n        return self._lookup(name)\n";
        let hints = scan_dynamic_dispatch_in_python("app/proxy.py", src);
        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].pattern, "__getattr__");
        assert_eq!(hints[0].line, 2);
    }

    #[test]
    fn detects_dunder_getattribute_method_definition() {
        let src = "class Strict:\n    def __getattribute__(self, name):\n        return super().__getattribute__(name)\n";
        let hints = scan_dynamic_dispatch_in_python("app/strict.py", src);
        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].pattern, "__getattr__");
    }

    #[test]
    fn getattr_inside_comment_or_string_is_masked() {
        // The scanner runs on masked source — a getattr in a comment
        // or string literal must NOT produce a warning.
        let src = "def f(obj):\n    # consider getattr(obj, 'x')(1) here\n    msg = 'use getattr(obj, x)(args) at runtime'\n    return msg\n";
        let hints = scan_dynamic_dispatch_in_python("app/f.py", src);
        assert!(
            hints.is_empty(),
            "getattr inside comment/string must not be flagged; got {hints:?}"
        );
    }

    // ---- Plan L t-004: nested-import resolution -----------------------

    #[test]
    fn extract_call_edges_resolves_function_body_import() {
        // `def f(): import requests; requests.get(...)` — the import
        // lives inside the function body, not at module scope. The
        // walker must descend into the body and pick it up.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        let src = "def f():\n    from pkg.util import helper\n    return helper()\n";

        let syms = vec![ParsedSymbol {
            qname: "app.main.f".into(),
            kind: SymbolKind::Function,
            start_line: 1,
            start_col: 0,
            end_line: 3,
            end_col: 22,
            signature: Some("def f()".into()),
            body: src.into(),
            doc: None,
        }];

        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("pkg.util.helper".into());
        ws.kinds
            .insert("pkg.util.helper".into(), SymbolKind::Function);
        ws.qnames.insert("app.main.f".into());
        ws.kinds.insert("app.main.f".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let edges = adapter.extract_call_edges("app/main.py", src, &syms, &ws);
        assert!(
            edges.iter().any(|e| e.callee_qname == "pkg.util.helper"),
            "function-body import must produce cross-module edge; got {edges:?}"
        );
    }

    #[test]
    fn extract_call_edges_resolves_if_typechecking_import() {
        // Imports inside `if TYPE_CHECKING:` blocks should also be
        // collected — the walker doesn't prune on conditional nodes.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        let src = "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from pkg.api import Client\n\ndef use():\n    return Client()\n";

        let syms = vec![ParsedSymbol {
            qname: "app.main.use".into(),
            kind: SymbolKind::Function,
            start_line: 6,
            start_col: 0,
            end_line: 7,
            end_col: 20,
            signature: Some("def use()".into()),
            body: src.into(),
            doc: None,
        }];

        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("pkg.api.Client".into());
        ws.kinds.insert("pkg.api.Client".into(), SymbolKind::Class);
        ws.qnames.insert("app.main.use".into());
        ws.kinds.insert("app.main.use".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let edges = adapter.extract_call_edges("app/main.py", src, &syms, &ws);
        assert!(
            edges.iter().any(|e| e.callee_qname == "pkg.api.Client"),
            "if TYPE_CHECKING import must resolve; got {edges:?}"
        );
    }

    #[test]
    fn extract_call_edges_resolves_try_except_import() {
        // `try: import cPickle as pickle / except: import pickle` —
        // the try-block import lives inside a `try_statement`. Walker
        // must descend.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        let src = "try:\n    from pkg.fast import loader\nexcept ImportError:\n    from pkg.slow import loader\n\ndef boot():\n    return loader()\n";

        let syms = vec![ParsedSymbol {
            qname: "app.main.boot".into(),
            kind: SymbolKind::Function,
            start_line: 6,
            start_col: 0,
            end_line: 7,
            end_col: 20,
            signature: Some("def boot()".into()),
            body: src.into(),
            doc: None,
        }];

        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("pkg.fast.loader".into());
        ws.kinds
            .insert("pkg.fast.loader".into(), SymbolKind::Function);
        ws.qnames.insert("pkg.slow.loader".into());
        ws.kinds
            .insert("pkg.slow.loader".into(), SymbolKind::Function);
        ws.qnames.insert("app.main.boot".into());
        ws.kinds
            .insert("app.main.boot".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let edges = adapter.extract_call_edges("app/main.py", src, &syms, &ws);
        // Either branch's resolution is acceptable — both are real
        // bindings in the same module. We just need at least one.
        let resolved = edges
            .iter()
            .any(|e| e.callee_qname == "pkg.fast.loader" || e.callee_qname == "pkg.slow.loader");
        assert!(
            resolved,
            "try/except import must resolve to one of the branches; got {edges:?}"
        );
    }

    #[test]
    fn module_scope_imports_still_resolve_after_nested_walker() {
        // Regression guard: the recursive walker must not break the
        // already-working module-scope case.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        let src = "from pkg.util import helper\n\ndef f():\n    return helper()\n";

        let syms = vec![ParsedSymbol {
            qname: "app.main.f".into(),
            kind: SymbolKind::Function,
            start_line: 3,
            start_col: 0,
            end_line: 4,
            end_col: 22,
            signature: Some("def f()".into()),
            body: src.into(),
            doc: None,
        }];

        let mut ws = WorkspaceSymbols::default();
        ws.qnames.insert("pkg.util.helper".into());
        ws.kinds
            .insert("pkg.util.helper".into(), SymbolKind::Function);
        ws.qnames.insert("app.main.f".into());
        ws.kinds.insert("app.main.f".into(), SymbolKind::Function);
        ws.build_suffix_index();

        let edges = adapter.extract_call_edges("app/main.py", src, &syms, &ws);
        assert!(
            edges.iter().any(|e| e.callee_qname == "pkg.util.helper"),
            "module-scope import must still resolve; got {edges:?}"
        );
    }

    #[test]
    fn extract_call_edges_resolves_double_dot_relative_import() {
        // Plan L t-003 acceptance gate: the double-dot case
        // (`from ..pkg import x`) was tested in isolation
        // (`relative_double_dot_goes_up_one_more`) but never end-to-end.
        // This locks in the full pipeline behavior so future refactors
        // can't silently regress on the two-dot case.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        // crucible.agents.litellm_agent imports from crucible.util
        // (two dots up: agents → crucible, then .util).
        let caller_src = "from ..util import helper\n\ndef act():\n    return helper()\n";

        let caller_syms = vec![ParsedSymbol {
            qname: "crucible.agents.litellm_agent.act".into(),
            kind: SymbolKind::Function,
            start_line: 3,
            start_col: 0,
            end_line: 4,
            end_col: 22,
            signature: Some("def act()".into()),
            body: caller_src.into(),
            doc: None,
        }];

        let mut workspace = WorkspaceSymbols::default();
        workspace.qnames.insert("crucible.util.helper".into());
        workspace
            .kinds
            .insert("crucible.util.helper".into(), SymbolKind::Function);
        workspace
            .qnames
            .insert("crucible.agents.litellm_agent.act".into());
        workspace.kinds.insert(
            "crucible.agents.litellm_agent.act".into(),
            SymbolKind::Function,
        );
        workspace.build_suffix_index();

        let edges = adapter.extract_call_edges(
            "crucible/agents/litellm_agent.py",
            caller_src,
            &caller_syms,
            &workspace,
        );

        assert!(
            edges
                .iter()
                .any(|e| e.callee_qname == "crucible.util.helper"),
            "expected double-dot relative import to produce cross-module edge to crucible.util.helper; got {edges:?}"
        );
    }

    #[test]
    fn extract_call_edges_resolves_relative_import_to_cross_module() {
        // End-to-end: a relative import + a call should produce a cross-module
        // CallEdge. This is the Crucible reproducer collapsed to a unit test.
        use crate::PythonAdapter;
        use agentstatedeveloper_core::{
            LanguageAdapter, ParsedSymbol, SymbolKind, WorkspaceSymbols,
        };

        let adapter = PythonAdapter::new();
        let caller_src =
            "from .base import make_decision\n\ndef act():\n    return make_decision()\n";

        let caller_syms = vec![ParsedSymbol {
            qname: "crucible.agents.litellm_agent.act".into(),
            kind: SymbolKind::Function,
            start_line: 3,
            start_col: 0,
            end_line: 4,
            end_col: 27,
            signature: Some("def act()".into()),
            body: caller_src.into(),
            doc: None,
        }];

        let mut workspace = WorkspaceSymbols::default();
        workspace
            .qnames
            .insert("crucible.agents.base.make_decision".into());
        workspace.kinds.insert(
            "crucible.agents.base.make_decision".into(),
            SymbolKind::Function,
        );
        workspace
            .qnames
            .insert("crucible.agents.litellm_agent.act".into());
        workspace.kinds.insert(
            "crucible.agents.litellm_agent.act".into(),
            SymbolKind::Function,
        );
        workspace.build_suffix_index();

        let edges = adapter.extract_call_edges(
            "crucible/agents/litellm_agent.py",
            caller_src,
            &caller_syms,
            &workspace,
        );

        assert!(
            edges
                .iter()
                .any(|e| e.callee_qname == "crucible.agents.base.make_decision"),
            "expected cross-module edge to crucible.agents.base.make_decision; got {edges:?}"
        );
    }
}

#[cfg(test)]
mod service_endpoint_tests {
    use super::*;
    use agentstatedeveloper_core::adapter::LanguageAdapter;

    fn detect(src: &str) -> Vec<DetectedEndpoint> {
        let a = PythonAdapter;
        let symbols = a.parse_symbols("app.py", src).unwrap();
        a.infer_service_endpoints("app.py", src, &symbols)
    }

    fn inbound(eps: &[DetectedEndpoint]) -> Vec<&DetectedEndpoint> {
        eps.iter()
            .filter(|e| e.direction == Direction::Inbound)
            .collect()
    }
    fn outbound(eps: &[DetectedEndpoint]) -> Vec<&DetectedEndpoint> {
        eps.iter()
            .filter(|e| e.direction == Direction::Outbound)
            .collect()
    }

    #[test]
    fn fastapi_decorator_route_is_inbound() {
        let src = "@app.get(\"/charge\")\ndef charge():\n    return 1\n";
        let eps = detect(src);
        let inb = inbound(&eps);
        assert_eq!(inb.len(), 1, "{eps:?}");
        assert_eq!(inb[0].contract, "http:GET /charge");
        assert!(
            inb[0].owner_qname.ends_with("charge"),
            "owner: {}",
            inb[0].owner_qname
        );
        assert!(inb[0].confidence > 0.9);
    }

    #[test]
    fn flask_route_with_methods_emits_one_per_method() {
        let src = "@app.route(\"/items\", methods=[\"GET\", \"POST\"])\ndef items():\n    pass\n";
        let eps = detect(src);
        let mut got: Vec<String> = inbound(&eps).iter().map(|e| e.contract.clone()).collect();
        got.sort();
        assert_eq!(
            got,
            vec![
                "http:GET /items".to_string(),
                "http:POST /items".to_string()
            ]
        );
    }

    #[test]
    fn flask_route_defaults_to_get() {
        let src = "@app.route(\"/ping\")\ndef ping():\n    pass\n";
        let eps = detect(src);
        let inb = inbound(&eps);
        assert_eq!(inb.len(), 1);
        assert_eq!(inb[0].contract, "http:GET /ping");
    }

    #[test]
    fn requests_client_call_is_outbound() {
        let src = "def pay():\n    requests.post(\"https://payments.svc/charge\", json=x)\n";
        let eps = detect(src);
        let out = outbound(&eps);
        assert_eq!(out.len(), 1, "{eps:?}");
        assert_eq!(out[0].contract, "http:POST /charge");
        assert!(
            out[0].owner_qname.ends_with("pay"),
            "owner: {}",
            out[0].owner_qname
        );
    }

    #[test]
    fn requests_request_method_first_arg() {
        let src = "def f():\n    httpx.request(\"DELETE\", \"https://api/things/{id}\")\n";
        let eps = detect(src);
        let out = outbound(&eps);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].contract, "http:DELETE /things/{}");
    }

    #[test]
    fn non_literal_urls_are_skipped() {
        // A variable and an f-string can't form a usable contract.
        let src = "def f():\n    requests.get(url)\n    requests.get(f\"/u/{i}\")\n";
        let eps = detect(src);
        assert!(outbound(&eps).is_empty(), "{eps:?}");
    }

    #[test]
    fn import_line_is_not_a_client_call() {
        let src = "import requests\n\ndef f():\n    return 1\n";
        assert!(detect(src).is_empty());
    }

    #[test]
    fn client_and_server_contracts_match_for_matching_endpoint() {
        // The whole point: an outbound client contract equals the inbound server
        // contract for the same logical endpoint, so match_edges would link them.
        let server = detect("@app.get(\"/users/{id}\")\ndef get_user(id):\n    pass\n");
        let client = detect("def fetch():\n    requests.get(\"https://users.svc/users/:id\")\n");
        assert_eq!(inbound(&server)[0].contract, outbound(&client)[0].contract);
        assert_eq!(inbound(&server)[0].contract, "http:GET /users/{}");
    }
}

#[cfg(test)]
mod dataflow_tests {
    use super::*;
    use agentstatedeveloper_core::adapter::{LanguageAdapter, WorkspaceSymbols};

    fn detect(src: &str) -> Vec<DetectedDataFlow> {
        let a = PythonAdapter;
        let symbols = a.parse_symbols("m.py", src).unwrap();
        a.extract_dataflow("m.py", src, &symbols, &WorkspaceSymbols::default())
    }

    #[test]
    fn same_file_call_maps_positional_args() {
        let src = "def helper(a, b):\n    return a\n\ndef caller():\n    helper(x, y)\n";
        let df = detect(src);
        assert_eq!(df.len(), 2, "{df:?}");
        assert!(df.iter().all(|d| d.callee_qname.ends_with("helper")));
        assert!(df.iter().all(|d| d.caller_qname.ends_with("caller")));
        let args: Vec<(usize, String)> = df.iter().map(|d| (d.arg_index, d.arg.clone())).collect();
        assert!(args.contains(&(0, "x".to_string())));
        assert!(args.contains(&(1, "y".to_string())));
    }

    #[test]
    fn method_calls_are_skipped() {
        let src = "def caller():\n    obj.helper(x)\n";
        assert!(detect(src).is_empty(), "{:?}", detect(src));
    }

    #[test]
    fn unknown_or_cross_file_callee_skipped() {
        // helper isn't defined in this file → not resolved (cross-file is a follow-up).
        let src = "def caller():\n    helper(x)\n";
        assert!(detect(src).is_empty());
    }

    #[test]
    fn non_identifier_args_are_skipped() {
        let src = "def helper(a):\n    pass\n\ndef caller():\n    helper(\"lit\")\n    helper(g(x))\n    helper(a + b)\n";
        assert!(detect(src).is_empty(), "{:?}", detect(src));
    }

    #[test]
    fn ambiguous_callee_name_skipped() {
        let src = "def helper(a):\n    pass\n\ndef helper(b):\n    pass\n\ndef caller():\n    helper(x)\n";
        assert!(detect(src).is_empty(), "{:?}", detect(src));
    }
}

#[cfg(test)]
mod pubsub_tests {
    use super::*;
    use agentstatedeveloper_core::adapter::LanguageAdapter;

    fn detect(src: &str) -> Vec<DetectedEndpoint> {
        let a = PythonAdapter;
        let symbols = a.parse_symbols("tasks.py", src).unwrap();
        a.infer_service_endpoints("tasks.py", src, &symbols)
    }
    fn ps(eps: &[DetectedEndpoint], dir: Direction) -> Vec<&DetectedEndpoint> {
        eps.iter()
            .filter(|e| e.transport == Transport::PubSub && e.direction == dir)
            .collect()
    }

    #[test]
    fn shared_task_is_a_listener() {
        let eps = detect("@shared_task\ndef process_order(o):\n    return o\n");
        let inb = ps(&eps, Direction::Inbound);
        assert_eq!(inb.len(), 1, "{eps:?}");
        assert_eq!(inb[0].contract, "topic:process_order");
    }

    #[test]
    fn delay_call_is_an_emit() {
        let eps = detect("def caller():\n    process_order.delay(payload)\n");
        let outb = ps(&eps, Direction::Outbound);
        assert_eq!(outb.len(), 1);
        assert_eq!(outb[0].contract, "topic:process_order");
    }

    #[test]
    fn listener_and_emit_share_one_contract() {
        let src = "@app.task(bind=True)\ndef send_email(addr):\n    pass\n\ndef trigger():\n    send_email.apply_async((a,))\n";
        let eps = detect(src);
        assert_eq!(
            ps(&eps, Direction::Inbound)[0].contract,
            ps(&eps, Direction::Outbound)[0].contract
        );
        assert_eq!(ps(&eps, Direction::Inbound)[0].contract, "topic:send_email");
    }

    #[test]
    fn non_celery_decorator_is_not_a_listener() {
        // @property / @app.get(...) must not register as a pub-sub listener.
        assert!(
            ps(
                &detect("@property\ndef value(self):\n    return 1\n"),
                Direction::Inbound
            )
            .is_empty()
        );
        let http = detect("@app.get(\"/x\")\ndef h():\n    pass\n");
        assert!(ps(&http, Direction::Inbound).is_empty());
    }
}