ripvec-core 4.1.15

Semantic code + document search engine. Cacheless static-embedding + cross-encoder rerank by default; optional ModernBERT/BGE transformer engines with GPU backends. Tree-sitter chunking, hybrid BM25 + PageRank, composable ranking layers.
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
//! Per-language entry-point detection for the `find_dead_code` MCP tool
//! (4.1.0).
//!
//! The trait [`EntryPointDetector`] and its per-language implementors
//! ([`RustEntryDetector`], [`PythonEntryDetector`], [`GoEntryDetector`])
//! identify the syntactic shapes that act as roots of the call graph: the
//! BFS reachability walk for dead-code detection seeds from the union of
//! all [`EntryPoint`]s emitted across the indexed corpus.
//!
//! This module is X1 of the 4.1.0 series; the actual reachability walk and
//! cluster discovery (`RepoGraph::compute_dead_code`) lands in X2. The MCP
//! tool wrapper lands in X3. The remaining language detectors land in X4.
//! See `docs/FIND_DEAD_CODE_DESIGN.md` Section 2 for the per-language
//! entry-point survey and Section 3 for the algorithm that consumes this
//! output.
//!
//! ## Type B (Wired-Stub) self-audit note
//!
//! Until X2 lands, every public item in this module is consumed only from
//! the integration tests under `crates/ripvec-core/tests/entry_points.rs`.
//! `scripts/check_wiring_gaps.sh` will report these as Type B findings.
//! The findings are **explicitly deferred** to X2 — see the Section 9
//! PLAN.md entry — not silently dangling. Do not annotate with
//! `#[doc(hidden)]`: the doc-visibility surface is part of the X2 contract
//! and is the intended public API of the dead-code module.

use std::path::{Path, PathBuf};

use streaming_iterator::StreamingIterator;
use tree_sitter::{Node, Parser, Query, QueryCursor};

/// Classification of why a [`Definition`](crate::repo_map::Definition)-shaped
/// item is treated as an entry point for the dead-code reachability walk.
///
/// Categories follow Section 2 of `docs/FIND_DEAD_CODE_DESIGN.md`. The
/// classification is per-detection, not per-definition: the same
/// `pub fn` can appear as both [`EntryPointKind::Main`] (for binaries) and
/// [`EntryPointKind::LibraryExport`] (for libraries) depending on how the
/// containing crate is structured. Downstream consumers (X2) treat each
/// detection independently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryPointKind {
    /// A binary-crate `main`-shaped entry: `fn main()` in Rust, `func main()`
    /// in Go, the `if __name__ == "__main__"` block in Python.
    Main,

    /// A public-API surface item: `pub` re-exports in Rust libraries,
    /// `__all__` exports in Python, capitalised names in Go libraries.
    LibraryExport,

    /// A test entry: `#[test]` / `#[bench]` in Rust, `def test_*` /
    /// `*_test.py` in Python, `func TestX` / `BenchmarkX` / `ExampleX` /
    /// `FuzzX` in Go.
    Test,

    /// A foreign-function-interface entry: `#[no_mangle]` /
    /// `extern "C"` in Rust, cgo `//export` in Go.
    Ffi,

    /// A procedural-macro entry: `#[proc_macro]`, `#[proc_macro_derive]`,
    /// `#[proc_macro_attribute]` in Rust.
    ProcMacro,

    /// A package-initialisation entry: `func init()` in Go.
    Init,

    /// A build-script entry: Cargo's `build.rs`.
    BuildScript,

    /// A method invoked by a framework-generated dispatcher whose call site
    /// the static call graph cannot see — e.g. rmcp's `#[tool(...)]`
    /// methods, whose dispatch table is synthesised by a procedural macro
    /// at compile time. Without explicit seeding these methods appear dead
    /// to BFS reachability even though they are the user-facing API.
    ///
    /// Added in 4.1.1 (Wave 1 Front A, node A4) after live measurement
    /// against ripvec itself reported `dead_fraction = 0.986` because
    /// every `#[tool]`-annotated worker was unreachable from the call
    /// graph — see `DEV_JOURNAL.md` 4.1.1 entry.
    FrameworkDispatched,
}

/// A single entry-point detection in one source file.
///
/// Per-detection, not per-definition — the same `pub fn` can produce
/// multiple `EntryPoint` instances (one for each matching predicate).
/// Downstream consumers should treat each detection as an independent
/// reachability seed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryPoint {
    /// The symbol name of the entry point. For Rust this is the function
    /// item identifier; for Python it is the function or module-level
    /// expression name; for Go it is the function declaration identifier.
    pub name: String,

    /// Why this item was treated as an entry point.
    pub kind: EntryPointKind,

    /// The source file the entry point was detected in.
    pub file_path: PathBuf,

    /// 1-based line number of the entry point declaration. Matches the
    /// `start_line` field of [`crate::repo_map::Definition`].
    pub line: u32,
}

/// Per-language entry-point detector.
///
/// Designed for consumption by `RepoGraph::compute_dead_code` in
/// 4.1.0-X2. Until X2 lands, the only consumers are the integration tests
/// under `crates/ripvec-core/tests/entry_points.rs` — see the
/// module-level docstring for the Type B (Wired-Stub) self-audit note.
///
/// Implementations parse the source once per call. The parsing cost is
/// trivial (tree-sitter is O(n) and the source is already in memory at
/// detection time), and stateless parsers compose more cleanly than a
/// shared parser cache across the three (and eventually eleven) language
/// detectors. X2's `RepoGraph::compute_dead_code` already iterates
/// per-file, so the per-file parse adds no additional walk cost.
pub trait EntryPointDetector {
    /// Return every entry point declared in this source file.
    ///
    /// `source` is the full UTF-8 contents of `file_path`. The path is
    /// passed alongside `source` so detectors that consider filename
    /// patterns (e.g. Python's `test_*.py` and `*_test.py`,
    /// Rust's `build.rs`) can use both signals.
    ///
    /// If parsing fails, returns an empty vector — entry-point detection
    /// is best-effort and should never abort the dead-code walk.
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint>;
}

// ---------------------------------------------------------------------------
// Rust detector
// ---------------------------------------------------------------------------

/// Rust entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2 + 4.1.1 Front A
/// widening):
/// - `pub fn main()` and bare `fn main()` (Main)
/// - `pub fn` items in `lib.rs` / `mod.rs` (LibraryExport)
/// - `pub use` re-exports in `lib.rs` / `mod.rs` (LibraryExport, A1)
/// - Top-level `fn main` in `examples/*.rs` / `benches/*.rs` (Main, A2)
/// - Criterion `pub fn benches()` in `benches/*.rs` (Main, A2)
/// - Items annotated with `#[test]` or `#[bench]` (Test)
/// - Items annotated with `#[no_mangle]` or marked `extern "C"` (Ffi)
/// - Items annotated with `#[proc_macro]`, `#[proc_macro_derive]`, or
///   `#[proc_macro_attribute]` (ProcMacro)
/// - Methods annotated with `#[tool(...)]` or every method inside
///   `#[tool_router] impl ...` (FrameworkDispatched, A3)
/// - The entire `build.rs` file is treated as a single BuildScript entry
///   point (the build script's `main` is the cargo-known entry).
///
/// File-path role detection lives in [`rust_file_role`]: lib/mod files
/// gain LibraryExport surfacing, examples/benches files surface their
/// top-level `fn main` and `pub fn` items as cargo-known entries.
#[derive(Debug, Default, Clone, Copy)]
pub struct RustEntryDetector;

/// Classification of a Rust source file by its role in the cargo workspace.
///
/// The detector uses this to widen entry-point recognition beyond what is
/// observable from source alone: `examples/*.rs` and `benches/*.rs` files
/// are cargo-known entries even when their `fn main` carries no annotation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RustFileRole {
    /// `src/lib.rs` or any `mod.rs` — the crate's published interface.
    LibOrMod,
    /// A file under `examples/` (cargo example binary).
    Example,
    /// A file under `benches/` (cargo benchmark target).
    Bench,
    /// Anything else.
    Other,
}

/// Determine which cargo role a Rust source path plays.
///
/// Examples and benches are recognised by any `examples` / `benches`
/// component in the path — cargo only honours top-level `examples/` and
/// `benches/` directories per crate, but the path-component check is
/// sufficient for our entry-point purposes (a synthetic file we test
/// against may live anywhere on disk).
fn rust_file_role(file_path: &Path) -> RustFileRole {
    if matches!(
        file_path.file_name().and_then(|s| s.to_str()),
        Some("lib.rs" | "mod.rs")
    ) {
        return RustFileRole::LibOrMod;
    }
    for component in file_path.components() {
        match component.as_os_str().to_str() {
            Some("examples") => return RustFileRole::Example,
            Some("benches") => return RustFileRole::Bench,
            _ => {}
        }
    }
    RustFileRole::Other
}

