repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Path Traversal Detector — AST-first sink classification.
//!
//! Architecture (post commit `45105f36`):
//!
//! - The `TaintAnalyzer` pipeline (under `src/detectors/security/taint/`)
//!   continues to do call-graph BFS for source→sink paths in the
//!   `PathTraversal` category. **Unchanged** by this migration.
//!
//! - The detector's previous line-based regex pass has been replaced
//!   with a tree-sitter walk per AST-eligible language (Python, JS,
//!   TS/JSX/TSX, Go). Every file-operation/file-download call site is
//!   matched at the AST level, the path argument is classified into a
//!   `PathArgKind`, and severity is derived from the kind. A separate
//!   pass merges taint-confirmed paths to boost High → Critical or
//!   downgrade sanitized findings.
//!
//! Non-AST languages (Ruby, PHP, Java) are not currently emitted from
//! this detector; the previous line-loop's coverage there was
//! incidental (regex shapes happened to match occasionally). The taint
//! analyzer still operates on those files via its own keyword-driven
//! function-name matching.
//!
//! Predecessors that established this AST-first migration arc:
//! `4381002a` (secrets), `4c656b2f` (cleartext), `ac8400c6` + `474e6cb5`
//! (eval), `c67ad76f` + `3c88328e` (command), `2f559a34` (pickle),
//! `32021903` (crypto), `e34cdec8` (Python alias propagation),
//! `45105f36` (metachar).

// Submodules. `annotation` is a pure parser; `predict` (added in commit 3)
// will consume it and the typed evidence to produce dual-branch
// predictions; `evidence` (added in commit 4) will pull typed signals
// out of a tree-sitter Python call node. Per Phase 2b decisions doc D5,
// the annotation parser is a deliberate copy of Phase 2a's
// `insecure_crypto::annotation`; the two will be consolidated into a
// shared `src/detectors/security/dual_branch_annotation.rs` module
// during Phase 2c (the rule-of-three opportunity).
mod annotation;
mod evidence;
mod predict;

use crate::detectors::ast_fingerprint::parse_root_ext;
use crate::detectors::ast_walk::AstWalkCtx;
use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::detector_context::ContentFlags;
use crate::detectors::fast_search::{find_in, *};
use crate::detectors::security::ast_helpers::{
    collect_named_args, node_text, receiver_chain_label as receiver_chain_label_shared,
    unwrap_callee,
};
use crate::detectors::security::scan_inputs::{ScanAstInputs, ScanInputs};
use crate::detectors::taint::{TaintAnalysisResult, TaintAnalyzer, TaintCategory};
use crate::models::{Finding, Severity};
use crate::parsers::lightweight::Language;
use anyhow::Result;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, OnceLock};

const SUPPORTED_EXTS: &[&str] = &["py", "js", "ts", "jsx", "tsx", "go"];
const AST_EXTS: &[&str] = &["py", "js", "ts", "jsx", "tsx", "go"];

pub struct PathTraversalDetector {
    repository_path: PathBuf,
    max_findings: usize,
    taint_analyzer: TaintAnalyzer,
    precomputed_cross: OnceLock<Vec<crate::detectors::taint::TaintPath>>,
    precomputed_intra: OnceLock<Vec<crate::detectors::taint::TaintPath>>,
}

impl PathTraversalDetector {
    pub fn new(repository_path: impl Into<PathBuf>) -> Self {
        Self {
            repository_path: repository_path.into(),
            max_findings: 50,
            taint_analyzer: TaintAnalyzer::new(),
            precomputed_cross: OnceLock::new(),
            precomputed_intra: OnceLock::new(),
        }
    }
}

impl Detector for PathTraversalDetector {
    fn name(&self) -> &'static str {
        "path-traversal"
    }
    fn description(&self) -> &'static str {
        "Detects path traversal vulnerabilities"
    }

    fn bypass_postprocessor(&self) -> bool {
        true
    }

    crate::detectors::impl_taint_precompute!();

    fn taint_category(&self) -> Option<crate::detectors::taint::TaintCategory> {
        Some(TaintCategory::PathTraversal)
    }

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

    fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
        crate::detectors::detector_context::ContentFlags::FILE_OPS
            .union(crate::detectors::detector_context::ContentFlags::PATH_OPS)
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let det_ctx = &ctx.detector_ctx;
        let files = &ctx.as_file_provider();
        let mut findings: Vec<Finding> = vec![];

        // -------------------------------------------------------------
        // Taint analysis (precomputed when available, else live).
        // -------------------------------------------------------------
        let mut taint_paths = if let Some(cross) = self.precomputed_cross.get() {
            cross.clone()
        } else {
            self.taint_analyzer
                .trace_taint(graph, TaintCategory::PathTraversal)
        };
        let intra_paths = if let Some(intra) = self.precomputed_intra.get() {
            intra.clone()
        } else {
            crate::detectors::taint::run_intra_function_taint(
                &self.taint_analyzer,
                graph,
                TaintCategory::PathTraversal,
                &self.repository_path,
            )
        };
        taint_paths.extend(intra_paths);
        let taint_result = TaintAnalysisResult::from_paths(taint_paths);

        // Single named place where the per-detector dual-branch policy
        // is read from project config. See `DualBranchPolicy` docs for
        // why this is a struct and not just a `bool`.
        let dual_branch_policy = DualBranchPolicy {
            flag_on: ctx.dual_branch.is_enabled_for("path-traversal"),
        };

        // -------------------------------------------------------------
        // Pass A: AST-first sink detection per file.
        // -------------------------------------------------------------
        for path in files.files_with_extensions(SUPPORTED_EXTS) {
            if findings.len() >= self.max_findings {
                break;
            }

            // Pre-filter via content flags / inline keyword scan.
            let flags = det_ctx.content_flags.get(path).copied().unwrap_or_default();
            let should_check = flags.has(ContentFlags::FILE_OPS)
                || flags.has(ContentFlags::PATH_OPS)
                || det_ctx.content_flags.is_empty();
            if !should_check {
                continue;
            }

            let raw = match files.content(path) {
                Some(c) => c,
                None => continue,
            };
            let raw_str: &str = &raw;

            if det_ctx.content_flags.is_empty() && !contains_any(PATH_KEYWORD_FINDERS, raw_str) {
                continue;
            }
            if raw_str.len() > 500_000 {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !AST_EXTS.contains(&ext) {
                continue;
            }
            let lang = Language::from_path(path);
            let cached = files.tree(path);
            let scan = ScanInputs::new(path, raw_str, ext);
            let ast_inputs = ScanAstInputs::new(scan, lang, cached.as_deref());
            let new_findings = self.scan_file_ast(&ast_inputs, &taint_result, &dual_branch_policy);
            findings.extend(new_findings);
        }

        // -------------------------------------------------------------
        // Pass B: taint-confirmed enrichment.
        //
        // Walk every taint path. For each path whose sink lies inside a
        // file we just scanned, either:
        //   - boost an already-emitted Pass A finding to Critical, or
        //   - if Pass A didn't fire (e.g. classifier said `Unknown` and
        //     was filtered, or the call shape didn't match a known
        //     sink), emit a fresh Critical finding from the taint path.
        // Sanitized paths drop the corresponding finding to Low so
        // they're filtered out below.
        // -------------------------------------------------------------
        merge_taint_paths(&mut findings, &taint_result, &self.repository_path);

        // Drop Low (sanitized / static-literal) findings.
        findings.retain(|f| f.severity != Severity::Low);

        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for PathTraversalDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }
}

// ---------------------------------------------------------------------------
// Pre-filter
// ---------------------------------------------------------------------------

/// Cheap pre-filter: does this file contain any file/path keyword?
/// Mirrors the inline keyword scan from the previous line-based loop;
/// every callee name we match in `match_*_call` MUST be covered.
static PATH_KEYWORD_FINDERS: &[&LazyLock<memchr::memmem::Finder<'static>>] = &[
    &FIND_OPEN_PAREN,
    &FIND_READ_FILE,
    &FIND_WRITE_FILE,
    &FIND_PATH_JOIN,
    &FIND_PATH_RESOLVE,
    &FIND_OS_PATH,
    &FIND_SEND_FILE,
    &FIND_SEND_FILE_SNAKE,
    &FIND_SERVE_FILE,
    &FIND_UNLINK,
    &FIND_RMDIR,
    &FIND_MKDIR,
    &FIND_COPY_FILE,
    &FIND_RENAME_PAREN,
    &FIND_OS_REMOVE,
    &FIND_SHUTIL,
    &FIND_FILEPATH,
    &FIND_PATHLIB,
    &FIND_CREATE_READ_STREAM,
    &FIND_CREATE_WRITE_STREAM,
    &FIND_APPEND_FILE,
    &FIND_STAT_SYNC,
    &FIND_ACCESS_SYNC,
];

// ---------------------------------------------------------------------------
// Sink classification (the "API table")
// ---------------------------------------------------------------------------