impl EntryPointDetector for RustEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_rust::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Treat the entire build.rs file as a single BuildScript entry.
        // The crate's main may be named anything inside build.rs (cargo
        // calls the file's main), so we emit one entry at line 1.
        if file_path.file_name().and_then(|s| s.to_str()) == Some("build.rs") {
            entries.push(EntryPoint {
                name: "build.rs".to_string(),
                kind: EntryPointKind::BuildScript,
                file_path: file_path.to_path_buf(),
                line: 1,
            });
        }

        let role = rust_file_role(file_path);

        // A1: `pub use` re-exports in lib.rs / mod.rs surface the named
        // items as LibraryExport entry points. Walk the top-level
        // children — re-exports are only meaningful at module scope.
        if role == RustFileRole::LibOrMod {
            let mut cursor = root.walk();
            for child in root.children(&mut cursor) {
                if child.kind() == "use_declaration" && rust_use_is_pub(&child, bytes) {
                    collect_rust_pub_use_entries(&child, bytes, file_path, &mut entries);
                }
            }
        }

        // A3: `#[tool_router] impl ...` blocks make every method inside
        // them framework-dispatched. Walk the AST top-down looking for
        // impl_item nodes with a preceding `#[tool_router]` attribute and
        // emit FrameworkDispatched entries for each contained method.
        visit_rust_tool_router_impls(&root, bytes, file_path, &mut entries);

        // Walk every function_item declaration recursively. For each item:
        //   - inspect its preceding attribute_item siblings for #[test],
        //     #[bench], #[no_mangle], #[proc_macro*], #[tool(...)]
        //   - inspect the function_item's own modifiers for `extern "C"`
        //   - inspect the name for `main`
        //   - if file is lib.rs/mod.rs and the item is `pub`, emit
        //     LibraryExport
        //   - if file is examples/*.rs and the item is `fn main`, emit Main
        //   - if file is benches/*.rs and the item is `fn main` or
        //     `pub fn benches`, emit Main
        visit_rust_node(&root, bytes, file_path, role, &mut entries);
        entries
    }
}

fn visit_rust_node(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    role: RustFileRole,
    out: &mut Vec<EntryPoint>,
) {
    if node.kind() == "function_item" {
        rust_classify_function(node, bytes, file_path, role, out);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        visit_rust_node(&child, bytes, file_path, role, out);
    }
}

fn rust_classify_function(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    role: RustFileRole,
    out: &mut Vec<EntryPoint>,
) {
    // Find the function name. function_item has a `name` field whose
    // value is an identifier child.
    let name_node = node.child_by_field_name("name");
    let Some(name_node) = name_node else { return };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);

    // Gather attributes that immediately precede this function. In
    // tree-sitter-rust the attributes are SIBLING attribute_item nodes,
    // not children of the function_item, so we walk previous siblings.
    let attrs = collect_preceding_rust_attrs(node, bytes);

    // A single function item may match multiple predicates (e.g. a
    // `#[no_mangle] pub extern "C" fn main` in `lib.rs` is both Ffi
    // and Main and LibraryExport). Emit one EntryPoint per matching
    // predicate; the BFS in X2 treats each detection as a distinct
    // reachability seed.

    // #[proc_macro], #[proc_macro_derive], #[proc_macro_attribute].
    if attrs.iter().any(|a| {
        a.starts_with("proc_macro_derive")
            || a.starts_with("proc_macro_attribute")
            || a == "proc_macro"
            || a.starts_with("proc_macro(")
    }) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::ProcMacro,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // #[test] / #[bench].
    if attrs.iter().any(|a| a == "test" || a == "bench") {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // FFI: #[no_mangle] OR `extern "C"` in the function declaration.
    let function_text =
        std::str::from_utf8(&bytes[node.start_byte()..node.end_byte()]).unwrap_or("");
    let has_extern_c =
        rust_function_has_extern_c(node, bytes) || function_text.contains("extern \"C\"");
    if attrs.iter().any(|a| a == "no_mangle") || has_extern_c {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Ffi,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // A3: `#[tool(...)]` framework-dispatched method.
    if attrs.iter().any(|a| a == "tool" || a.starts_with("tool(")) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::FrameworkDispatched,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // Main: `fn main` (with or without `pub`).
    if name == "main" {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // LibraryExport: `pub fn` in lib.rs / mod.rs.
    if role == RustFileRole::LibOrMod && rust_function_is_pub(node, bytes) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // A2: Criterion benches expose `pub fn benches()` invoked via the
    // `criterion_main!` macro. Treat any top-level `pub fn` in a
    // `benches/*.rs` file as a Main entry — cargo's bench target invokes
    // it as a binary entry.
    if role == RustFileRole::Bench
        && rust_function_is_pub(node, bytes)
        && is_top_level_in_source(node)
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Return true if this node sits at the source-file root (its parent
/// chain reaches `source_file` with no intervening item-bearing scope).
///
/// Used to scope examples/benches `pub fn` recognition to module-level
/// declarations only.
fn is_top_level_in_source(node: &Node<'_>) -> bool {
    node.parent().is_some_and(|p| p.kind() == "source_file")
}

/// Collect the text of every `#[...]` attribute node that immediately
/// precedes this function_item in source order. The returned strings are
/// the attribute path/identifier (e.g. `"test"`, `"no_mangle"`,
/// `"proc_macro_derive(Foo)"`), with the leading `#[` and trailing `]`
/// stripped, and any leading `outer_attribute_item` `#[` punctuation
/// removed.
fn collect_preceding_rust_attrs(node: &Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut attrs = Vec::new();
    let mut prev = node.prev_sibling();
    while let Some(p) = prev {
        if p.kind() == "attribute_item" || p.kind() == "inner_attribute_item" {
            // The attribute_item child structure is `# [ attribute ]`;
            // pull the `attribute` child and use its text.
            let mut cursor = p.walk();
            let mut attr_text: Option<String> = None;
            for child in p.children(&mut cursor) {
                if child.kind() == "attribute"
                    && let Ok(text) =
                        std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
                {
                    attr_text = Some(text.to_string());
                }
            }
            if let Some(t) = attr_text {
                attrs.push(t);
            }
            prev = p.prev_sibling();
        } else if p.kind().starts_with("line_comment") || p.kind().starts_with("block_comment") {
            prev = p.prev_sibling();
        } else {
            break;
        }
    }
    attrs
}

/// Return true if the function_item node has a `pub` visibility modifier.
fn rust_function_is_pub(node: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier"
            && let Ok(text) = std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
        {
            return text.starts_with("pub");
        }
    }
    false
}

/// Return true if a `use_declaration` node carries a `pub` visibility
/// modifier (i.e. it is a `pub use ...;` re-export).
fn rust_use_is_pub(node: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier"
            && let Ok(text) = std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
        {
            return text.starts_with("pub");
        }
    }
    false
}

/// Collect [`EntryPoint`]s for each name re-exported by a
/// `pub use ...;` declaration.
///
/// Handles the four common shapes from `docs/PLAN.md` cluster A:
/// - `pub use ::path::to::Item;` — emit `Item` (the trailing segment).
/// - `pub use ::path::to::*;` — emit a glob entry whose `name` is the
///   full path (the consumer at graph-walk time fans out to every
///   matching definition).
/// - `pub use ::path::to::{Foo, Bar};` — emit `Foo` and `Bar`.
/// - `pub use ::path::to::Item as Alias;` — emit `Alias` (the alias is
///   the exported surface name).
fn collect_rust_pub_use_entries(
    use_decl: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let line = u32::try_from(use_decl.start_position().row + 1).unwrap_or(u32::MAX);
    // Find the `argument` field of the use_declaration (tree-sitter-rust
    // names the use tree this way). Fall back to walking children if the
    // field is missing on this grammar version.
    let argument = use_decl.child_by_field_name("argument").or_else(|| {
        let mut cursor = use_decl.walk();
        let mut found: Option<Node<'_>> = None;
        for child in use_decl.children(&mut cursor) {
            match child.kind() {
                "scoped_identifier" | "scoped_use_list" | "use_list" | "use_as_clause"
                | "use_wildcard" | "identifier" => {
                    found = Some(child);
                    break;
                }
                _ => {}
            }
        }
        found
    });
    let Some(argument) = argument else { return };
    rust_collect_use_tree(&argument, bytes, file_path, line, out);
}

/// Recursively walk a `pub use` tree, emitting one [`EntryPoint`] per
/// leaf name (or one glob entry per `::*`).
fn rust_collect_use_tree(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    line: u32,
    out: &mut Vec<EntryPoint>,
) {
    match node.kind() {
        // Wildcard: `path::*` — emit the whole path as the entry name.
        "use_wildcard" => {
            if let Ok(text) = std::str::from_utf8(&bytes[node.start_byte()..node.end_byte()]) {
                let trimmed = text.trim();
                let normalised = trimmed.replace(char::is_whitespace, "");
                out.push(EntryPoint {
                    name: normalised,
                    kind: EntryPointKind::LibraryExport,
                    file_path: file_path.to_path_buf(),
                    line,
                });
            }
        }
        // Braced group: `path::{Foo, Bar as Baz, sub::Qux}` — recurse
        // into each element.
        "use_list" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if matches!(child.kind(), "," | "{" | "}") {
                    continue;
                }
                rust_collect_use_tree(&child, bytes, file_path, line, out);
            }
        }
        // `path::{...}` is a `scoped_use_list`; walk into the list child.
        "scoped_use_list" => {
            let list = node.child_by_field_name("list").or_else(|| {
                let mut cursor = node.walk();
                node.children(&mut cursor).find(|c| c.kind() == "use_list")
            });
            if let Some(list) = list {
                rust_collect_use_tree(&list, bytes, file_path, line, out);
            }
        }
        // `path::Item as Alias` — the alias is the exported name.
        "use_as_clause" => {
            let alias = node.child_by_field_name("alias");
            if let Some(alias) = alias
                && let Ok(text) = std::str::from_utf8(&bytes[alias.start_byte()..alias.end_byte()])
            {
                out.push(EntryPoint {
                    name: text.to_string(),
                    kind: EntryPointKind::LibraryExport,
                    file_path: file_path.to_path_buf(),
                    line,
                });
            }
        }
        // `crate::a::b::c::Item` — the trailing identifier is the export.
        "scoped_identifier" => {
            let name = node.child_by_field_name("name");
            if let Some(name) = name
                && let Ok(text) = std::str::from_utf8(&bytes[name.start_byte()..name.end_byte()])
            {
                out.push(EntryPoint {
                    name: text.to_string(),
                    kind: EntryPointKind::LibraryExport,
                    file_path: file_path.to_path_buf(),
                    line,
                });
            }
        }
        // Bare `Item` (e.g. `pub use Item;`).
        "identifier" => {
            if let Ok(text) = std::str::from_utf8(&bytes[node.start_byte()..node.end_byte()]) {
                out.push(EntryPoint {
                    name: text.to_string(),
                    kind: EntryPointKind::LibraryExport,
                    file_path: file_path.to_path_buf(),
                    line,
                });
            }
        }
        // Anything else (whitespace, punctuation, comments): ignore.
        _ => {}
    }
}