/// Which file-operation / file-download API a sink call matched.
/// Drives the title and remediation text emitted in the Finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PathApi {
    /// Generic file read/write/etc.: `open`, `fs.readFile`, `os.Open`.
    FileOp,
    /// `os.path.join`, `path.join`, `filepath.Join` — the helper itself
    /// is not a sink, but with a variable arg it's the canonical
    /// path-join-with-user-input shape.
    PathJoin,
    /// `res.sendFile`, `res.download`, `http.ServeFile`,
    /// `flask.send_file`, `flask.send_from_directory`,
    /// `django.http.FileResponse`, `starlette.responses.FileResponse`.
    SendFile,
}

/// Shape of the path argument at a sink call. Drives the severity
/// table (`PathApi::severity_for`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PathArgKind {
    /// `open("/etc/hosts")` — constant string. Likely benign.
    StaticLiteral,
    /// `open(f"/uploads/{user_file}")` or `` `/uploads/${userFile}` ``.
    Interpolated,
    /// `open(user_path)` — bare variable / member / subscript.
    UserVariable,
    /// `open("/uploads/" + filename)` — binary `+` with at least one
    /// non-literal operand.
    Concatenation,
    /// Couldn't classify (e.g. unfamiliar wrapper expression).
    Unknown,
}

impl PathApi {
    fn title(self) -> &'static str {
        match self {
            PathApi::FileOp => "Potential path traversal in file operation",
            PathApi::PathJoin => "Path traversal via path.join with user input",
            PathApi::SendFile => "Path traversal in file download",
        }
    }

    fn base_description(self) -> &'static str {
        match self {
            PathApi::FileOp => {
                "File operation with user-controlled input detected. An attacker could use '../' \
                 sequences to access files outside the intended directory."
            }
            PathApi::PathJoin => {
                "path.join() with user input does NOT prevent path traversal. Joining '/base' \
                 with '../etc/passwd' results in '/etc/passwd'."
            }
            PathApi::SendFile => {
                "File download/send function with user-controlled path. Attackers could download \
                 arbitrary files from the server."
            }
        }
    }

    fn suggested_fix(self) -> &'static str {
        match self {
            PathApi::FileOp =>
                "1. Use path.basename() to extract filename only\n\
                 2. Validate resolved path is within allowed directory\n\
                 3. Use a whitelist of allowed filenames if possible",
            PathApi::PathJoin =>
                "After joining, verify the resolved path starts with your base directory:\n\
                 ```\nconst resolved = path.resolve(baseDir, userInput);\n\
                 if (!resolved.startsWith(path.resolve(baseDir))) { throw new Error('Invalid path'); }\n```",
            PathApi::SendFile =>
                "Use res.download() with { root: '/safe/base/dir' } option, or validate resolved \
                 path is within allowed directory.",
        }
    }

    fn why_it_matters(self) -> &'static str {
        match self {
            PathApi::FileOp => {
                "Attackers could read sensitive files like /etc/passwd or overwrite critical \
                 system files."
            }
            PathApi::PathJoin => {
                "path.join() is commonly misunderstood as safe, but it preserves '../' sequences \
                 allowing directory escape."
            }
            PathApi::SendFile => {
                "Attackers could download sensitive configuration files, source code, or \
                 credentials from the server."
            }
        }
    }

    /// Severity table for `(api, arg_kind, has_user_input_marker)`.
    ///
    /// `has_user_input_marker` reflects the result of the "does the
    /// argument expression contain a request-shaped substring" check.
    /// When the AST said the arg was a variable/concat/interpolation
    /// AND that substring check fired, we have higher confidence than
    /// when only one of the two signals is present.
    fn severity_for(self, kind: PathArgKind, has_user_marker: bool) -> Severity {
        match (self, kind) {
            // Static literal: never a sink. Filtered out post-merge.
            (_, PathArgKind::StaticLiteral) => Severity::Low,
            // For PathJoin: only fire when there's a non-literal arg.
            // The helper itself is benign with all-literal args.
            (PathApi::PathJoin, PathArgKind::Unknown) => Severity::Low,
            // Variable / interpolation / concatenation with the
            // user-input marker present → High; without → Medium.
            (_, PathArgKind::Interpolated)
            | (_, PathArgKind::UserVariable)
            | (_, PathArgKind::Concatenation) => {
                if has_user_marker {
                    Severity::High
                } else {
                    Severity::Medium
                }
            }
            // Catch-all unknown shape with marker: treat as Medium.
            (_, PathArgKind::Unknown) => {
                if has_user_marker {
                    Severity::Medium
                } else {
                    Severity::Low
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Pass A: AST scan
// ---------------------------------------------------------------------------

/// One path-traversal-shaped call site.
struct PathSite<'a> {
    call_node: tree_sitter::Node<'a>,
    api: PathApi,
    arg_kind: PathArgKind,
    /// Bytes of the path-argument expression — used for the
    /// user-input substring check.
    arg_text: String,
}

// ---------------------------------------------------------------------------
// Dual-branch policy
// ---------------------------------------------------------------------------

/// Per-detector decision: which path-traversal sites get the
/// dual-branch treatment on this run.
///
/// Mirrors Phase 2a's `insecure_crypto::DualBranchPolicy`; the same
/// rationale applies. This struct is the single named place that
/// encodes Phase 2b's migration scope. Adding a language or API to
/// dual-branch scope is a one-line change to [`Self::applies_to`];
/// reviewers can audit "which sites are dual-branched right now?" by
/// reading one match arm rather than diff-spotting `if dual_branch_enabled`
/// scattered across the scanner.
///
/// # Why this isn't just a `bool`
///
/// 1. The "should I dual-branch this finding?" decision depends on
///    more than the project flag — it also depends on the language
///    (Python only in Phase 2b) and the matched API. Compressing all
///    of that into a single bool at the call site would invite drift
///    when later phases migrate JS or Go.
///
/// 2. `policy.applies_to(lang, api)` is grep-friendly and
///    self-documenting at the call site; `dual_branch_enabled` is not.
///
/// 3. `DualBranchPolicy` is unit-testable in isolation, separate from
///    the AST walk.
struct DualBranchPolicy {
    /// True iff the project's `[dual_branch]` config has the flag on
    /// for `path-traversal`. Captured from `ctx.dual_branch` once at
    /// the top of `detect()`.
    flag_on: bool,
}

impl DualBranchPolicy {
    /// True iff `(lang, api)` is in Phase 2b's migration scope AND the
    /// project flag is on.
    ///
    /// Phase 2b scope: Python files only, all three `PathApi` variants
    /// (`FileOp`, `PathJoin`, `SendFile`). Other languages emit
    /// single-branch findings unchanged regardless of flag state.
    fn applies_to(&self, lang: Language, _api: PathApi) -> bool {
        if !self.flag_on {
            return false;
        }
        if !matches!(lang, Language::Python) {
            return false;
        }
        // All three APIs are in scope for Python. The match exists
        // (even though it's effectively a wildcard today) so that a
        // future scope tightening — e.g. only `PathJoin` gets the
        // dual-branch treatment because it's noisiest — has a single
        // place to land.
        true
    }
}

impl PathTraversalDetector {
    fn scan_file_ast(
        &self,
        inputs: &ScanAstInputs<'_>,
        _taint_result: &TaintAnalysisResult,
        dual_branch_policy: &DualBranchPolicy,
    ) -> Vec<Finding> {
        let path = inputs.path();
        let content = inputs.content();
        let ext = inputs.ext();
        let lang = inputs.lang;
        let cached_tree = inputs.cached_tree;
        let mut findings = vec![];
        if content.contains('\0') {
            return findings;
        }

        let owned;
        let root = match cached_tree {
            Some(tree) => tree.root_node(),
            None => match parse_root_ext(content, lang, ext) {
                Some(t) => {
                    owned = t;
                    owned.root_node()
                }
                None => return findings,
            },
        };

        let bytes = content.as_bytes();
        let lines: Vec<&str> = content.lines().collect();

        let py_aliases = if matches!(lang, Language::Python) {
            super::python_imports::collect_python_from_imports(root, bytes)
        } else {
            HashMap::new()
        };
        let py_module_aliases = if matches!(lang, Language::Python) {
            super::python_imports::collect_python_module_aliases(root, bytes)
        } else {
            HashMap::new()
        };

        let mut sites: Vec<PathSite> = Vec::new();
        let ctx = AstWalkCtx {
            lang,
            source: bytes,
        };
        let aliases = super::python_imports::PythonAliases::new(&py_aliases, &py_module_aliases);
        collect_path_sites(&ctx, root, &aliases, &mut sites);

        let rel_path = path
            .strip_prefix(&self.repository_path)
            .unwrap_or(path)
            .to_path_buf();
        let file_str = path.to_string_lossy();
        let is_test_file = file_str.contains("/test")
            || file_str.contains("/tests/")
            || file_str.contains("_test.")
            || file_str.contains(".test.")
            || file_str.contains("/spec/")
            || file_str.contains("_spec.");

        for site in sites {
            if findings.len() >= self.max_findings {
                break;
            }
            let line_idx = site.call_node.start_position().row;
            if let Some(line) = lines.get(line_idx) {
                let prev = if line_idx > 0 {
                    Some(lines[line_idx - 1])
                } else {
                    None
                };
                if crate::detectors::is_line_suppressed(line, prev) {
                    continue;
                }
            }
            let line_num = (line_idx + 1) as u32;

            // Branch on dual-branch policy. The policy struct's docstring
            // explains why this isn't just `if dual_branch_enabled`.
            if dual_branch_policy.applies_to(lang, site.api) {
                let snippet = lines.get(line_idx).map(|s| s.trim()).unwrap_or("");
                findings.push(self.build_dual_branch_python_finding(
                    &rel_path,
                    line_num,
                    site.api,
                    snippet,
                    site.call_node,
                    bytes,
                    &lines,
                ));
                continue;
            }

            let has_user_marker = contains_any(USER_INPUT_FINDERS, &site.arg_text);
            let mut severity = site.api.severity_for(site.arg_kind, has_user_marker);

            // Test-file de-rating: same policy as the pre-AST detector.
            if is_test_file {
                severity = match severity {
                    Severity::Critical => Severity::Medium,
                    Severity::High => Severity::Low,
                    Severity::Medium => Severity::Low,
                    other => other,
                };
            }

            // Skip Low up front so we don't allocate Findings for them.
            if severity == Severity::Low {
                continue;
            }

            findings.push(Finding {
                id: String::new(),
                detector: "PathTraversalDetector".to_string(),
                severity,
                title: site.api.title().to_string(),
                description: site.api.base_description().to_string(),
                affected_files: vec![rel_path.clone()],
                line_start: Some(line_num),
                line_end: Some(line_num),
                suggested_fix: Some(site.api.suggested_fix().to_string()),
                estimated_effort: Some("30 minutes".to_string()),
                category: Some("security".to_string()),
                cwe_id: Some("CWE-22".to_string()),
                why_it_matters: Some(site.api.why_it_matters().to_string()),
                ..Default::default()
            });
        }

        findings
    }

    /// Build a dual-branch Python path-traversal finding.
    ///
    /// Only called when [`DualBranchPolicy::applies_to`] returns true,
    /// i.e. the project flag is on AND the site is in Phase 2b's
    /// migration scope (Python + any of `FileOp`/`PathJoin`/`SendFile`).
    /// Pipeline:
    ///
    /// ```text
    /// call_node ─extract_python_evidence─> Evidence ─predict─> Prediction
    ///         └── caller already validated lang + api
    /// ```
    ///
    /// The resulting `Finding` carries:
    ///
    /// - Primary fields (`severity`, `title`, `description`,
    ///   `suggested_fix`) from the predicted branch.
    /// - `alternative_branch` populated with the opposite branch.
    /// - `prediction_reasons` holding each typed signal that
    ///   contributed to the score.
    /// - `resolution_signals` for collapsing annotations (when present).
    ///
    /// Severity convention from decision **D3**: predicted RealBug →
    /// High; predicted Benign → Info. The alternative carries the
    /// opposite severity so consumers that disagree with the
    /// prediction (or render `--show-alternatives`) get the original
    /// High interpretation.
    ///
    /// Important: dual-branch findings opt OUT of Pass B taint
    /// enrichment in [`merge_taint_paths`] — they're already classified
    /// by the predictor, and the taint pass's unconditional `Critical`
    /// bump would defeat that. The skip is keyed on
    /// `Finding::is_dual_branch()`.
    fn build_dual_branch_python_finding(
        &self,
        rel_path: &Path,
        line_num: u32,
        api: PathApi,
        snippet: &str,
        call_node: tree_sitter::Node<'_>,
        source: &[u8],
        lines: &[&str],
    ) -> Finding {
        let api_label = match api {
            PathApi::FileOp => "open",
            PathApi::PathJoin => "os.path.join",
            PathApi::SendFile => "send_file",
        };

        let evidence = evidence::extract_python_evidence(call_node, source, lines);
        let prediction = predict::predict(&evidence, api_label);

        let predicted_label = prediction.predicted;
        let predicted_severity = prediction.predicted_severity;
        let predicted_title = match predicted_label {
            crate::dual_branch::BranchLabel::RealBug => {
                format!("Path traversal via {api_label}")
            }
            crate::dual_branch::BranchLabel::Benign => {
                format!("Internal path-join in {api_label} (informational)")
            }
        };
        let predicted_description = format!(
            "**Path traversal (dual-branch)**\n\n\
             **API**: `{}`\n\n\
             **Location**: {}:{}\n\n\
             **Code**:\n```\n{}\n```\n\n\
             {}",
            api_label,
            rel_path.display(),
            line_num,
            snippet,
            match predicted_label {
                crate::dual_branch::BranchLabel::RealBug => format!(
                    "The path argument to `{api_label}` appears to originate from \
                     user-controlled input. The predictor leans RealBug for this \
                     call site (see `prediction_reasons`)."
                ),
                crate::dual_branch::BranchLabel::Benign => format!(
                    "The path argument to `{api_label}` appears to be \
                     internal/literal/config-derived. The predictor leans Benign \
                     (see `prediction_reasons`); the High-severity interpretation \
                     is carried in `alternative_branch`."
                ),
            },
        );
        let predicted_fix = match predicted_label {
            crate::dual_branch::BranchLabel::RealBug => Some(
                "Validate the path component against an allowlist, or wrap with \
                 `os.path.basename(...)` to strip `..` sequences. For file-serving \
                 endpoints, use `flask.send_from_directory` or \
                 `pathlib.Path.resolve` with a base-prefix check.\n\n\
                 If this is a false positive (the path is internal/config-derived \
                 and not attacker-reachable), annotate the call site with \
                 `# repotoire: internal-path[<reason>]` to collapse the finding \
                 to Info."
                    .to_string(),
            ),
            crate::dual_branch::BranchLabel::Benign => Some(
                "If this is intentional internal use, annotate \
                 `# repotoire: internal-path[<reason>]` to collapse the finding to \
                 Info definitively. If this IS attacker-reachable (the alternative \
                 branch), validate against an allowlist or wrap with \
                 `os.path.basename(...)`."
                    .to_string(),
            ),
        };

        let mut finding = Finding {
            id: String::new(),
            detector: "PathTraversalDetector".to_string(),
            severity: predicted_severity,
            title: predicted_title,
            description: predicted_description,
            affected_files: vec![rel_path.to_path_buf()],
            line_start: Some(line_num),
            line_end: Some(line_num),
            suggested_fix: predicted_fix,
            estimated_effort: Some("30 minutes".to_string()),
            category: Some("security".to_string()),
            cwe_id: Some("CWE-22".to_string()),
            why_it_matters: Some(
                "Path traversal lets attackers read or write files outside the \
                 intended directory — but not every path-join call site is \
                 attacker-reachable. The predictor's job is to distinguish."
                    .to_string(),
            ),
            ..Default::default()
        };

        finding = finding.with_alternative_branch(prediction.alternative_branch);
        for reason in prediction.reasons {
            finding = finding.with_prediction_reason(reason);
        }
        for resolution in prediction.resolutions {
            finding = finding.with_resolution_signal(resolution);
        }

        finding
    }
}

/// User-input marker check for an argument expression's source text.
/// Mirrors the substring set the previous line-loop applied to the
/// whole line, but applied only to the path-argument bytes, which cuts
/// FPs from siblings on the same line.
static USER_INPUT_FINDERS: &[&LazyLock<memchr::memmem::Finder<'static>>] = &[
    &FIND_REQ_PARAMS,
    &FIND_REQ_QUERY,
    &FIND_REQ_BODY,
    &FIND_REQ_FILE,
    &FIND_REQUEST_GET,
    &FIND_REQUEST_POST,
    &FIND_REQUEST_FILES,
    &FIND_REQUEST_ARGS,
    &FIND_REQUEST_FORM,
    &FIND_REQUEST_DATA,
    &FIND_REQUEST_VALUES,
    &FIND_PARAMS_BRACKET,
    &FIND_INPUT_PAREN,
    &FIND_SYS_ARGV,
    &FIND_PROCESS_ARGV,
    &FIND_R_URL,
    &FIND_C_PARAM,
    &FIND_C_QUERY,
    &FIND_FORM_VALUE,
    &FIND_R_FORM,
    &FIND_QUERY_BRACKET,
    &FIND_QUERY_GET,
    &FIND_BODY_BRACKET,
    &FIND_BODY_GET,
];

// ---------------------------------------------------------------------------
// AST walking (per-language match arms)
// ---------------------------------------------------------------------------

fn collect_path_sites<'a>(
    ctx: &AstWalkCtx<'a>,
    node: tree_sitter::Node<'a>,
    py_aliases: &super::python_imports::PythonAliases<'_>,
    out: &mut Vec<PathSite<'a>>,
) {
    if let Some(site) = match_path_site(node, ctx.source, ctx.lang, py_aliases) {
        out.push(site);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_path_sites(ctx, child, py_aliases, out);
    }
}

fn match_path_site<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    lang: Language,
    py_aliases: &super::python_imports::PythonAliases<'_>,
) -> Option<PathSite<'a>> {
    match (node.kind(), lang) {
        ("call", Language::Python) => match_python_call(node, source, py_aliases),
        ("call_expression", Language::JavaScript | Language::TypeScript) => {
            match_js_call(node, source)
        }
        ("call_expression", Language::Go) => match_go_call(node, source),
        _ => None,
    }
}