/// Walk the AST top-down looking for `#[tool_router] impl ...` blocks.
/// For each such impl block, emit a [`EntryPointKind::FrameworkDispatched`]
/// entry for every contained method.
fn visit_rust_tool_router_impls(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    if node.kind() == "impl_item" {
        let attrs = collect_preceding_rust_attrs(node, bytes);
        if attrs
            .iter()
            .any(|a| a == "tool_router" || a.starts_with("tool_router("))
        {
            // Walk the impl's body, emitting an entry per function_item.
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for child in body.children(&mut cursor) {
                    if child.kind() != "function_item" {
                        continue;
                    }
                    let Some(name_node) = child.child_by_field_name("name") else {
                        continue;
                    };
                    let Ok(name) =
                        std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
                    else {
                        continue;
                    };
                    let line = u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                    out.push(EntryPoint {
                        name: name.to_string(),
                        kind: EntryPointKind::FrameworkDispatched,
                        file_path: file_path.to_path_buf(),
                        line,
                    });
                }
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        visit_rust_tool_router_impls(&child, bytes, file_path, out);
    }
}

/// Return true if the function_item has an `extern "C"` ABI declaration
/// as a function-modifier child (e.g. `pub extern "C" fn bar()`).
fn rust_function_has_extern_c(node: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        // tree-sitter-rust uses `function_modifiers` containing
        // `extern_modifier`; the latter's child is a `string_literal`
        // with the ABI name.
        if child.kind() != "function_modifiers" {
            continue;
        }
        let mut inner = child.walk();
        for grandchild in child.children(&mut inner) {
            if grandchild.kind() == "extern_modifier"
                && let Ok(text) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
                && text.contains("\"C\"")
            {
                return true;
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Python detector
// ---------------------------------------------------------------------------

/// Python entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2 + Cycle 9
/// B-0007 widening):
/// - `if __name__ == "__main__":` blocks at module top level (Main)
/// - Functions directly called from within the `__main__` block (Main) —
///   e.g. `main()` or `cli()`. Seeds the actual callable as a BFS root.
/// - Top-level functions decorated with `@click.command()`,
///   `@typer.command()`, or any `@X.command()` pattern (Main).
/// - Top-level functions named in `__all__` (LibraryExport)
/// - Functions starting with `test_` in files matching `test_*.py` /
///   `*_test.py` or under a `tests/` directory (Test)
#[derive(Debug, Default, Clone, Copy)]
pub struct PythonEntryDetector;

impl EntryPointDetector for PythonEntryDetector {
    #[expect(
        clippy::too_many_lines,
        reason = "two-pass detection: first-pass collects top-level fn names and CLI decorators, second-pass emits entries; helper functions keep individual pieces readable"
    )]
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_python::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        let is_test_file = python_is_test_file(file_path);

        // First pass: collect top-level function names and CLI decorators.
        let mut toplevel_fns: Vec<(String, u32)> = Vec::new();
        let mut click_decorated: Vec<(String, u32)> = Vec::new();
        {
            let mut cursor = root.walk();
            for child in root.children(&mut cursor) {
                match child.kind() {
                    "function_definition" => {
                        if let Some(name_node) = child.child_by_field_name("name")
                            && let Ok(name) = std::str::from_utf8(
                                &bytes[name_node.start_byte()..name_node.end_byte()],
                            )
                        {
                            let line =
                                u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                            toplevel_fns.push((name.to_string(), line));
                        }
                    }
                    "decorated_definition" => {
                        if let Some(fn_node) = child.child_by_field_name("definition")
                            && fn_node.kind() == "function_definition"
                            && let Some(name_node) = fn_node.child_by_field_name("name")
                            && let Ok(name) = std::str::from_utf8(
                                &bytes[name_node.start_byte()..name_node.end_byte()],
                            )
                        {
                            let line =
                                u32::try_from(fn_node.start_position().row + 1).unwrap_or(u32::MAX);
                            toplevel_fns.push((name.to_string(), line));
                            if python_has_cli_command_decorator(&child, bytes) {
                                click_decorated.push((name.to_string(), line));
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        // Second pass: emit entry points.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            match child.kind() {
                "if_statement" if python_is_dunder_main_block(&child, bytes) => {
                    let line = u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                    entries.push(EntryPoint {
                        name: "__main__".to_string(),
                        kind: EntryPointKind::Main,
                        file_path: file_path.to_path_buf(),
                        line,
                    });
                    // Also emit functions called directly in the block body.
                    // tree-sitter-python uses "consequence" for the block,
                    // not "body".
                    if let Some(body) = child.child_by_field_name("consequence") {
                        for called in python_direct_calls_in_block(&body, bytes) {
                            let fn_line = toplevel_fns
                                .iter()
                                .find(|(n, _)| n == &called)
                                .map(|(_, l)| *l)
                                .unwrap_or(line);
                            entries.push(EntryPoint {
                                name: called,
                                kind: EntryPointKind::Main,
                                file_path: file_path.to_path_buf(),
                                line: fn_line,
                            });
                        }
                    }
                }
                "expression_statement" => {
                    // `__all__ = [...]` is an expression_statement
                    // containing an assignment.
                    if let Some(names) = python_extract_dunder_all(&child, bytes) {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        for n in names {
                            entries.push(EntryPoint {
                                name: n,
                                kind: EntryPointKind::LibraryExport,
                                file_path: file_path.to_path_buf(),
                                line,
                            });
                        }
                    }
                }
                "function_definition" | "decorated_definition" => {
                    let fn_node = if child.kind() == "decorated_definition" {
                        child.child_by_field_name("definition")
                    } else {
                        Some(child)
                    };
                    if let Some(fn_node) = fn_node
                        && fn_node.kind() == "function_definition"
                        && let Some(name_node) = fn_node.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                        && is_test_file
                        && name.starts_with("test_")
                    {
                        let line =
                            u32::try_from(fn_node.start_position().row + 1).unwrap_or(u32::MAX);
                        entries.push(EntryPoint {
                            name: name.to_string(),
                            kind: EntryPointKind::Test,
                            file_path: file_path.to_path_buf(),
                            line,
                        });
                    }
                }
                _ => {}
            }
        }

        // Emit @click.command() / @typer.command() decorated functions.
        for (name, line) in click_decorated {
            entries.push(EntryPoint {
                name,
                kind: EntryPointKind::Main,
                file_path: file_path.to_path_buf(),
                line,
            });
        }

        entries
    }
}

fn python_is_test_file(file_path: &Path) -> bool {
    let Some(file_name) = file_path.file_name().and_then(|s| s.to_str()) else {
        return false;
    };
    let is_py = Path::new(file_name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("py"));
    if !is_py {
        return false;
    }
    let stem = Path::new(file_name)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    if stem.starts_with("test_") || stem.ends_with("_test") {
        return true;
    }
    // Any component named `tests` in the parent directory chain.
    file_path
        .components()
        .any(|c| c.as_os_str() == std::ffi::OsStr::new("tests"))
}

fn python_is_dunder_main_block(node: &Node<'_>, bytes: &[u8]) -> bool {
    // if condition: comparison `__name__ == "__main__"`.
    let cond = node.child_by_field_name("condition");
    let Some(cond) = cond else { return false };
    let Ok(text) = std::str::from_utf8(&bytes[cond.start_byte()..cond.end_byte()]) else {
        return false;
    };
    // Tolerate single or double quotes around `__main__`.
    let normalized = text.replace(' ', "");
    normalized.contains("__name__==\"__main__\"")
        || normalized.contains("__name__=='__main__'")
        || normalized.contains("\"__main__\"==__name__")
        || normalized.contains("'__main__'==__name__")
}

/// Extract the string literals from a top-level `__all__ = [...]`
/// assignment. Returns `None` if the statement is not such an assignment.
fn python_extract_dunder_all(node: &Node<'_>, bytes: &[u8]) -> Option<Vec<String>> {
    // expression_statement -> assignment (left, right)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "assignment" {
            let left = child.child_by_field_name("left")?;
            let right = child.child_by_field_name("right")?;
            let left_text = std::str::from_utf8(&bytes[left.start_byte()..left.end_byte()]).ok()?;
            if left_text.trim() != "__all__" {
                return None;
            }
            // right is typically a `list` or `tuple` node containing
            // `string` children.
            let mut names = Vec::new();
            let mut inner = right.walk();
            for grandchild in right.children(&mut inner) {
                if grandchild.kind() != "string" {
                    continue;
                }
                // Walk the string node to find string_content child.
                let mut sc = grandchild.walk();
                let mut content_text: Option<String> = None;
                for sg in grandchild.children(&mut sc) {
                    if sg.kind() == "string_content"
                        && let Ok(t) = std::str::from_utf8(&bytes[sg.start_byte()..sg.end_byte()])
                    {
                        content_text = Some(t.to_string());
                    }
                }
                if let Some(t) = content_text {
                    names.push(t);
                } else if let Ok(raw) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
                {
                    // Fallback: strip the outer quotes from the raw
                    // string text.
                    let trimmed = raw.trim_matches(|c| c == '"' || c == '\'');
                    names.push(trimmed.to_string());
                }
            }
            return Some(names);
        }
    }
    None
}

/// Return the names of functions called as bare `name()` (no attribute
/// access) in the immediate statement children of a Python block node.
///
/// Used to extract the callable(s) invoked from an
/// `if __name__ == "__main__":` block body — typically a single call like
/// `main()` or `cli()`.  Restricted to top-level
/// `expression_statement → call → identifier` to avoid over-seeding.
fn python_direct_calls_in_block(block: &Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut names = Vec::new();
    let mut cursor = block.walk();
    for stmt in block.children(&mut cursor) {
        if stmt.kind() != "expression_statement" {
            continue;
        }
        let mut sc = stmt.walk();
        for expr in stmt.children(&mut sc) {
            if expr.kind() != "call" {
                continue;
            }
            if let Some(func_node) = expr.child_by_field_name("function")
                && func_node.kind() == "identifier"
                && let Ok(name) =
                    std::str::from_utf8(&bytes[func_node.start_byte()..func_node.end_byte()])
                && !name.is_empty()
            {
                names.push(name.to_string());
            }
        }
    }
    names
}

/// Return true if a `decorated_definition` node carries a CLI command
/// decorator matching `@X.command()` or `@X.command` (where X is any
/// module name such as `click`, `typer`, `app`, `cli`, etc.).
///
/// Only `.command` attribute access is matched — this covers all major
/// Python CLI frameworks conservatively.
fn python_has_cli_command_decorator(decorated_def: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = decorated_def.walk();
    for child in decorated_def.children(&mut cursor) {
        if child.kind() != "decorator" {
            continue;
        }
        let mut dc = child.walk();
        for inner in child.children(&mut dc) {
            match inner.kind() {
                "call" => {
                    if let Some(func) = inner.child_by_field_name("function")
                        && func.kind() == "attribute"
                        && let Some(prop) = func.child_by_field_name("attribute")
                        && let Ok(prop_text) =
                            std::str::from_utf8(&bytes[prop.start_byte()..prop.end_byte()])
                        && prop_text == "command"
                    {
                        return true;
                    }
                }
                "attribute" => {
                    if let Some(prop) = inner.child_by_field_name("attribute")
                        && let Ok(prop_text) =
                            std::str::from_utf8(&bytes[prop.start_byte()..prop.end_byte()])
                        && prop_text == "command"
                    {
                        return true;
                    }
                }
                _ => {}
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Go detector
// ---------------------------------------------------------------------------

/// Go entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2):
/// - `func main()` in `package main` (Main)
/// - `func init()` (Init) — runs automatically at package load
/// - Functions starting with `Test`, `Benchmark`, `Example`, `Fuzz` (Test)
/// - Exported names (starting with uppercase) in library packages
///   (LibraryExport)
#[derive(Debug, Default, Clone, Copy)]
pub struct GoEntryDetector;

impl EntryPointDetector for GoEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_go::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Determine the package name. `package main` enables `main` as
        // the binary entry; non-main packages are libraries whose
        // exported names are library entries.
        let package_name = go_package_name(&root, bytes).unwrap_or_default();
        let is_main_package = package_name == "main";

        // Walk top-level function_declaration / method_declaration nodes.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            match child.kind() {
                "function_declaration" => {
                    if let Some(name_node) = child.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                    {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        go_classify(name, line, is_main_package, file_path, &mut entries);
                    }
                }
                "method_declaration" => {
                    // Methods participate in LibraryExport only — main / init
                    // / Test* are exclusively free functions.
                    if let Some(name_node) = child.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                        && !is_main_package
                        && go_is_exported(name)
                    {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        entries.push(EntryPoint {
                            name: name.to_string(),
                            kind: EntryPointKind::LibraryExport,
                            file_path: file_path.to_path_buf(),
                            line,
                        });
                    }
                }
                _ => {}
            }
        }

        entries
    }
}

fn go_package_name(root: &Node<'_>, bytes: &[u8]) -> Option<String> {
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() != "package_clause" {
            continue;
        }
        let mut inner = child.walk();
        for grandchild in child.children(&mut inner) {
            if grandchild.kind() == "package_identifier"
                && let Ok(text) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
            {
                return Some(text.to_string());
            }
        }
    }
    None
}

fn go_classify(
    name: &str,
    line: u32,
    is_main_package: bool,
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    if name == "main" && is_main_package {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if name == "init" {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Init,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if name.starts_with("Test")
        || name.starts_with("Benchmark")
        || name.starts_with("Example")
        || name.starts_with("Fuzz")
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if !is_main_package && go_is_exported(name) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Return true if `name` starts with an ASCII uppercase letter, which is
/// Go's syntactic rule for an exported (package-public) identifier.
fn go_is_exported(name: &str) -> bool {
    name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
}

// ---------------------------------------------------------------------------
// C detector
// ---------------------------------------------------------------------------

/// C entry-point detector (I#73, Cycle 7 / 4.1.4).
///
/// Detects the following patterns as entry points:
/// - Any `function_definition` whose declarator resolves to the identifier
///   `main` — regardless of return type or parameter shape. This covers
///   `int main()`, `int main(int argc, char **argv)`, and the rare
///   pointer-return variant `int *main(void)`.
/// - `__attribute__((constructor))` annotated functions → [`EntryPointKind::Init`].
///   These run before `main` via ELF `.init_array`; they are BFS roots.
/// - `// export NAME` line comments (cgo-style FFI) → [`EntryPointKind::Ffi`].
///   Cgo emits these above C wrapper stubs for Go functions exported to C.
///
/// The detector does **not** attempt full C pre-processing. Macros that
/// expand to `main` or `__attribute__((constructor))` are not detected —
/// this is an acceptable limitation at this stage.
#[derive(Debug, Default, Clone, Copy)]
pub struct CEntryDetector;

impl EntryPointDetector for CEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_c::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Collect cgo `//export NAME` comments first — they are not tied to
        // any AST function node; we scan the source text directly.
        c_collect_cgo_exports(source, file_path, &mut entries);

        // Walk top-level declarations.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            if child.kind() == "function_definition" {
                c_classify_function(&child, bytes, file_path, &mut entries);
            }
        }

        entries
    }
}

/// Classify a C `function_definition` node and emit entry points as
/// appropriate.
///
/// Handles three cases:
/// 1. Declarator is a `function_declarator` directly — covers `int main(…)`.
/// 2. Declarator is a `pointer_declarator` wrapping a `function_declarator`
///    — covers `int *main(void)`.
/// 3. The function has an `__attribute__((constructor))` specifier — emit
///    an additional [`EntryPointKind::Init`] entry.
fn c_classify_function(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);

    // Resolve the innermost identifier name from the declarator.
    let Some(declarator) = node.child_by_field_name("declarator") else {
        return;
    };
    let Some(name) = c_resolve_function_name(&declarator, bytes) else {
        return;
    };

    // Check for `__attribute__((constructor))` — the attribute_specifier
    // appears as a direct child of the function_definition (before the
    // type or declarator fields).
    let has_constructor_attr = c_has_constructor_attribute(node, bytes);

    if name == "main" {
        out.push(EntryPoint {
            name: name.clone(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    if has_constructor_attr {
        out.push(EntryPoint {
            name,
            kind: EntryPointKind::Init,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Walk a C declarator node to extract the innermost `identifier` that
/// names the function. Handles:
/// - `function_declarator` with `declarator: identifier` (direct case)
/// - `pointer_declarator` → `function_declarator` → `identifier` (pointer
///   return type)
///
/// Returns `None` if the name cannot be resolved (e.g., anonymous
/// declarations or grammar variants not covered here).
fn c_resolve_function_name(declarator: &tree_sitter::Node<'_>, bytes: &[u8]) -> Option<String> {
    match declarator.kind() {
        "function_declarator" => {
            // The inner declarator field holds the name.
            let inner = declarator.child_by_field_name("declarator")?;
            c_resolve_function_name(&inner, bytes)
        }
        "pointer_declarator" => {
            // Recurse: pointer_declarator wraps another declarator.
            let inner = declarator.child_by_field_name("declarator")?;
            c_resolve_function_name(&inner, bytes)
        }
        "identifier" => {
            let text =
                std::str::from_utf8(&bytes[declarator.start_byte()..declarator.end_byte()]).ok()?;
            Some(text.to_string())
        }
        _ => None,
    }
}

/// Return true if the `function_definition` node has an
/// `__attribute__((constructor))` specifier as a direct child.
///
/// In tree-sitter-c the attribute appears as an `attribute_specifier`
/// child of `function_definition` (before the `type` field). The
/// `attribute_specifier` contains an `argument_list` whose first
/// element is an `identifier` with text `"constructor"`.
fn c_has_constructor_attribute(node: &tree_sitter::Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "attribute_specifier" {
            continue;
        }
        // Look for an argument_list child containing "constructor".
        let mut inner = child.walk();
        for grandchild in child.children(&mut inner) {
            if grandchild.kind() != "argument_list" {
                continue;
            }
            let mut arg_cur = grandchild.walk();
            for arg in grandchild.children(&mut arg_cur) {
                if arg.kind() == "identifier"
                    && std::str::from_utf8(&bytes[arg.start_byte()..arg.end_byte()])
                        .is_ok_and(|t| t == "constructor")
                {
                    return true;
                }
            }
        }
    }
    false
}

/// Scan the raw source for cgo-style `//export NAME` line comments and
/// emit [`EntryPointKind::Ffi`] entries for each exported name found.
///
/// cgo inserts these above the C stub for each Go function exported to C.
/// They are not associated with any AST node, so we scan the source text
/// directly. The format is exactly `//export <ident>` (no space after `//`).
fn c_collect_cgo_exports(source: &str, file_path: &Path, out: &mut Vec<EntryPoint>) {
    for (i, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("//export ") {
            let name = rest.trim();
            if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                let line_num = u32::try_from(i + 1).unwrap_or(u32::MAX);
                out.push(EntryPoint {
                    name: name.to_string(),
                    kind: EntryPointKind::Ffi,
                    file_path: file_path.to_path_buf(),
                    line: line_num,
                });
            }
        }
    }
}

// ---------------------------------------------------------------------------
// JavaScript / TypeScript detector
// ---------------------------------------------------------------------------

/// JavaScript and TypeScript entry-point detector (I#70, Cycle 7 / 4.1.4).
///
/// Detects the following patterns:
/// - `export default function NAME(…)` → [`EntryPointKind::LibraryExport`]
/// - `export default class NAME` → [`EntryPointKind::LibraryExport`]
/// - `export const NAME = (…) => …` (named arrow export) →
///   [`EntryPointKind::LibraryExport`]
/// - `module.exports = …` → [`EntryPointKind::LibraryExport`] (named
///   `module.exports`)
/// - `exports.NAME = …` → [`EntryPointKind::LibraryExport`]
/// - `test(…)`, `it(…)`, `describe(…)` calls in `*.test.js` /
///   `*.spec.js` / `*.test.ts` / `*.spec.ts` files →
///   [`EntryPointKind::Test`]
///
/// The detector uses `tree-sitter-javascript` for all JS/TS sources.
/// TypeScript-specific syntax (type annotations, decorators) is handled
/// gracefully because tree-sitter-javascript degrades cleanly on TS.
#[derive(Debug, Default, Clone, Copy)]
pub struct JsEntryDetector;

impl EntryPointDetector for JsEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_javascript::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        let is_test_file = js_is_test_file(file_path);

        // First pass: detect the CommonJS object-accumulation alias
        // `var app = exports = module.exports = {}` so the second pass
        // can recognise `app.METHOD = function...` as LibraryExport.
        let module_exports_alias = js_find_module_exports_alias(&root, bytes);

        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            match child.kind() {
                "export_statement" => {
                    js_classify_export(&child, bytes, file_path, &mut entries);
                }
                "expression_statement" => {
                    js_classify_expression_statement(
                        &child,
                        bytes,
                        file_path,
                        is_test_file,
                        module_exports_alias.as_deref(),
                        &mut entries,
                    );
                }
                _ => {}
            }
        }

        entries
    }
}

/// Return true if the file path indicates a JS/TS test file.
///
/// Matches `*.test.js`, `*.spec.js`, `*.test.ts`, `*.spec.ts`,
/// `*.test.jsx`, `*.spec.jsx`, `*.test.tsx`, `*.spec.tsx` and any file
/// under a `__tests__` directory.
fn js_is_test_file(file_path: &Path) -> bool {
    let Some(file_name) = file_path.file_name().and_then(|s| s.to_str()) else {
        return false;
    };
    // Check for .test.* or .spec.* before the final extension.
    let stem_lower = file_name.to_ascii_lowercase();
    if stem_lower.contains(".test.") || stem_lower.contains(".spec.") {
        return true;
    }
    // Check for __tests__ directory component.
    file_path
        .components()
        .any(|c| c.as_os_str() == std::ffi::OsStr::new("__tests__"))
}

/// Scan the top-level AST for the CommonJS object-accumulation pattern
/// `var ALIAS = exports = module.exports = {}` and return the local
/// variable name (`ALIAS`) if found.
///
/// The pattern appears in express's `lib/application.js`:
/// ```text
/// var app = exports = module.exports = {};
/// ```
/// Subsequent `app.use = function...`, `app.handle = function...` etc.
/// are all library exports whose reachability depends on knowing `app` is
/// the module.exports alias.
///
/// Returns the first alias found; returns `None` when the pattern is absent.
fn js_find_module_exports_alias(root: &tree_sitter::Node<'_>, bytes: &[u8]) -> Option<String> {
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() != "variable_declaration" {
            continue;
        }
        let mut vc = child.walk();
        for decl in child.children(&mut vc) {
            if decl.kind() != "variable_declarator" {
                continue;
            }
            let Some(name_node) = decl.child_by_field_name("name") else {
                continue;
            };
            let Ok(alias) =
                std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
            else {
                continue;
            };
            let Some(value) = decl.child_by_field_name("value") else {
                continue;
            };
            if js_assignment_reaches_module_exports(&value, bytes) {
                return Some(alias.to_string());
            }
        }
    }
    None
}

/// Return true if `node` is an `assignment_expression` (possibly nested)
/// that has `module.exports` as one of its left-hand sides.
///
/// Handles both direct and chained forms:
/// - `module.exports = {}`
/// - `exports = module.exports = {}`
fn js_assignment_reaches_module_exports(node: &tree_sitter::Node<'_>, bytes: &[u8]) -> bool {
    if node.kind() != "assignment_expression" {
        return false;
    }
    if let Some(left) = node.child_by_field_name("left")
        && left.kind() == "member_expression"
        && let (Some(obj), Some(prop)) = (
            left.child_by_field_name("object"),
            left.child_by_field_name("property"),
        )
    {
        let obj_text = std::str::from_utf8(&bytes[obj.start_byte()..obj.end_byte()]).unwrap_or("");
        let prop_text =
            std::str::from_utf8(&bytes[prop.start_byte()..prop.end_byte()]).unwrap_or("");
        if obj_text == "module" && prop_text == "exports" {
            return true;
        }
    }
    // Recurse into RHS for chained assignments.
    node.child_by_field_name("right")
        .is_some_and(|right| js_assignment_reaches_module_exports(&right, bytes))
}

/// Classify a top-level `export_statement` node and emit entry points.
///
/// Handles the patterns:
/// - `export default function NAME(…)` / `export default class NAME`
/// - `export const NAME = (…) => …` (named arrow-function export)
fn js_classify_export(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);

    // Walk children to find the `declaration` field (or the `default`
    // keyword plus inline declaration). tree-sitter-javascript uses the
    // `declaration` field for named exports and places the value inline
    // after `default` for default exports.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" => {
                // `export default function NAME(…)` or `export function NAME(…)`.
                if let Some(name_node) = child.child_by_field_name("name")
                    && let Ok(name) =
                        std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
                {
                    out.push(EntryPoint {
                        name: name.to_string(),
                        kind: EntryPointKind::LibraryExport,
                        file_path: file_path.to_path_buf(),
                        line,
                    });
                }
            }
            "class_declaration" => {
                // `export default class NAME` or `export class NAME`.
                if let Some(name_node) = child.child_by_field_name("name")
                    && let Ok(name) =
                        std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
                {
                    out.push(EntryPoint {
                        name: name.to_string(),
                        kind: EntryPointKind::LibraryExport,
                        file_path: file_path.to_path_buf(),
                        line,
                    });
                }
            }
            "lexical_declaration" => {
                // `export const NAME = (…) => …` — walk variable declarators.
                js_collect_lexical_exports(&child, bytes, file_path, line, out);
            }
            _ => {}
        }
    }
}

/// Walk a `lexical_declaration` (const/let) inside an export statement
/// and emit LibraryExport entries for each variable whose value is an
/// arrow function or function expression.
fn js_collect_lexical_exports(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    line: u32,
    out: &mut Vec<EntryPoint>,
) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "variable_declarator" {
            continue;
        }
        let Some(name_node) = child.child_by_field_name("name") else {
            continue;
        };
        let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
        else {
            continue;
        };
        // Only emit if the RHS is a function-like value (arrow or
        // function expression). Non-function exports (e.g. string
        // constants) are not entry points.
        if child
            .child_by_field_name("value")
            .is_some_and(|v| matches!(v.kind(), "arrow_function" | "function_expression"))
        {
            out.push(EntryPoint {
                name: name.to_string(),
                kind: EntryPointKind::LibraryExport,
                file_path: file_path.to_path_buf(),
                line,
            });
        }
    }
}

/// Classify a top-level `expression_statement` node.
///
/// Handles:
/// - `module.exports = …` — emits a LibraryExport entry named `module.exports`.
/// - `exports.NAME = …` — emits a LibraryExport entry named `NAME`.
/// - `exports = module.exports = VALUE` — chained assignment; emits
///   LibraryExport for the value name when it is an identifier.
/// - `ALIAS.METHOD = function...` — emits LibraryExport named `METHOD`
///   when `ALIAS` is the known `module.exports` alias (B-0010).
/// - `test(…)` / `it(…)` / `describe(…)` — emits a Test entry when in a
///   test file.
fn js_classify_expression_statement(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    is_test_file: bool,
    module_exports_alias: Option<&str>,
    out: &mut Vec<EntryPoint>,
) {
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "assignment_expression" => {
                js_classify_assignment(&child, bytes, file_path, line, module_exports_alias, out);
            }
            "call_expression" if is_test_file => {
                js_classify_test_call(&child, bytes, file_path, line, out);
            }
            _ => {}
        }
    }
}