// ----- Python ---------------------------------------------------------------

/// `(module, name)` → (api, arg-index-of-path).
fn classify_python_path_callee(module: &str, name: &str) -> Option<(PathApi, usize)> {
    Some(match (module, name) {
        // Bare open() — module is "" for a from-import resolution; we
        // also accept the canonical form `open(...)` from `__builtins__`
        // via the bare-identifier branch.
        ("", "open") | ("builtins", "open") | ("io", "open") => (PathApi::FileOp, 0),
        ("os", "remove" | "unlink" | "rmdir" | "mkdir" | "rename" | "chmod") => {
            (PathApi::FileOp, 0)
        }
        ("shutil", "copy" | "copyfile" | "copy2" | "move" | "rmtree") => (PathApi::FileOp, 0),
        ("os.path", "join") => (PathApi::PathJoin, 0),
        // `pathlib.Path(user_input)` is the canonical wrapper; the
        // ".read_text()" / ".open()" follow-up is detected as a chained
        // call but the Path() constructor itself is the sink we flag
        // when the arg is non-literal.
        ("pathlib", "Path") => (PathApi::FileOp, 0),
        // Flask / Django / Starlette file responses.
        ("flask", "send_file" | "send_from_directory") => (PathApi::SendFile, 0),
        ("django.http", "FileResponse") => (PathApi::SendFile, 0),
        ("starlette.responses", "FileResponse") => (PathApi::SendFile, 0),
        _ => return None,
    })
}

fn match_python_call<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    aliases: &super::python_imports::PythonAliases<'_>,
) -> Option<PathSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let func = unwrap_callee(func);
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);

    let (api, idx) = match func.kind() {
        "attribute" => {
            let obj = func.child_by_field_name("object")?;
            let attr = func.child_by_field_name("attribute")?;
            let attr_text = node_text(attr, source)?;
            // Build dotted module label, with alias resolution.
            //
            // - For receiver `os.path`, recv_text == "os.path"; we keep
            //   it dotted so `("os.path", "join")` resolves correctly.
            // - For receiver `o` after `import os as o`, aliases.modules
            //   maps "o" → "os".
            // - For receiver `op` after `import os.path as op`,
            //   aliases.modules maps "op" → "os.path".
            let recv_text = node_text(obj, source).unwrap_or("");
            let module_label = aliases
                .modules
                .get(recv_text)
                .cloned()
                .unwrap_or_else(|| recv_text.to_string());
            classify_python_path_callee(&module_label, attr_text)?
        }
        "identifier" => {
            let name = node_text(func, source)?;
            // `from os import unlink` — aliases.imports maps the local
            // name back to its module. For `open` itself we don't
            // require an alias entry since it's a builtin.
            let module = if name == "open" {
                "".to_string()
            } else {
                aliases.imports.get(name).cloned()?
            };
            classify_python_path_callee(&module, name)?
        }
        _ => return None,
    };

    let target = arg_nodes.get(idx).copied()?;
    let target = if target.kind() == "keyword_argument" {
        arg_nodes
            .iter()
            .copied()
            .find(|a| a.kind() != "keyword_argument")?
    } else {
        target
    };
    // For PathJoin, we may have multiple args. Inspect them all and
    // pick the strongest classification.
    let arg_kind = if api == PathApi::PathJoin {
        classify_path_args_python(&arg_nodes, source)
    } else {
        classify_path_arg_python(target, source)
    };
    let arg_text = collect_arg_text(&arg_nodes, source);

    Some(PathSite {
        call_node: node,
        api,
        arg_kind,
        arg_text,
    })
}

fn classify_path_args_python(args: &[tree_sitter::Node<'_>], source: &[u8]) -> PathArgKind {
    let mut strongest = PathArgKind::StaticLiteral;
    for a in args {
        if a.kind() == "keyword_argument" {
            continue;
        }
        let k = classify_path_arg_python(*a, source);
        strongest = strongest_kind(strongest, k);
    }
    strongest
}

#[allow(clippy::only_used_in_recursion)]
fn classify_path_arg_python(node: tree_sitter::Node<'_>, source: &[u8]) -> PathArgKind {
    match node.kind() {
        "string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "interpolation" {
                    return PathArgKind::Interpolated;
                }
            }
            PathArgKind::StaticLiteral
        }
        "concatenated_string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if classify_path_arg_python(child, source) == PathArgKind::Interpolated {
                    return PathArgKind::Interpolated;
                }
            }
            PathArgKind::StaticLiteral
        }
        "binary_operator" => {
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");
            let mut found_var = false;
            let mut found_lit = false;
            for opt in [left, right].iter().flatten() {
                match classify_path_arg_python(*opt, source) {
                    PathArgKind::UserVariable
                    | PathArgKind::Interpolated
                    | PathArgKind::Concatenation
                    | PathArgKind::Unknown => found_var = true,
                    PathArgKind::StaticLiteral => found_lit = true,
                }
            }
            if found_var && found_lit {
                PathArgKind::Concatenation
            } else if found_var {
                PathArgKind::UserVariable
            } else {
                PathArgKind::StaticLiteral
            }
        }
        "identifier" | "attribute" | "subscript" | "call" => PathArgKind::UserVariable,
        "parenthesized_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_path_arg_python(c, source);
                }
            }
            PathArgKind::Unknown
        }
        "await" | "conditional_expression" => {
            let mut strongest = PathArgKind::StaticLiteral;
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    strongest = strongest_kind(strongest, classify_path_arg_python(c, source));
                }
            }
            strongest
        }
        _ => PathArgKind::Unknown,
    }
}

// ----- JS / TS --------------------------------------------------------------

fn match_js_call<'a>(node: tree_sitter::Node<'a>, source: &'a [u8]) -> Option<PathSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let func = unwrap_callee(func);

    let (api, idx) = match func.kind() {
        "identifier" => {
            // Bare `readFile`, `writeFileSync`, etc. — likely
            // destructured from `fs`. Same canonical mapping.
            match node_text(func, source)? {
                "readFile" | "readFileSync" | "writeFile" | "writeFileSync" | "appendFile"
                | "unlink" | "unlinkSync" | "rmdir" | "mkdir" | "copyFile" | "rename" | "stat"
                | "statSync" | "access" | "accessSync" | "createReadStream"
                | "createWriteStream" | "open" => (PathApi::FileOp, 0),
                _ => return None,
            }
        }
        "member_expression" => {
            let obj = func.child_by_field_name("object")?;
            let prop = func.child_by_field_name("property")?;
            let prop_text = node_text(prop, source)?;
            let recv = receiver_chain_label_js(obj, source);
            let is_fs = matches!(recv.as_str(), "fs" | "fsp" | "fspromises");
            let is_path = matches!(recv.as_str(), "path");
            // Express response object: typical name is `res`, but also
            // `response`. Receiver can be `res`, `response`, or
            // member-of-member ending in those.
            let is_response = matches!(recv.as_str(), "res" | "response");
            if is_fs {
                match prop_text {
                    "readFile" | "readFileSync" | "writeFile" | "writeFileSync" | "appendFile"
                    | "unlink" | "unlinkSync" | "rmdir" | "mkdir" | "copyFile" | "rename"
                    | "stat" | "statSync" | "access" | "accessSync" | "createReadStream"
                    | "createWriteStream" | "open" => (PathApi::FileOp, 0),
                    _ => return None,
                }
            } else if is_path {
                match prop_text {
                    "join" | "resolve" => (PathApi::PathJoin, 0),
                    _ => return None,
                }
            } else if is_response {
                match prop_text {
                    "sendFile" | "download" => (PathApi::SendFile, 0),
                    _ => return None,
                }
            } else {
                return None;
            }
        }
        _ => return None,
    };

    let target = arg_nodes.get(idx).copied()?;
    let arg_kind = if api == PathApi::PathJoin {
        classify_path_args_js(&arg_nodes, source)
    } else {
        classify_path_arg_js(target, source)
    };
    let arg_text = collect_arg_text(&arg_nodes, source);

    Some(PathSite {
        call_node: node,
        api,
        arg_kind,
        arg_text,
    })
}