/// Classify an `assignment_expression` for CommonJS export patterns.
///
/// Emits:
/// - `module.exports = …` → LibraryExport named `"module.exports"`
/// - `exports.NAME = …` → LibraryExport named `NAME`
/// - `exports = module.exports = VALUE` → recurses, seeding VALUE name
/// - `ALIAS.METHOD = function...` → LibraryExport named `METHOD` when
///   `ALIAS` is the known module.exports alias (B-0010)
fn js_classify_assignment(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    line: u32,
    module_exports_alias: Option<&str>,
    out: &mut Vec<EntryPoint>,
) {
    let Some(left) = node.child_by_field_name("left") else {
        return;
    };

    // Handle chained assignment: `exports = module.exports = VALUE`
    // The left side is a bare `exports` identifier, and the RHS is
    // another assignment_expression (or a direct value).
    if left.kind() == "identifier" {
        let Ok(left_name) = std::str::from_utf8(&bytes[left.start_byte()..left.end_byte()]) else {
            return;
        };
        if left_name == "exports"
            && let Some(right) = node.child_by_field_name("right")
        {
            if right.kind() == "assignment_expression" {
                // Recurse: `exports = module.exports = VALUE`
                js_classify_assignment(&right, bytes, file_path, line, module_exports_alias, out);
            } else {
                // `exports = VALUE` — emit VALUE if it is a named fn.
                js_emit_identifier_as_export(&right, bytes, file_path, line, out);
            }
        }
        return;
    }

    if left.kind() != "member_expression" {
        return;
    }
    let Some(obj_node) = left.child_by_field_name("object") else {
        return;
    };
    let Some(prop_node) = left.child_by_field_name("property") else {
        return;
    };
    let Ok(obj) = std::str::from_utf8(&bytes[obj_node.start_byte()..obj_node.end_byte()]) else {
        return;
    };
    let Ok(prop) = std::str::from_utf8(&bytes[prop_node.start_byte()..prop_node.end_byte()]) else {
        return;
    };

    if obj == "module" && prop == "exports" {
        // `module.exports = ...` — the whole module is exported.
        out.push(EntryPoint {
            name: "module.exports".to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    } else if obj == "exports" {
        // `exports.NAME = ...` — a named CommonJS export.
        out.push(EntryPoint {
            name: prop.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    } else if module_exports_alias.is_some_and(|alias| alias == obj) {
        // `ALIAS.METHOD = function...` — CommonJS object-accumulation.
        // Only emit when the RHS is a function-like value.
        let is_fn = node.child_by_field_name("right").is_some_and(|v| {
            matches!(
                v.kind(),
                "function_expression" | "arrow_function" | "function_declaration"
            )
        });
        if is_fn {
            out.push(EntryPoint {
                name: prop.to_string(),
                kind: EntryPointKind::LibraryExport,
                file_path: file_path.to_path_buf(),
                line,
            });
        }
    }
}

/// Emit a LibraryExport entry when `node` is an identifier naming a
/// function or factory (used for `exports = VALUE` assignments).
fn js_emit_identifier_as_export(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    line: u32,
    out: &mut Vec<EntryPoint>,
) {
    if node.kind() == "identifier"
        && let Ok(name) = std::str::from_utf8(&bytes[node.start_byte()..node.end_byte()])
        && !name.is_empty()
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Classify a `call_expression` for Jest/Vitest test runner patterns.
///
/// Emits Test entries for `test(…)`, `it(…)`, and `describe(…)` calls.
/// The first string argument (if present) becomes the entry name; falls
/// back to the call function name when the first argument is not a string.
fn js_classify_test_call(
    node: &tree_sitter::Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    line: u32,
    out: &mut Vec<EntryPoint>,
) {
    let Some(func_node) = node.child_by_field_name("function") else {
        return;
    };
    let Ok(func_name) = std::str::from_utf8(&bytes[func_node.start_byte()..func_node.end_byte()])
    else {
        return;
    };
    if !matches!(func_name, "test" | "it" | "describe") {
        return;
    }

    // Try to extract the first string argument as the test name.
    let entry_name = node
        .child_by_field_name("arguments")
        .and_then(|args| {
            let mut c = args.walk();
            args.children(&mut c).find(|ch| ch.kind() == "string")
        })
        .and_then(|s| {
            // String node: look for a string_fragment child.
            let mut c = s.walk();
            s.children(&mut c).find(|ch| ch.kind() == "string_fragment")
        })
        .and_then(|frag| {
            std::str::from_utf8(&bytes[frag.start_byte()..frag.end_byte()])
                .ok()
                .map(ToString::to_string)
        })
        .unwrap_or_else(|| func_name.to_string());

    out.push(EntryPoint {
        name: entry_name,
        kind: EntryPointKind::Test,
        file_path: file_path.to_path_buf(),
        line,
    });
}

// ---------------------------------------------------------------------------
// Java detector (B-0009, Cycle 9 / 4.1.5)
// ---------------------------------------------------------------------------

/// Java entry-point detector (B-0009, Cycle 9).
///
/// Detects the entry-point shapes that anchor JVM-ecosystem call graphs.
/// Before this detector, `find_dead_code` returned `dead_fraction = 1.0`
/// on every Java codebase — there were no seeds, so BFS reachability
/// reached nothing.
///
/// Patterns recognised:
/// - `public static void main(String[] args)` → [`EntryPointKind::Main`]
/// - JUnit method annotations `@Test`, `@ParameterizedTest`,
///   `@RepeatedTest`, `@TestFactory` → [`EntryPointKind::Test`]
/// - Spring DI / stereotype class annotations `@Component`, `@Service`,
///   `@Repository`, `@Controller`, `@RestController`, `@Configuration`,
///   `@AutoConfiguration` → [`EntryPointKind::LibraryExport`]
/// - Spring `@Bean`-annotated methods → [`EntryPointKind::LibraryExport`]
///   (each bean is a library export from the DI container's perspective)
/// - `@SpringBootApplication`, `@SpringBootTest` annotated classes →
///   [`EntryPointKind::FrameworkDispatched`] (Spring container drives
///   their lifecycle; static call graph cannot see the invocation)
///
/// Annotation matching is by the trailing identifier — both
/// `@Component` and `@org.springframework.stereotype.Component` are
/// recognised. The detector treats `marker_annotation` (`@Foo`) and
/// `annotation` (`@Foo(args)`) uniformly.
#[derive(Debug, Default, Clone, Copy)]
pub struct JavaEntryDetector;

impl EntryPointDetector for JavaEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_java::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();
        visit_java_node(&root, bytes, file_path, &mut entries);
        entries
    }
}

/// Recursively walk the Java AST emitting entry points for matching
/// class and method declarations.
fn visit_java_node(node: &Node<'_>, bytes: &[u8], file_path: &Path, out: &mut Vec<EntryPoint>) {
    match node.kind() {
        "class_declaration" | "interface_declaration" | "enum_declaration" => {
            java_classify_class(node, bytes, file_path, out);
        }
        "method_declaration" => {
            java_classify_method(node, bytes, file_path, out);
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        visit_java_node(&child, bytes, file_path, out);
    }
}

/// Annotations that mark a class as a Spring-framework-dispatched
/// application entry whose lifecycle the container drives.
const JAVA_FRAMEWORK_CLASS_ANNOTATIONS: &[&str] = &[
    "SpringBootApplication",
    "SpringBootTest",
    "EnableAutoConfiguration",
];

/// Annotations that mark a class as a Spring DI bean / library-export
/// surface. The Spring container instantiates these even when no
/// in-source caller does.
const JAVA_STEREOTYPE_CLASS_ANNOTATIONS: &[&str] = &[
    "Component",
    "Service",
    "Repository",
    "Controller",
    "RestController",
    "Configuration",
    "AutoConfiguration",
    "ConfigurationProperties",
];

/// Annotations that mark a method as a JUnit test entry.
const JAVA_TEST_METHOD_ANNOTATIONS: &[&str] = &[
    "Test",
    "ParameterizedTest",
    "RepeatedTest",
    "TestFactory",
    "TestTemplate",
    "BeforeEach",
    "AfterEach",
    "BeforeAll",
    "AfterAll",
];

/// Classify a Java class/interface/enum declaration.
fn java_classify_class(node: &Node<'_>, bytes: &[u8], file_path: &Path, out: &mut Vec<EntryPoint>) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);
    let annotations = java_collect_annotation_names(node, bytes);

    if annotations
        .iter()
        .any(|a| JAVA_FRAMEWORK_CLASS_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::FrameworkDispatched,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    if annotations
        .iter()
        .any(|a| JAVA_STEREOTYPE_CLASS_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Classify a Java method declaration.
fn java_classify_method(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);
    let annotations = java_collect_annotation_names(node, bytes);

    // `public static void main(String[] args)` — the JVM entry contract.
    // tree-sitter-java places `public`, `static`, etc. as direct children
    // of a `modifiers` node; check both modifier text and method shape.
    if name == "main" && java_method_is_public_static(node, bytes) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    if annotations
        .iter()
        .any(|a| JAVA_TEST_METHOD_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // @Bean methods are library-export surfaces — Spring publishes them
    // into the application context regardless of in-source callers.
    if annotations.iter().any(|a| a == "Bean") {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Collect annotation identifiers from a declaration's `modifiers` child.
///
/// tree-sitter-java places annotations inside a `modifiers` node child
/// of the declaration. Each annotation is either:
/// - `marker_annotation` — bare `@Foo`, with a `name` field that is an
///   `identifier` or `scoped_identifier`.
/// - `annotation` — `@Foo(args)`, same `name` field shape.
///
/// We extract the trailing identifier from the annotation name so that
/// both `@Component` and `@org.springframework.stereotype.Component`
/// resolve to `"Component"`.
fn java_collect_annotation_names(node: &Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut names = Vec::new();
    let Some(modifiers) = java_find_modifiers_child(node) else {
        return names;
    };
    let mut cursor = modifiers.walk();
    for child in modifiers.children(&mut cursor) {
        match child.kind() {
            "marker_annotation" | "annotation" => {
                if let Some(name_node) = child.child_by_field_name("name")
                    && let Some(ident) = java_annotation_trailing_identifier(&name_node, bytes)
                {
                    names.push(ident);
                }
            }
            _ => {}
        }
    }
    names
}

/// Find the `modifiers` child of a Java declaration node, if present.
fn java_find_modifiers_child<'tree>(node: &Node<'tree>) -> Option<Node<'tree>> {
    let mut cursor = node.walk();
    node.children(&mut cursor)
        .find(|&child| child.kind() == "modifiers")
}

/// Extract the trailing identifier from a Java annotation name node.
///
/// Handles two shapes:
/// - `(identifier)` — bare `@Foo`; returns `"Foo"`.
/// - `(scoped_identifier scope: ... name: (identifier))` — fully qualified
///   `@a.b.Foo`; returns `"Foo"`. Falls back to walking children to find
///   the last `identifier` if the `name` field is not present.
fn java_annotation_trailing_identifier(name_node: &Node<'_>, bytes: &[u8]) -> Option<String> {
    match name_node.kind() {
        "identifier" => std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()])
            .ok()
            .map(ToString::to_string),
        "scoped_identifier" => {
            // Prefer the `name` field; fall back to the last `identifier`
            // child if the field is unavailable on this grammar version.
            if let Some(name) = name_node.child_by_field_name("name") {
                return std::str::from_utf8(&bytes[name.start_byte()..name.end_byte()])
                    .ok()
                    .map(ToString::to_string);
            }
            let mut last: Option<String> = None;
            let mut cursor = name_node.walk();
            for child in name_node.children(&mut cursor) {
                if child.kind() == "identifier"
                    && let Ok(text) =
                        std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
                {
                    last = Some(text.to_string());
                }
            }
            last
        }
        _ => None,
    }
}

/// Return true if a Java `method_declaration` has both `public` and
/// `static` modifiers — required for the JVM `main` entry contract.
fn java_method_is_public_static(node: &Node<'_>, bytes: &[u8]) -> bool {
    let Some(modifiers) = java_find_modifiers_child(node) else {
        return false;
    };
    let text =
        std::str::from_utf8(&bytes[modifiers.start_byte()..modifiers.end_byte()]).unwrap_or("");
    // tree-sitter-java emits `public` and `static` as unnamed children
    // (keyword tokens) inside `modifiers`. The whole-text contains-check
    // is a reliable proxy and avoids enumerating the grammar's keyword
    // node kinds, which differ across grammar versions.
    text.contains("public") && text.contains("static")
}

// ---------------------------------------------------------------------------
// Kotlin detector (B-0009, Cycle 9 / 4.1.5)
// ---------------------------------------------------------------------------

/// Kotlin entry-point detector (B-0009, Cycle 9).
///
/// Detects:
/// - Top-level `fun main(...)` → [`EntryPointKind::Main`]
/// - Classes annotated with `@Component` / `@Service` / `@Repository` /
///   `@Controller` / `@RestController` / `@Configuration` →
///   [`EntryPointKind::LibraryExport`]
/// - Classes annotated with `@SpringBootApplication` /
///   `@SpringBootTest` → [`EntryPointKind::FrameworkDispatched`]
/// - Functions annotated with `@Test`, `@ParameterizedTest`,
///   `@RepeatedTest` → [`EntryPointKind::Test`]
/// - Classes whose names end in `Test` or `Spec` (Spek / KotlinTest
///   convention) → [`EntryPointKind::Test`]
///
/// Uses `tree_sitter_kotlin_ng` — the same grammar wired into the
/// chunker via `crates/ripvec-core/src/languages.rs`. Annotations are
/// matched by trailing identifier (so `@Component` and
/// `@org.springframework.stereotype.Component` both resolve).
#[derive(Debug, Default, Clone, Copy)]
pub struct KotlinEntryDetector;

impl EntryPointDetector for KotlinEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_kotlin_ng::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Top-level functions: `fun main(...)` is the JVM entry contract.
        // Walk only the root's direct children to enforce top-level scope.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            if child.kind() == "function_declaration" {
                kotlin_classify_top_level_function(&child, bytes, file_path, &mut entries);
            }
        }

        // Class / object declarations + nested function declarations.
        // Use full-AST walk so annotated nested classes and methods are
        // also seeded.
        visit_kotlin_node(&root, bytes, file_path, &mut entries);

        entries
    }
}

/// Annotations that mark a Kotlin class as Spring-framework-dispatched.
const KOTLIN_FRAMEWORK_CLASS_ANNOTATIONS: &[&str] = &[
    "SpringBootApplication",
    "SpringBootTest",
    "EnableAutoConfiguration",
];

/// Annotations that mark a Kotlin class as a DI / library-export surface.
const KOTLIN_STEREOTYPE_CLASS_ANNOTATIONS: &[&str] = &[
    "Component",
    "Service",
    "Repository",
    "Controller",
    "RestController",
    "Configuration",
    "AutoConfiguration",
    "ConfigurationProperties",
];

/// Annotations that mark a Kotlin function as a test entry.
const KOTLIN_TEST_FUNCTION_ANNOTATIONS: &[&str] = &[
    "Test",
    "ParameterizedTest",
    "RepeatedTest",
    "TestFactory",
    "TestTemplate",
];

/// Recursively walk the Kotlin AST emitting entry points for class /
/// object / function declarations.
fn visit_kotlin_node(node: &Node<'_>, bytes: &[u8], file_path: &Path, out: &mut Vec<EntryPoint>) {
    match node.kind() {
        "class_declaration" | "object_declaration" => {
            kotlin_classify_class(node, bytes, file_path, out);
        }
        "function_declaration" => {
            kotlin_classify_function_annotations(node, bytes, file_path, out);
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        visit_kotlin_node(&child, bytes, file_path, out);
    }
}

/// Classify a top-level Kotlin function declaration.
///
/// Emits [`EntryPointKind::Main`] for any top-level `fun main`, whether
/// declared with `()`, `(args: Array<String>)`, or the Kotlin 1.3+
/// suspended `suspend fun main(...)` shape.
fn kotlin_classify_top_level_function(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);
    if name == "main" {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Classify annotations on a Kotlin function (anywhere in the tree).
///
/// Emits [`EntryPointKind::Test`] for `@Test` family annotations.
fn kotlin_classify_function_annotations(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);
    let annotations = kotlin_collect_annotation_names(node, bytes);
    if annotations
        .iter()
        .any(|a| KOTLIN_TEST_FUNCTION_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Classify a Kotlin class / object declaration.
fn kotlin_classify_class(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);
    let annotations = kotlin_collect_annotation_names(node, bytes);

    if annotations
        .iter()
        .any(|a| KOTLIN_FRAMEWORK_CLASS_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::FrameworkDispatched,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    if annotations
        .iter()
        .any(|a| KOTLIN_STEREOTYPE_CLASS_ANNOTATIONS.contains(&a.as_str()))
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // Convention-based: classes named `*Test` or `*Spec` are test entries
    // even without an explicit annotation — covers Spek / KotlinTest /
    // many Spring projects' naming patterns.
    if (name.ends_with("Test") || name.ends_with("Spec")) && name.len() > 4 {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Collect annotation identifiers preceding a Kotlin declaration.
///
/// In `tree-sitter-kotlin-ng` annotations appear inside a `modifiers`
/// (or `modifier_list`) child of the declaration. The annotation node
/// kinds vary by grammar version — we accept `annotation` and
/// `single_annotation` and pull the trailing identifier from whichever
/// child contains the annotation's user_type / identifier.
fn kotlin_collect_annotation_names(node: &Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut names = Vec::new();
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "modifiers" | "modifier_list" => {
                kotlin_collect_annotations_in(&child, bytes, &mut names);
            }
            // Some grammar variants attach annotations directly as
            // siblings of the declaration body rather than inside a
            // `modifiers` node — handle that case too.
            "annotation" | "single_annotation" => {
                if let Some(ident) = kotlin_annotation_identifier(&child, bytes) {
                    names.push(ident);
                }
            }
            _ => {}
        }
    }
    names
}

/// Walk into a Kotlin `modifiers` node and collect annotation names.
fn kotlin_collect_annotations_in(node: &Node<'_>, bytes: &[u8], out: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "annotation" | "single_annotation" => {
                if let Some(ident) = kotlin_annotation_identifier(&child, bytes) {
                    out.push(ident);
                }
            }
            _ => {}
        }
    }
}

/// Extract the trailing identifier from a Kotlin annotation node.
///
/// Kotlin annotations parse as `@<user_type>` where `user_type` is a
/// dot-separated chain of `simple_user_type` nodes each containing a
/// `(simple_identifier)` (or just `(identifier)` in `tree-sitter-kotlin-ng`).
/// We walk the annotation subtree and return the last identifier found —
/// matching `@Component` and `@org.springframework.stereotype.Component`
/// uniformly to `"Component"`.
fn kotlin_annotation_identifier(node: &Node<'_>, bytes: &[u8]) -> Option<String> {
    let mut last: Option<String> = None;
    let mut stack: Vec<Node<'_>> = vec![*node];
    while let Some(n) = stack.pop() {
        if matches!(n.kind(), "identifier" | "simple_identifier")
            && let Ok(text) = std::str::from_utf8(&bytes[n.start_byte()..n.end_byte()])
        {
            // Skip the `@` token itself if it happens to be tokenised as
            // an identifier (it isn't in practice, but be defensive).
            if !text.is_empty() && text != "@" {
                last = Some(text.to_string());
            }
        }
        let mut cursor = n.walk();
        for child in n.children(&mut cursor) {
            stack.push(child);
        }
    }
    last
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// Return the entry-point detector for a language identifier.
///
/// `language` is the lowercased language name as used in
/// `crate::languages` (`"rust"`, `"python"`, `"go"`, `"c"`, `"javascript"`,
/// `"java"`, `"kotlin"`).
/// Returns `None` for any language not yet covered by this module.
///
/// File-extension dispatch (`"rs"`, `"py"`, `"pyi"`, `"go"`, `"c"`,
/// `"h"`, `"js"`, `"jsx"`, `"ts"`, `"tsx"`, `"java"`, `"kt"`, `"kts"`) is
/// also accepted for caller convenience — the BFS walk in X2 carries
/// extensions, not language names, through its per-file loop.
#[must_use]
pub fn detector_for(language: &str) -> Option<Box<dyn EntryPointDetector>> {
    match language {
        "rust" | "rs" => Some(Box::new(RustEntryDetector)),
        "python" | "py" | "pyi" => Some(Box::new(PythonEntryDetector)),
        "go" => Some(Box::new(GoEntryDetector)),
        "c" | "h" => Some(Box::new(CEntryDetector)),
        "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" => {
            Some(Box::new(JsEntryDetector))
        }
        "java" => Some(Box::new(JavaEntryDetector)),
        "kotlin" | "kt" | "kts" => Some(Box::new(KotlinEntryDetector)),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Summary aggregation (4.1.1 Front A node A4)
// ---------------------------------------------------------------------------

/// Render a per-kind count map as a sorted list of human-friendly summary
/// lines for the `find_dead_code` MCP tool's `entry_points_detected`
/// field.
///
/// Each line follows the shape `"<count> <label>"` — e.g. `"12
/// framework-dispatched (MCP tools)"`, `"3 library exports"`. The output
/// is sorted lexicographically so the surface order is deterministic
/// across calls.
///
/// Lives in `ripvec-core` so the MCP tool wrapper and any future CLI
/// consumer share a single labelling convention. Added in 4.1.1 (Wave 1
/// Front A node A4) alongside [`EntryPointKind::FrameworkDispatched`].
#[must_use]
pub fn summarize_entry_point_kinds<S: std::hash::BuildHasher>(
    counts: &std::collections::HashMap<EntryPointKind, usize, S>,
) -> Vec<String> {
    let mut summary: Vec<String> = counts
        .iter()
        .map(|(kind, count)| format!("{count} {label}", label = label_for_kind(*kind)))
        .collect();
    summary.sort();
    summary
}

/// Return the human-friendly label used in the
/// [`summarize_entry_point_kinds`] output for a given variant.
///
/// Exposed `pub` so external consumers can format individual kinds
/// without rebuilding a count map.
#[must_use]
pub fn label_for_kind(kind: EntryPointKind) -> &'static str {
    match kind {
        EntryPointKind::Main => "main",
        EntryPointKind::LibraryExport => "library exports",
        EntryPointKind::Test => "tests",
        EntryPointKind::Ffi => "FFI",
        EntryPointKind::ProcMacro => "proc-macros",
        EntryPointKind::Init => "init functions",
        EntryPointKind::BuildScript => "build scripts",
        EntryPointKind::FrameworkDispatched => "framework-dispatched (MCP tools)",
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Parse `source` with the given tree-sitter `Language`. Returns `None`
/// if the parser cannot be configured or the parse fails.
fn parse_with(source: &str, language: &tree_sitter::Language) -> Option<tree_sitter::Tree> {
    let mut parser = Parser::new();
    parser.set_language(language).ok()?;
    parser.parse(source, None)
}

// Unused-but-keep-for-X2 helpers. These ride alongside the detector
// implementations so X2 has a single import point for the BFS-time
// helpers.
//
// `query_match_lines` returns the 1-based line of every match of a
// compiled tree-sitter query against `source`. X2 will use this to
// post-process the raw RepoGraph definitions when an entry-point
// predicate fires on something that is not itself a Definition (e.g.
// the Python `if __name__ == "__main__"` block isn't a Definition —
// it's a top-level statement that anchors any function it calls).
//
// We expose it as `pub(crate)` so X2 can consume without it widening
// the public surface.

#[allow(dead_code)]
pub(crate) fn query_match_lines(
    source: &str,
    language: &tree_sitter::Language,
    query: &Query,
) -> Vec<u32> {
    let mut lines = Vec::new();
    let Some(tree) = parse_with(source, language) else {
        return lines;
    };
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), source.as_bytes());
    while let Some(m) = matches.next() {
        for cap in m.captures {
            let line = u32::try_from(cap.node.start_position().row + 1).unwrap_or(u32::MAX);
            lines.push(line);
        }
    }
    lines
}