fn classify_path_args_js(args: &[tree_sitter::Node<'_>], source: &[u8]) -> PathArgKind {
    let mut strongest = PathArgKind::StaticLiteral;
    for a in args {
        let k = classify_path_arg_js(*a, source);
        strongest = strongest_kind(strongest, k);
    }
    strongest
}

#[allow(clippy::only_used_in_recursion)]
fn classify_path_arg_js(node: tree_sitter::Node<'_>, source: &[u8]) -> PathArgKind {
    match node.kind() {
        "string" => PathArgKind::StaticLiteral,
        "template_string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "template_substitution" {
                    return PathArgKind::Interpolated;
                }
            }
            PathArgKind::StaticLiteral
        }
        "binary_expression" => {
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");
            let mut found_var = false;
            let mut found_lit = false;
            for opt in [left, right].iter().flatten() {
                match classify_path_arg_js(*opt, source) {
                    PathArgKind::UserVariable
                    | PathArgKind::Interpolated
                    | PathArgKind::Concatenation
                    | PathArgKind::Unknown => found_var = true,
                    PathArgKind::StaticLiteral => found_lit = true,
                }
            }
            if found_var && found_lit {
                PathArgKind::Concatenation
            } else if found_var {
                PathArgKind::UserVariable
            } else {
                PathArgKind::StaticLiteral
            }
        }
        "identifier" | "member_expression" | "subscript_expression" | "call_expression"
            if is_trusted_node_global(node, source) =>
        {
            // `__dirname`, `__filename`, and `process.cwd()` are
            // application-controlled Node built-ins — not attacker
            // controllable. Treat them as static literals so callers like
            // `path.join(process.cwd(), 'src', 'foo')` don't fire.
            PathArgKind::StaticLiteral
        }
        "identifier" | "member_expression" | "subscript_expression" | "call_expression" => {
            PathArgKind::UserVariable
        }
        "parenthesized_expression"
        | "await_expression"
        | "as_expression"
        | "type_assertion_expression"
        | "non_null_expression"
        | "satisfies_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_path_arg_js(c, source);
                }
            }
            PathArgKind::Unknown
        }
        "ternary_expression" => {
            let consequence = node.child_by_field_name("consequence");
            let alternative = node.child_by_field_name("alternative");
            let mut strongest = PathArgKind::StaticLiteral;
            for opt in [consequence, alternative].iter().flatten() {
                let k = classify_path_arg_js(*opt, source);
                strongest = strongest_kind(strongest, k);
            }
            strongest
        }
        _ => PathArgKind::Unknown,
    }
}

/// Recognise the trusted Node built-ins `__dirname`, `__filename`, and
/// `process.cwd()` (with or without parentheses, i.e. `process.cwd` member
/// access too). These are application-controlled, never reachable from an
/// HTTP request body / query / header, and routinely used in `path.join` to
/// build internal paths. Treating them as untrusted produces high-volume
/// FPs (the original PR #87 bug). Real user-controlled `member_expression`s
/// like `req.body.path` still fall through to `UserVariable`.
fn is_trusted_node_global(node: tree_sitter::Node<'_>, source: &[u8]) -> bool {
    match node.kind() {
        "identifier" => {
            matches!(node_text(node, source), Some("__dirname" | "__filename"))
        }
        "member_expression" => {
            // `process.cwd` (member access without parens) is also trusted.
            let obj = match node.child_by_field_name("object") {
                Some(n) => n,
                None => return false,
            };
            let prop = match node.child_by_field_name("property") {
                Some(n) => n,
                None => return false,
            };
            matches!(node_text(obj, source), Some("process"))
                && matches!(node_text(prop, source), Some("cwd"))
        }
        "call_expression" => {
            // `process.cwd()` — the callee must be the trusted member expr.
            let func = match node.child_by_field_name("function") {
                Some(n) => n,
                None => return false,
            };
            if func.kind() != "member_expression" {
                return false;
            }
            is_trusted_node_global(func, source)
        }
        _ => false,
    }
}

// ----- Go -------------------------------------------------------------------

fn match_go_call<'a>(node: tree_sitter::Node<'a>, source: &'a [u8]) -> Option<PathSite<'a>> {
    let func = node.child_by_field_name("function")?;
    if func.kind() != "selector_expression" {
        return None;
    }
    let operand = func.child_by_field_name("operand")?;
    let field = func.child_by_field_name("field")?;
    let operand_text = node_text(operand, source)?;
    let field_text = node_text(field, source)?;
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);

    let (api, idx) = match (operand_text, field_text) {
        (
            "os",
            "Open" | "Create" | "OpenFile" | "Remove" | "RemoveAll" | "Rename" | "Mkdir"
            | "MkdirAll" | "Chmod",
        ) => (PathApi::FileOp, 0),
        ("ioutil", "ReadFile" | "WriteFile" | "ReadDir") => (PathApi::FileOp, 0),
        ("os", _) | ("ioutil", _) => return None,
        ("filepath", "Join" | "Clean") => (PathApi::PathJoin, 0),
        ("http", "ServeFile") => (PathApi::SendFile, 1),
        _ => return None,
    };

    let target = arg_nodes.get(idx).copied()?;
    let arg_kind = if api == PathApi::PathJoin {
        classify_path_args_go(&arg_nodes, source)
    } else {
        classify_path_arg_go(target, source)
    };
    let arg_text = collect_arg_text(&arg_nodes, source);

    Some(PathSite {
        call_node: node,
        api,
        arg_kind,
        arg_text,
    })
}

fn classify_path_args_go(args: &[tree_sitter::Node<'_>], source: &[u8]) -> PathArgKind {
    let mut strongest = PathArgKind::StaticLiteral;
    for a in args {
        let k = classify_path_arg_go(*a, source);
        strongest = strongest_kind(strongest, k);
    }
    strongest
}

#[allow(clippy::only_used_in_recursion)]
fn classify_path_arg_go(node: tree_sitter::Node<'_>, source: &[u8]) -> PathArgKind {
    match node.kind() {
        "interpreted_string_literal" | "raw_string_literal" => PathArgKind::StaticLiteral,
        "binary_expression" => {
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");
            let mut found_var = false;
            let mut found_lit = false;
            for opt in [left, right].iter().flatten() {
                match classify_path_arg_go(*opt, source) {
                    PathArgKind::UserVariable
                    | PathArgKind::Interpolated
                    | PathArgKind::Concatenation
                    | PathArgKind::Unknown => found_var = true,
                    PathArgKind::StaticLiteral => found_lit = true,
                }
            }
            if found_var && found_lit {
                PathArgKind::Concatenation
            } else if found_var {
                PathArgKind::UserVariable
            } else {
                PathArgKind::StaticLiteral
            }
        }
        "identifier" | "selector_expression" | "index_expression" | "call_expression" => {
            PathArgKind::UserVariable
        }
        "parenthesized_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_path_arg_go(c, source);
                }
            }
            PathArgKind::Unknown
        }
        _ => PathArgKind::Unknown,
    }
}

// ---------------------------------------------------------------------------
// Pass B: taint enrichment
// ---------------------------------------------------------------------------

fn merge_taint_paths(
    findings: &mut Vec<Finding>,
    taint_result: &TaintAnalysisResult,
    repo_root: &Path,
) {
    for taint in &taint_result.paths {
        // Resolve the taint sink to a relative path matching what
        // Pass A emitted (Pass A uses the rel-to-repo path).
        let abs_sink = Path::new(&taint.sink_file);
        let rel_sink = abs_sink.strip_prefix(repo_root).unwrap_or(abs_sink);

        let sink_line = taint.sink_line;

        // A finding "sits at" this taint sink if its first affected
        // file matches and its start line is the sink line.
        let sits_at_sink = |f: &Finding| {
            let file_match = f
                .affected_files
                .first()
                .map(|p| p == rel_sink || p == abs_sink)
                .unwrap_or(false);
            file_match && f.line_start == Some(sink_line)
        };

        let mut matched = false;
        for f in findings.iter_mut() {
            if !sits_at_sink(f) {
                continue;
            }
            matched = true;
            // Phase 2b: dual-branch findings opt out of taint
            // mutation. The predictor already chose a branch and a
            // severity for them; the unconditional `Critical` bump
            // below would clobber that. We still record `matched =
            // true` above so we don't emit a duplicate fresh Critical
            // finding at the same site.
            if f.is_dual_branch() {
                continue;
            }
            if taint.is_sanitized {
                f.severity = Severity::Low;
                f.description = format!(
                    "{}\n\n**Taint Analysis Note**: A sanitizer function (`{}`) was found in \
                     the data flow path, which may mitigate this vulnerability.",
                    f.description,
                    taint.sanitizer.as_deref().unwrap_or("unknown")
                );
            } else {
                f.severity = Severity::Critical;
                f.description = format!(
                    "{}\n\n**Taint Analysis Confirmed**: Data flow analysis traced a path from \
                     user input to this file sink without sanitization:\n\n`{}`",
                    f.description,
                    taint.path_string()
                );
            }
        }
        // If no Pass A finding sat at this taint sink line, emit a
        // fresh Critical finding from the taint path. This covers the
        // case where the AST classifier said "Unknown" (and was
        // filtered) but the call-graph BFS found a real source→sink.
        if !matched && !taint.is_sanitized {
            findings.push(Finding {
                id: String::new(),
                detector: "PathTraversalDetector".to_string(),
                severity: Severity::Critical,
                title: "Path traversal confirmed by taint analysis".to_string(),
                description: format!(
                    "{}\n\n**Taint Analysis Confirmed**: Data flow analysis traced a path from \
                     user input to this file sink without sanitization:\n\n`{}`",
                    PathApi::FileOp.base_description(),
                    taint.path_string()
                ),
                affected_files: vec![rel_sink.to_path_buf()],
                line_start: Some(sink_line),
                line_end: Some(sink_line),
                suggested_fix: Some(PathApi::FileOp.suggested_fix().to_string()),
                estimated_effort: Some("30 minutes".to_string()),
                category: Some("security".to_string()),
                cwe_id: Some("CWE-22".to_string()),
                why_it_matters: Some(PathApi::FileOp.why_it_matters().to_string()),
                ..Default::default()
            });
        }
    }
}

// ---------------------------------------------------------------------------
// Generic helpers
// ---------------------------------------------------------------------------

// `collect_named_args`, `unwrap_callee`, `node_text` live in `ast_helpers`
// (imported above).

/// JS member-expression receiver label.
///
/// Audit-style: descend through `require('fs')` so
/// `require('fs').readFile(...)` is recognised as `fs.readFile(...)`.
/// Member-of-member receivers (`this.fs.readFile`, `self.fs.readFile`)
/// resolve to the last segment, lowercased, matching the pattern in
/// `command_injection::receiver_chain_label`.
///
/// Implementation: delegate to the shared
/// [`receiver_chain_label`](crate::detectors::security::ast_helpers::receiver_chain_label)
/// passing this detector's [`require_module_label`] as the resolver —
/// that's the only piece that varies between detectors (it names `fs` /
/// `path` for *this* detector).
fn receiver_chain_label_js(node: tree_sitter::Node<'_>, source: &[u8]) -> String {
    receiver_chain_label_shared(node, source, Some(&require_module_label))
}

/// `require('fs')` / `require('node:fs')` / `import('fs')` →
/// canonical lowercased label `"fs"`. Returns `None` otherwise.
fn require_module_label(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<&'static str> {
    debug_assert_eq!(node.kind(), "call_expression");
    let func = node.child_by_field_name("function")?;
    let func_text = node_text(func, source)?;
    let is_require_or_import =
        matches!(func.kind(), "identifier" | "import") && matches!(func_text, "require" | "import");
    if !is_require_or_import {
        return None;
    }
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let first = arg_nodes.first()?;
    let module = js_string_literal_value(*first, source)?;
    match module.as_str() {
        "fs" | "node:fs" | "fs/promises" | "node:fs/promises" => Some("fs"),
        "path" | "node:path" => Some("path"),
        _ => None,
    }
}

fn js_string_literal_value(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    if node.kind() != "string" {
        return None;
    }
    let mut cursor = node.walk();
    let mut buf = String::new();
    let mut saw_fragment = false;
    for child in node.children(&mut cursor) {
        if child.kind() == "string_fragment" {
            if let Some(t) = node_text(child, source) {
                buf.push_str(t);
                saw_fragment = true;
            }
        }
    }
    if saw_fragment {
        Some(buf)
    } else {
        None
    }
}

// `node_text` lives in `ast_helpers`; imported above.

fn collect_arg_text(args: &[tree_sitter::Node<'_>], source: &[u8]) -> String {
    let mut out = String::new();
    for a in args {
        if let Some(t) = node_text(*a, source) {
            out.push_str(t);
            out.push(' ');
        }
    }
    out
}

/// Severity ordering for `PathArgKind` — used when scanning multiple
/// args (PathJoin) to pick the worst.
fn strongest_kind(a: PathArgKind, b: PathArgKind) -> PathArgKind {
    fn rank(k: PathArgKind) -> u8 {
        match k {
            PathArgKind::StaticLiteral => 0,
            PathArgKind::Unknown => 1,
            PathArgKind::Concatenation => 2,
            PathArgKind::Interpolated => 3,
            PathArgKind::UserVariable => 4,
        }
    }
    if rank(b) > rank(a) {
        b
    } else {
        a
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detectors::base::Detector;
    use crate::graph::builder::GraphBuilder;

    // ----- 9 pre-existing tests (preserved verbatim) -----

    #[test]
    fn test_detects_open_with_user_input() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("vuln.py", "def download(request):\n    filename = request.GET.get(\"file\")\n    f = open(request.GET[\"file\"], \"r\")\n    return f.read()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect open() with user-controlled path from request"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.title.to_lowercase().contains("path traversal")),
            "Finding should mention path traversal. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
        assert!(
            findings
                .iter()
                .any(|f| f.cwe_id.as_deref() == Some("CWE-22")),
            "Finding should have CWE-22"
        );
    }

    #[test]
    fn test_no_findings_for_hardcoded_path() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("safe.py", "def read_config():\n    with open(\"config/settings.json\", \"r\") as f:\n        return json.load(f)\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Hardcoded path should have no path traversal findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_get_full_path() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("views.py", "from django.http import HttpResponseRedirect\n\ndef my_view(request):\n    return HttpResponseRedirect(request.get_full_path())\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag request.get_full_path() as path traversal. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_list_remove() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("library.py", "def process(request):\n    params = list(request.GET.keys())\n    params.remove('page')\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag list.remove() as file operation. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_still_detects_real_path_traversal() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("download.py", "import os\n\ndef download(request):\n    filepath = os.path.join('/uploads', request.GET.get('file'))\n    return open(filepath, 'r').read()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should still detect real path traversal with request.GET"
        );
    }

    #[test]
    fn test_detects_path_join_with_req_params_js() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("download.js", "const path = require('path');\n\nfunction getFile(req, res) {\n    const filePath = path.join('/uploads', req.params.filename);\n    res.sendFile(filePath);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect path.join with req.params user input in JS"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.cwe_id.as_deref() == Some("CWE-22")),
            "Finding should have CWE-22"
        );
    }

    #[test]
    fn test_detects_readfile_with_request_query_ts() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("serve.ts", "import fs from 'fs';\n\nfunction serveFile(req: Request, res: Response) {\n    const name = req.query.file;\n    const data = fs.readFileSync('/data/' + req.query.file);\n    res.send(data);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect readFileSync with req.query in TypeScript"
        );
    }

    #[test]
    fn test_no_finding_for_path_traversal_in_comment() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("safe.py", "# Vulnerable: open(request.GET['file'], 'r')\ndef read_config():\n    with open('config.json', 'r') as f:\n        return f.read()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Path traversal pattern in a comment should not produce findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_sendfile_with_user_input_js() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("server.js", "const express = require('express');\n\napp.get('/download', (req, res) => {\n    const file = req.query.file;\n    res.sendFile(req.query.file);\n});\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect sendFile with user-controlled req.query"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.title.to_lowercase().contains("path traversal")),
            "Finding should mention path traversal. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // ----- AST migration cohort (12 new tests) -----

    // Cohort 1: shapes that already passed pre-migration (sanity).
    #[test]
    fn test_detects_open_with_user_input_python_ast() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "v.py",
                "def f(request):\n    return open(request.args.get('file')).read()\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect open() with user input via AST"
        );
    }

    #[test]
    fn test_detects_fs_readfile_with_req_param_js_ast() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "v.js",
                "const fs = require('fs');\nfs.readFile(req.params.filename);\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect fs.readFile with req.params via AST"
        );
    }

    #[test]
    fn test_skips_open_with_static_literal_python() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("v.py", "def f():\n    return open('/etc/hosts').read()\n")],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Static-literal open() must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_skips_open_in_comment() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("v.py", "# open(user_input)\ndef f():\n    return 1\n")],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Comment-only sink must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // Cohort 2: audit-shape (alias resolution, require descent).
    #[test]
    fn test_b1_require_fs_readfile_via_require_alias_js() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("v.js", "require('fs').readFile(req.body.path);\n")],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "require('fs').readFile(...) should fire via receiver descent. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_python_aliased_module_open() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("v.py", "import os.path as op\ndef f(request):\n    return op.join('/base', request.args.get('x'))\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Aliased `import os.path as op` then `op.join(base, user)` should fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_skips_open_method_name_python() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "v.py",
                "class Reader:\n    def open(self):\n        return self\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Method named `open` is a definition, not a call site. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_path_join_with_concatenation_python() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("v.py", "import os\ndef f(request):\n    return os.path.join('/base', '../' + request.args.get('x'))\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "os.path.join(base, '../' + user) should fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // Cohort 3: audit-pending features.
    #[test]
    fn test_detects_pathlib_path_with_user_input_python() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("v.py", "import pathlib\ndef f(request):\n    return pathlib.Path(request.args.get('x')).read_text()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "pathlib.Path(user_input).read_text() should fire on the Path() constructor. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_express_sendfile_with_req_path_js() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "v.js",
                "app.get('/x', (req, res) => { res.sendFile(req.params.path); });\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "res.sendFile(req.params.path) should fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
        assert!(findings
            .iter()
            .any(|f| f.title.to_lowercase().contains("download")
                || f.title.to_lowercase().contains("traversal")));
    }

    #[test]
    fn test_taint_confirmed_boosts_to_critical() {
        // Two scenarios validated here:
        //
        // 1. **Direct on-line user input** — `open(request.args.get('x'))`
        //    has the user-input marker present in the arg span, so the
        //    AST classifier emits High (UserVariable + has_user_marker).
        //
        // 2. **Variable-via-line user input** — `f = request.args.get(...)`
        //    then `open(f)` — the marker is NOT in the open() arg span.
        //    Severity stays at Medium until taint analysis (Pass B)
        //    promotes it. Note: the intra-function taint pass reads
        //    from disk via `run_intra_function_taint`, which a
        //    mock-file unit test can't satisfy; that promotion is
        //    exercised end-to-end in the binary verification.
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("app.py", "from flask import request\ndef serve():\n    return open(request.args.get('file')).read()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(!findings.is_empty(), "Direct user-input sink should fire");
        let f = &findings[0];
        assert!(matches!(f.severity, Severity::High | Severity::Critical),
            "Direct user-input sink (marker on the same expression) must be High or Critical; got {:?}", f.severity);
    }

    #[test]
    fn repro_path_join_with_process_cwd_should_not_fire() {
        // PR #87 FP: `path.join(process.cwd(), 'src', 'foo')` is application
        // controlled, not user controlled. Same for __dirname / __filename.
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "docs.ts",
                "import path from 'path';\n\nconst DOCS_CLI_DIR = path.join(process.cwd(), 'src', 'app', 'docs', 'cli');\nconst DIR2 = path.join(__dirname, 'fixtures');\nconst DIR3 = path.join(__filename, 'sibling');\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "path.join(process.cwd()/__dirname/__filename, ...static...) is trusted, should NOT fire. Got: {:?}",
            findings
                .iter()
                .map(|f| format!("{} (line {:?})", f.title, f.line_start))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn repro_path_join_with_user_input_still_fires() {
        // Negative regression: a real user-tainted path.join must still fire.
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "vuln.ts",
                "import path from 'path';\n\nfunction handler(req: Request) {\n  return path.join(req.body.userPath, 'foo');\n}\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "path.join(req.body.userPath, ...) MUST still fire as path traversal"
        );
    }

    #[test]
    fn test_severity_critical_for_user_input_low_for_static_literal() {
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("v.py", "def f(request):\n    a = open('/etc/hosts').read()\n    b = open(request.args.get('x')).read()\n    return a + b\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // Exactly one finding (the user-input line). The static literal
        // is filtered out as Low.
        assert_eq!(
            findings.len(),
            1,
            "Expected exactly the user-input line to fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, &f.severity, f.line_start))
                .collect::<Vec<_>>()
        );
        let f = &findings[0];
        assert!(
            matches!(f.severity, Severity::High | Severity::Critical),
            "User-input sink should be at least High; got {:?}",
            f.severity
        );
        assert_eq!(
            f.line_start,
            Some(3),
            "Should fire on the user-input line (line 3), not the static-literal line (line 2)"
        );
    }

    // ─────────────────────────────────────────────────────────────────
    // Phase 2b: dual-branch end-to-end tests.
    //
    // These exercise the full pipeline:
    //   detect() → DualBranchPolicy::applies_to() → scan_file_ast()
    //          → build_dual_branch_python_finding()
    //          → evidence::extract_python_evidence()
    //          → predict::predict()
    //
    // 2x2 fixture matrix from `2026-05-09-dual-branch-phase2-
    // path-traversal-decisions.md`.
    //
    // Helper `run_dual_branch` flips the project's dual-branch flag on
    // for `path-traversal`; the existing test helpers above leave it
    // off (default behavior).
    // ─────────────────────────────────────────────────────────────────

    fn run_dual_branch(file: &str, content: &str) -> Vec<Finding> {
        use crate::config::DualBranchConfig;
        use std::collections::HashMap;

        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let mut detectors = HashMap::new();
        detectors.insert("path-traversal".to_string(), true);
        let cfg = DualBranchConfig {
            enabled: true,
            detectors,
        };
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(file, content)],
        )
        .with_dual_branch(cfg);
        detector.detect(&ctx).expect("detection should succeed")
    }

    #[test]
    fn flag_off_emits_single_branch_unchanged() {
        // Sanity: with flag off (default), Python path-traversal sites
        // emit no `alternative_branch` and no predictor reasons. Pin
        // the "opt-in" promise — no behavior change unless the user
        // opts in.
        let store = GraphBuilder::new().freeze();
        let detector = PathTraversalDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "vuln.py",
                "def download(request):\n    return open(request.GET[\"file\"], \"r\")\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(!findings.is_empty(), "must still fire single-branch");
        for f in &findings {
            assert!(
                f.alternative_branch.is_none(),
                "no alternative_branch when flag off: {:?}",
                f.title
            );
            assert!(
                f.prediction_reasons.iter().all(|r| r.weight == 0.0),
                "no predictor-emitted (weight ≠ 0) reasons when flag off; \
                 only weight-0 graph-enrichment reasons are allowed. reasons: {:?}",
                f.prediction_reasons
                    .iter()
                    .map(|r| (&r.kind, r.weight))
                    .collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn flag_on_python_path_traversal_emits_dual_branch() {
        // Smoke: flag on, Python open() with request.GET → finding has
        // alternative_branch.
        let findings = run_dual_branch(
            "vuln.py",
            "def download(request):\n    return open(request.GET[\"file\"], \"r\")\n",
        );
        assert!(!findings.is_empty(), "must fire dual-branch");
        let f = &findings[0];
        assert!(
            f.alternative_branch.is_some(),
            "alternative_branch must be populated when flag on. title={:?}",
            f.title
        );
        assert!(
            !f.prediction_reasons.is_empty(),
            "at least one prediction reason"
        );
    }

    // ── 2x2 matrix ──

    #[test]
    fn matrix_predicted_realbug_actual_realbug() {
        // Classic CWE-22: open(request.GET[...]) inside a view.
        // First-arg origin = RequestSource (-0.50) → RealBug → High.
        let findings = run_dual_branch(
            "vuln.py",
            "def download(request):\n    return open(request.GET[\"file\"], \"r\")\n",
        );
        assert!(!findings.is_empty());
        let f = &findings[0];
        assert_eq!(f.severity, Severity::High);
        assert!(
            f.title.to_lowercase().contains("path traversal"),
            "RealBug title; got {:?}",
            f.title
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
        assert_eq!(alt.severity, Severity::Info);
    }

    #[test]
    fn matrix_predicted_benign_actual_benign_literal_first() {
        // Pure literal first arg → +0.40 → Benign → Info.
        let findings = run_dual_branch(
            "internal.py",
            "import os\n\
             def make_config_path():\n\
             \x20   return os.path.join('/etc/myapp', 'config.json')\n",
        );
        assert!(!findings.is_empty(), "must produce a finding");
        let f = &findings[0];
        assert_eq!(
            f.severity,
            Severity::Info,
            "predicted Benign for literal first arg. title={:?}, reasons={:?}",
            f.title,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
        assert_eq!(alt.severity, Severity::High);
    }

    #[test]
    fn matrix_predicted_realbug_actual_benign_synthetic() {
        // Parameter-named first arg, no other signals: -0.30 → RealBug.
        // Human-judged "benign" (the function might be called only
        // with safe paths internally), but the predictor doesn't know
        // and conservatively flags. This is exactly the case where the
        // user adds `# repotoire: internal-path[...]` to override.
        let findings = run_dual_branch(
            "internal.py",
            "import os\n\
             def serve(folder):\n\
             \x20   return open(os.path.join(folder, 'data.json'))\n",
        );
        // The `os.path.join` site — first arg `folder` matches param.
        let f = findings
            .iter()
            .find(|f| f.title.to_lowercase().contains("path traversal"))
            .expect("expected at least one path-traversal finding");
        assert_eq!(
            f.severity,
            Severity::High,
            "Parameter first arg leans RealBug. title={:?}",
            f.title
        );
    }

    #[test]
    fn matrix_predicted_benign_actual_realbug_basename_misuse() {
        // Adversarial: parameter first arg, basename wrapping, inside
        // a test-named function. -0.30 + 0.20 + 0.15 = +0.05 → Benign.
        // A skilled attacker might still reach this through a
        // mis-named test function in production, but this is exactly
        // the case where the alternative_branch matters.
        //
        // We use a non-test-path filename so the existing
        // `is_test_file` derating in the single-branch path doesn't
        // confound us; the test-fn signal still fires from the
        // function name `test_serve`.
        let findings = run_dual_branch(
            "helpers.py",
            "import os\n\
             def test_serve(name):\n\
             \x20   return open(os.path.join(name, 'data'), 'r')\n",
        );
        let f = findings
            .iter()
            .find(|f| f.title.to_lowercase().contains("path"))
            .unwrap_or_else(|| {
                panic!(
                    "expected at least one path finding; got titles: {:?}",
                    findings.iter().map(|f| &f.title).collect::<Vec<_>>()
                )
            });
        // Note: this asserts on the OUTER call (`open`) since that's
        // what the detector's site loop emits first. The `os.path.join`
        // inside `open` is also a site, so we should see two findings
        // total. We assert on the first one.
        assert!(
            f.is_dual_branch(),
            "must be dual-branched; got {:?}",
            f.title
        );
        // The branch could be Benign (if test-fn signal flips it) or
        // RealBug (if it doesn't, because the param-name signal
        // dominates). Pin BOTH possibilities and document which
        // signals fired.
        let total: f32 = f.prediction_reasons.iter().map(|r| r.weight).sum();
        let signals: Vec<_> = f
            .prediction_reasons
            .iter()
            .map(|r| (&r.kind, r.weight))
            .collect();
        if total > 0.0 {
            assert_eq!(
                f.severity,
                Severity::Info,
                "positive sum {total} should predict Benign/Info; signals={signals:?}"
            );
        } else {
            assert_eq!(
                f.severity,
                Severity::High,
                "non-positive sum {total} should predict RealBug/High (tiebreak conservative); \
                 signals={signals:?}"
            );
        }
    }

    // ── Collapsing annotations ──

    #[test]
    fn internal_path_annotation_collapses_via_detect() {
        // Even with a request-source first arg (which would otherwise
        // predict RealBug at -0.50), the `internal-path` annotation
        // forces Benign with confidence 1.0.
        let findings = run_dual_branch(
            "guarded.py",
            "def serve(request):\n\
             \x20   return open(request.GET[\"file\"], \"r\")  # repotoire: internal-path[validated-by-caller]\n",
        );
        assert!(!findings.is_empty(), "must produce a finding");
        let f = &findings[0];
        assert_eq!(
            f.severity,
            Severity::Info,
            "internal-path annotation must collapse to Info even with request-source arg"
        );
        assert_eq!(
            f.resolution_signals.len(),
            1,
            "exactly one resolution signal"
        );
        match &f.resolution_signals[0].kind {
            crate::dual_branch::ResolutionKind::SourceAnnotation { syntax } => {
                assert!(syntax.contains("internal-path"));
                assert!(syntax.contains("validated-by-caller"));
            }
            other => panic!("unexpected resolution kind: {other:?}"),
        }
    }

    #[test]
    fn user_controlled_annotation_collapses_via_detect() {
        // Even with a literal first arg (which would otherwise predict
        // Benign at +0.40), the `user-controlled` annotation forces
        // RealBug with confidence 1.0.
        let findings = run_dual_branch(
            "annotated.py",
            "import os\n\
             def make():\n\
             \x20   return os.path.join('/var/www', x)  # repotoire: user-controlled[GET]\n",
        );
        assert!(!findings.is_empty());
        let f = &findings[0];
        assert_eq!(f.severity, Severity::High);
        assert_eq!(f.resolution_signals.len(), 1);
        match &f.resolution_signals[0].kind {
            crate::dual_branch::ResolutionKind::SourceAnnotation { syntax } => {
                assert!(syntax.contains("user-controlled"));
                assert!(syntax.contains("GET"));
            }
            other => panic!("unexpected resolution kind: {other:?}"),
        }
    }

    // ── Scope guards ──

    #[test]
    fn dual_branch_does_not_affect_non_python_languages() {
        // JS/TS path is not in Phase 2b scope. Even with the flag on,
        // a JS file-op equivalent emits single-branch.
        let findings = run_dual_branch(
            "vuln.js",
            "const fs = require('fs');\n\
             function download(req) {\n\
             \x20   return fs.readFile(req.query.file, 'utf8');\n\
             }\n",
        );
        for f in &findings {
            assert!(
                f.alternative_branch.is_none(),
                "JS path must not be dual-branched in Phase 2b: {:?}",
                f.title
            );
            assert!(
                f.prediction_reasons.iter().all(|r| r.weight == 0.0),
                "JS path must not carry predictor (weight ≠ 0) reasons in Phase 2b"
            );
        }
    }

    #[test]
    fn dual_branch_findings_skip_taint_critical_bump() {
        // When dual-branch fires, the predictor's chosen severity must
        // survive even if Pass B taint analysis would otherwise bump
        // the finding to Critical. With a literal first arg the
        // predictor chooses Benign / Info; that must NOT become
        // Critical from the taint pass.
        //
        // This test fires Pass A only (no taint paths in the mock
        // graph), so it pins the integration shape rather than the
        // Pass B skip logic in isolation. The skip logic itself is
        // documented in `merge_taint_paths` and exercised by the
        // unit-level invariant: `is_dual_branch()` ⇒ skip.
        let findings = run_dual_branch(
            "internal.py",
            "import os\n\
             def make():\n\
             \x20   return os.path.join('/etc', 'config')\n",
        );
        assert!(
            !findings.is_empty(),
            "literal first arg must produce a finding"
        );
        let f = &findings[0];
        assert!(
            f.is_dual_branch(),
            "literal first arg → dual-branch finding emitted"
        );
        assert_eq!(
            f.severity,
            Severity::Info,
            "predicted Benign severity preserved (no taint Critical bump)"
        );
    }

    // ── Worked example: Click utils.py:489 shape ──

    #[test]
    fn click_utils_489_simplified_with_folder_as_param() {
        // A simplified version of Click's `get_app_dir` where the
        // first argument to `os.path.join` IS a function parameter.
        // This pins the predictor's Parameter-signal path: -0.30
        // weight, RealBug verdict, High severity.
        //
        // NOTE: this is NOT the real Click `get_app_dir` signature —
        // see `click_utils_489_real_signature_local_var_folder` below
        // for that shape. We keep this one because it exercises the
        // happy-path Parameter classification end-to-end through the
        // detector.
        let findings = run_dual_branch(
            "click_utils_simplified.py",
            "import os\n\
             def get_app_dir(app_name, folder=None):\n\
             \x20   if folder is None:\n\
             \x20       folder = os.environ.get('XDG_CONFIG_HOME', '~/.config')\n\
             \x20   return os.path.join(folder, app_name)\n",
        );
        let f = findings
            .iter()
            .find(|f| f.title.to_lowercase().contains("path"))
            .unwrap_or_else(|| {
                panic!(
                    "expected a path finding for the os.path.join call; got: {:?}",
                    findings.iter().map(|f| &f.title).collect::<Vec<_>>()
                )
            });
        assert!(f.is_dual_branch());
        // First arg `folder` matches the param list → Parameter (-0.30)
        // → RealBug → High.
        assert_eq!(
            f.severity,
            Severity::High,
            "first arg is parameter `folder` → RealBug. reasons: {:?}",
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        // Confirm the FirstArgIdentifier signal actually fired (not
        // tiebreak).
        assert!(
            f.prediction_reasons.iter().any(|r| matches!(
                &r.kind,
                crate::dual_branch::PredictionReasonKind::FirstArgIdentifier { name } if name == "folder"
            )),
            "FirstArgIdentifier signal must fire for `folder`; got: {:?}",
            f.prediction_reasons
                .iter()
                .map(|r| &r.kind)
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
        assert_eq!(alt.severity, Severity::Info);
        // Document remediation: user adds the annotation to override.
        assert!(
            f.suggested_fix
                .as_deref()
                .unwrap_or("")
                .contains("internal-path"),
            "RealBug suggested_fix should mention the internal-path annotation. \
             got: {:?}",
            f.suggested_fix
        );
    }

    #[test]
    fn click_utils_489_real_signature_local_var_folder() {
        // The ACTUAL Click `get_app_dir` signature
        // (validated 2026-05-10 against pallets/click `main`):
        //
        //   def get_app_dir(app_name, roaming=True, force_posix=False):
        //       ...
        //       folder = os.environ.get(key)   # ← local var
        //       return os.path.join(folder, app_name)
        //
        // `folder` is NOT a function parameter — it's a local
        // variable bound from `os.environ.get(...)`. The v0 evidence
        // extractor only classifies bare identifiers against the
        // enclosing function's parameter list, so `folder` falls
        // through to `Unknown`, no signal fires, sum = 0.0, tiebreak
        // → RealBug → High.
        //
        // This pins the v0 limitation: the verdict is correct (we
        // default-conservative when we don't know the origin), but
        // `prediction_reasons` does NOT contain a FirstArgIdentifier
        // entry for `folder` because the extractor doesn't trace
        // local-variable origins. A v1 extractor would walk back to
        // `os.environ.get(...)` and emit a ConfigSource signal
        // (+0.40) tipping the verdict to Benign.
        //
        // When v1 lands and this test fails, update the assertion
        // AND the decisions-doc "Real-world v0 limitation discovered"
        // section in the same commit.
        let findings = run_dual_branch(
            "click_utils_real.py",
            "import os\n\
             def get_app_dir(app_name, roaming=True, force_posix=False):\n\
             \x20   key = 'APPDATA' if roaming else 'LOCALAPPDATA'\n\
             \x20   folder = os.environ.get(key)\n\
             \x20   return os.path.join(folder, app_name)\n",
        );
        let f = findings
            .iter()
            .find(|f| f.title.to_lowercase().contains("path"))
            .unwrap_or_else(|| {
                panic!(
                    "expected a path finding; got: {:?}",
                    findings.iter().map(|f| &f.title).collect::<Vec<_>>()
                )
            });
        assert!(f.is_dual_branch());
        // Verdict: correct (RealBug / High) — but by TIEBREAK, not
        // by signal.
        assert_eq!(f.severity, Severity::High, "tiebreak → RealBug → High");
        // Pin the v0 limitation: NO FirstArgIdentifier reason for
        // `folder` (because it's a local var, not a param).
        let has_folder_signal = f.prediction_reasons.iter().any(|r| matches!(
            &r.kind,
            crate::dual_branch::PredictionReasonKind::FirstArgIdentifier { name } if name == "folder"
        ));
        assert!(
            !has_folder_signal,
            "v0 limitation: `folder` is a local var, not a param — the \
             extractor should NOT emit a FirstArgIdentifier signal. If \
             this assertion now fails, v1 extractor has landed; update \
             this test and the decisions doc together. reasons: {:?}",
            f.prediction_reasons
                .iter()
                .map(|r| &r.kind)
                .collect::<Vec<_>>()
        );
    }
}