repotoire 0.8.2

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
//! Post-processing pipeline for findings.
//!
//! Applied after detection and before scoring:
//! 0.5. Assign default confidence by category (preserves detector-set values)
//! 0.6. Confidence enrichment with contextual signals (bundled, non-prod, multi-detector, test)
//! 0.65. Apply user FP/TP labels from feedback command (FPs removed; visibility
//!       handled later by the consumer-side `filter_by_min_confidence`)
//! 2. Detector overrides from project config
//!    2.5. Path exclusion filtering
//!    2.6. File-level suppression (`repotoire:ignore-file`)
//!    2.7. Auto-suppress detector test fixtures
//! 4. De-duplicate overlapping dead-code findings
//! 5. Compound smell escalation
//! 6. Security downgrading for non-production paths
//! 7. FP classification filtering
//! 8. Confidence clamping
//! 9. LLM verification (optional, --verify)
//!
//! Steps removed in the new engine architecture (now applied by other stages
//! or by the consumer-side wrapper in `cli/analyze/mod.rs`):
//! - Step 1 (incremental cache update) — engine has its own caching layer
//! - Step 3 (max-files filtering) — moved to the `collect` stage
//! - Step 10 (ranking) — moved to the consumer (presentation concern)
//! - Min-confidence filtering — moved to the consumer
//!
//! `filter_by_min_confidence` and `rank_findings` are still exposed as
//! standalone helpers for the consumer-side wrapper, but they are no longer
//! threaded through `postprocess_findings`.

use crate::config::ProjectConfig;
use crate::detectors::FileContentCache;
use crate::models::{Finding, Severity};

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;

// ── Functions moved from detect.rs ───────────────────────────────────────────

/// Apply detector config overrides from project config
pub(super) fn apply_detector_overrides(
    findings: &mut Vec<Finding>,
    project_config: &ProjectConfig,
) {
    if project_config.detectors.is_empty() {
        return;
    }

    let detector_configs = &project_config.detectors;

    // Filter out disabled detectors
    findings.retain(|f| {
        let detector_name = crate::config::normalize_detector_name(&f.detector);
        if let Some(config) = detector_configs.get(&detector_name) {
            if let Some(false) = config.enabled {
                return false;
            }
        }
        true
    });

    // Apply severity overrides
    for finding in findings.iter_mut() {
        let detector_name = crate::config::normalize_detector_name(&finding.detector);
        if let Some(config) = detector_configs.get(&detector_name) {
            if let Some(sev) = config.severity {
                finding.severity = sev;
            }
        }
    }
}

/// Core label-application logic. Separated from I/O for testability.
/// - FP-labeled findings are removed (or kept with low confidence if show_all).
/// - TP-labeled findings get confidence 0.95 + deterministic = true.
fn apply_labels_to_findings(
    findings: &mut Vec<Finding>,
    labels: &HashMap<String, bool>,
    show_all: bool,
) {
    if labels.is_empty() {
        return;
    }

    let mut fp_findings: Vec<Finding> = Vec::new();
    let mut applied = 0u32;

    findings.retain_mut(|f| {
        match labels.get(&f.id) {
            Some(false) => {
                // FP label: remove from findings
                applied += 1;
                if show_all {
                    f.confidence = Some(0.05);
                    f.threshold_metadata
                        .insert("user_label".to_string(), "false_positive".to_string());
                    fp_findings.push(f.clone());
                }
                false // remove from main vec
            }
            Some(true) => {
                // TP label: pin with high confidence
                applied += 1;
                f.confidence = Some(0.95);
                f.deterministic = true;
                f.threshold_metadata
                    .insert("user_label".to_string(), "true_positive".to_string());
                true // keep
            }
            None => true, // no label
        }
    });

    // Re-insert FP findings for --show-all visibility
    if show_all {
        findings.extend(fp_findings);
    }

    if applied > 0 {
        tracing::info!(
            "Applied {} user feedback labels ({} in training data)",
            applied,
            labels.len()
        );
    }
}

/// Load user FP/TP labels from training_data.jsonl and apply them.
/// Called from the postprocess pipeline; FP findings are removed.
/// `--show-all` visibility is a presentation concern handled by the
/// consumer-side `filter_by_min_confidence`, not here.
fn apply_user_labels(findings: &mut Vec<Finding>) {
    let labels = crate::classifier::FeedbackCollector::default().load_label_map();
    apply_labels_to_findings(findings, &labels, false);
}

/// Inputs for the postprocessing pipeline.
///
/// Bundles the cross-cutting context (graph, config, paths) that every step
/// needs. Replaces the previous 14-parameter signature, of which 7 parameters
/// were dead at the only callsite (incremental cache, max_files, rank,
/// min_confidence, show_all). Those features moved to other stages or to the
/// consumer-side wrapper; see the module-level doc.
pub struct PostprocessParams<'a> {
    pub project_config: &'a ProjectConfig,
    pub all_files: &'a [PathBuf],
    pub graph: &'a dyn crate::graph::GraphQuery,
    pub repo_path: &'a Path,
    pub bypass_set: &'a HashSet<String>,
    /// Run LLM verification (currently a no-op; reserved for `--verify`).
    pub verify: bool,
    /// Optional shared file content + parse-tree cache. When present,
    /// AST-using postprocess passes (e.g. `classify_param_gated_security_branches`)
    /// reuse parses populated by AST-using detectors during analyze. When
    /// absent, the postprocess passes that need an AST construct a
    /// throwaway local cache; they remain functional but lose the warm-cache
    /// perf benefit.
    pub file_cache: Option<&'a Arc<FileContentCache>>,
}

/// Aggregated counters from selected postprocess passes.
///
/// Currently only tracks the universal "param-gated security branch"
/// demotion count. Other steps update their counts via tracing logs; if
/// more callers need structured counters they can be added here.
#[derive(Debug, Default, Clone, Copy)]
pub struct PostprocessSummary {
    /// Number of security findings demoted to Low by
    /// `classify_param_gated_security_branches`.
    pub security_downgraded: usize,
}

/// Run the full post-processing pipeline on findings.
///
/// Returns a [`PostprocessSummary`] for the counters the engine needs to
/// expose in its own stats struct (currently just the param-gated demotion
/// count). The findings vector is mutated in place.
pub fn postprocess_findings(
    findings: &mut Vec<Finding>,
    params: &PostprocessParams<'_>,
) -> PostprocessSummary {
    let mut summary = PostprocessSummary::default();
    // Step 0: Replace random UUIDs with deterministic IDs for cache dedup (#73)
    for finding in findings.iter_mut() {
        let file = finding
            .affected_files
            .first()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let line = finding.line_start.unwrap_or(0);
        finding.id = crate::detectors::base::finding_id(&finding.detector, &file, line);
    }

    // Step 0.5: Assign default confidence to findings that don't have one.
    // Detectors may set confidence explicitly (e.g. voting engine); those are
    // left untouched.  For the rest, we assign a category-specific default so
    // every finding flowing into scoring and reporting has a confidence value.
    assign_default_confidence(findings);

    // Step 0.6: Enrich confidence with contextual signals.
    // Adjusts confidence based on path-based heuristics (bundled code, test
    // files, non-production paths) and multi-detector agreement.  Only fires
    // when signals match; unmatched findings are left untouched.
    crate::detectors::confidence_enrichment::enrich_all(findings);

    // Step 0.7: Phase 1c — graph-aware enrichment of prediction_reasons.
    // Adds typed `EnclosingScope` and `ImportPresence` reasons sourced
    // from the graph. Does NOT change severity or confidence (Phase 1
    // is "collect, don't decide"; severity changes happen in per-detector
    // predictor logic shipped in Phase 2). See
    // `detectors/graph_enrichment.rs` module docs for the design
    // tradeoffs (notably: why we don't gate on `alternative_branch.is_some()`,
    // and why weights are 0.0 in Phase 1c).
    crate::detectors::graph_enrichment::enrich_graph_evidence(findings, params.graph);

    // Step 1.5: Apply user FP/TP labels from feedback command.
    // FP-labeled findings are removed; TP-labeled findings are pinned with
    // confidence 0.95. Visibility of removed FPs (`--show-all`) is a
    // presentation concern and is handled later by `filter_by_min_confidence`
    // in the consumer-side wrapper.
    apply_user_labels(findings);

    // Step 2: Apply detector overrides from project config
    apply_detector_overrides(findings, params.project_config);

    // Step 2.5: Filter out findings for excluded paths (including built-in defaults)
    if !params
        .project_config
        .exclude
        .effective_patterns()
        .is_empty()
    {
        let before = findings.len();
        findings.retain(|f| {
            !f.affected_files
                .iter()
                .any(|p| params.project_config.should_exclude(p))
        });
        let removed = before - findings.len();
        if removed > 0 {
            tracing::debug!("Filtered {} findings from excluded paths", removed);
        }
    }

    // Step 2.55: Per-file detector suppressions from [per_file_ignores] table.
    // Drops findings whose (path, detector) pair matches a configured glob.
    // This is the preferred way to silence stable, audited false positives
    // (e.g. weak-crypto warnings in Git plumbing where SHA-1 is mandated).
    if !params.project_config.per_file_ignores.is_empty() {
        let before = findings.len();
        findings.retain(|f| {
            !f.affected_files
                .iter()
                .any(|p| params.project_config.is_per_file_ignored(p, &f.detector))
        });
        let removed = before - findings.len();
        if removed > 0 {
            tracing::debug!("[per_file_ignores] suppressed {} findings", removed);
        }
    }

    // Step 2.6: File-level suppression — filter findings from files with repotoire:ignore-file
    filter_file_level_suppressed(findings);

    // Step 2.65: Inline suppression — filter findings where the affected line has
    // a repotoire:ignore comment. This catches suppressions for GraphWide detectors
    // (mutual-recursion, infinite-loop, etc.) that don't read file content themselves.
    filter_inline_suppressed(findings);

    // Step 2.7: Auto-suppress detector test fixtures (e.g. SQL injection detector's own test files)
    filter_detector_test_fixtures(findings);

    // Step 4: De-duplicate overlapping dead-code style findings (#50)
    dedupe_dead_code_overlap(findings);

    // Step 4.5: Deduplicate exact-match findings (same detector, title, file, line)
    deduplicate_findings(findings);

    // Step 5: Escalate compound smells (multiple issues in same location)
    crate::scoring::escalate_compound_smells(findings);

    // Step 5.5: Classify security findings inside parameter-gated conditional
    // branches. The library is implementing a caller-controlled security
    // parameter (HTTPX `verify=False`, password hasher `legacy=True`, etc.);
    // the actionable site is the call site, not this implementation.
    //
    // When the per-detector `dual_branch` flag is off (default): demote (not
    // suppress) so reviewers can still find them via `--severity-min low`.
    //
    // When the flag is on for `insecure-tls`: promote `InsecureTlsDetector`
    // findings to dual-branch shape instead. Param-gated → predicted
    // Benign/Info with EnclosingScope evidence; non-param-gated → predicted
    // RealBug/(orig severity) with empty evidence (tiebreaker-conservative).
    // See `docs/superpowers/specs/2026-05-09-dual-branch-phase2-insecure-tls-decisions.md`.
    summary.security_downgraded = classify_param_gated_security_branches(
        findings,
        params.file_cache,
        params.repo_path,
        &params.project_config.dual_branch,
    );

    // Step 6: Downgrade security findings in non-production paths
    downgrade_non_production_security(findings);

    // Step 7: FP filtering with category-aware thresholds
    filter_false_positives(findings, params.graph, params.bypass_set);

    // Step 8: Clamp confidence to [0.0, 1.0] (#35)
    for finding in findings.iter_mut() {
        if let Some(ref mut c) = finding.confidence {
            *c = c.clamp(0.0, 1.0);
        }
    }

    // Step 9: LLM verification (if --verify flag)
    if params.verify {
        // Check for API key availability — don't silently do nothing (#46)
        let has_claude = std::env::var("ANTHROPIC_API_KEY").is_ok();
        let has_ollama = std::process::Command::new("ollama")
            .arg("list")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if !has_claude && !has_ollama {
            eprintln!(
                "\n⚠️  --verify requires an AI backend but none is available.\n\
                 Set ANTHROPIC_API_KEY for Claude, or install Ollama (https://ollama.ai).\n\
                 Skipping LLM verification."
            );
        } else {
            // LLM verification available via --verify flag
            tracing::debug!("LLM verification: backend available, implementation pending");
        }
    }

    // `all_files` is currently unused by the pipeline — kept on the params
    // struct so callers don't need to change when steps that need it (e.g.
    // dead-symbol cross-file dedup) come back.
    let _ = params.all_files;
    let _ = params.repo_path;

    summary
}

/// Assign a category-based default confidence to every finding that lacks one.
///
/// Detectors that already set `confidence` (e.g. the voting engine) are left
/// untouched.  For the rest a default is chosen based on the finding's category:
///
/// | Category            | Default | Rationale                                  |
/// |---------------------|---------|--------------------------------------------|
/// | "architecture"      | 0.85    | Structural evidence is strong              |
/// | "security"          | 0.75    | Taint analysis is good but not perfect     |
/// | "design"            | 0.65    | Code smell detection has higher FP rate     |
/// | "dead-code"/"dead_code" | 0.70 | Graph-based but may miss dynamic dispatch |
/// | "ai_watchdog"       | 0.60    | Heuristic detection                        |
/// | Others / None       | 0.70    | Reasonable default                         |
fn assign_default_confidence(findings: &mut [Finding]) {
    let mut assigned = 0usize;
    for finding in findings.iter_mut() {
        if finding.confidence.is_none() {
            let default = Finding::default_confidence_for_category(finding.category.as_deref());
            finding.confidence = Some(default);
            assigned += 1;
        }
    }
    if assigned > 0 {
        tracing::debug!(
            "Assigned default confidence to {} findings without explicit confidence",
            assigned
        );
    }
}

/// Remove duplicate overlaps between DeadCodeDetector and UnreachableCodeDetector.
/// Keep UnreachableCode findings when both target the same symbol/location.
fn dedupe_dead_code_overlap(findings: &mut Vec<Finding>) {
    use std::collections::HashSet;

    let mut unreachable_keys: HashSet<(String, u32, String)> = HashSet::new();

    for f in findings
        .iter()
        .filter(|f| f.detector == "UnreachableCodeDetector")
    {
        let file = f
            .affected_files
            .first()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let line = f.line_start.unwrap_or(0);
        let symbol = extract_symbol_from_title(&f.title);
        unreachable_keys.insert((file, line, symbol));
    }

    findings.retain(|f| {
        if f.detector != "DeadCodeDetector" {
            return true;
        }

        let file = f
            .affected_files
            .first()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let line = f.line_start.unwrap_or(0);
        let symbol = extract_symbol_from_title(&f.title);

        !unreachable_keys.contains(&(file, line, symbol))
    });
}

fn extract_symbol_from_title(title: &str) -> String {
    title
        .split(':')
        .nth(1)
        .map(|s| s.trim().to_lowercase())
        .unwrap_or_else(|| title.trim().to_lowercase())
}

/// Downgrade security findings in non-production paths (scripts, tests, fixtures).
fn downgrade_non_production_security(findings: &mut [Finding]) {
    use crate::detectors::content_classifier::is_non_production_path;

    const SECURITY_DETECTORS: &[&str] = &[
        "CommandInjectionDetector",
        "SQLInjectionDetector",
        "XssDetector",
        "SsrfDetector",
        "PathTraversalDetector",
        "LogInjectionDetector",
        "EvalDetector",
        "InsecureRandomDetector",
        "HardcodedCredentialsDetector",
        "CleartextCredentialsDetector",
    ];

    for finding in findings.iter_mut() {
        let is_non_prod = finding
            .affected_files
            .iter()
            .any(|p| is_non_production_path(&p.to_string_lossy()));

        if is_non_prod
            && SECURITY_DETECTORS.contains(&finding.detector.as_str())
            && (finding.severity == Severity::Critical || finding.severity == Severity::High)
        {
            finding.severity = Severity::Medium;
            finding.description = format!("[Non-production path] {}", finding.description);
        }
    }
}

/// Demotion note appended to the description of demoted findings.
///
/// Kept as a constant so tests and downstream tooling can match the exact
/// string. Newlines are deliberate: rendered into Markdown surfaces (HTML
/// report, JSON description), the leading blank line separates it from the
/// detector-supplied body.
const PARAM_GATED_DEMOTION_NOTE: &str =
    "\n\n_Note: this finding lives inside a parameter-gated conditional branch. \
The library is implementing a caller-controlled security parameter; the \
actionable security decision is at the call sites that pass the dangerous \
value to this function._";

/// Threshold-metadata key set on demoted findings so downstream tooling
/// (filters, reports, the feedback loop) can identify them without parsing
/// the description text.
pub(crate) const PARAM_GATED_METADATA_KEY: &str = "library_opt_out_implementation";

/// Universal postprocess pass: classify security findings whose enclosing
/// if/elif/else condition references one of the immediately enclosing
/// function's parameters.
///
/// # Two outcomes
///
/// The pass has two outcomes depending on the per-detector
/// [`crate::config::DualBranchConfig`] flag for the finding's detector.
///
/// ## Outcome A — flag off (default for all detectors today, plus all
/// non-InsecureTls security findings unconditionally)
///
/// **Demote, not suppress** the param-gated finding:
/// - `severity` drops to [`Severity::Low`].
/// - `confidence` is halved and capped at 0.4.
/// - A structured note is appended to `description`.
/// - Threshold metadata flag [`PARAM_GATED_METADATA_KEY`] is set to "true".
///
/// This preserves recall: a reviewer running `--severity-min low` still
/// sees the finding, while top-of-list precision (Critical/High counts)
/// improves. Same behavior as before Phase 2c.
///
/// ## Outcome B — flag on for `insecure-tls`, finding from `InsecureTlsDetector`
///
/// **Promote** the finding to dual-branch shape:
/// - **Param-gated case** (the AST says "library opt-out implementation"):
///   - Predicted: Benign / Info.
///   - Alternative: RealBug / original severity.
///   - `prediction_reasons` += `EnclosingScope { scope_kind: "param_gated_conditional", name: <param> }` with weight `+0.9`.
///   - If a `# repotoire: tls-disabled[<reason>]` annotation is present on
///     the finding's line or the immediately preceding line, also push
///     `ResolutionSignal::SourceAnnotation` — that's authoritative collapse.
/// - **Non-param-gated case** (the AST says top-level / unconditional):
///   - Predicted: RealBug / original severity.
///   - Alternative: Benign / Info.
///   - No `prediction_reasons` from this pass (the conservative tiebreak).
///   - If the annotation is present, the annotation still wins: predicted
///     flips to Benign / Info with the `SourceAnnotation` resolution.
///
/// The semantic-vs-typed split (why the param-gated AST signal is a
/// `PredictionReason` and not a `ResolutionSignal`) is documented in D5
/// of the Phase 2c decisions doc.
///
/// # Trade-off (Outcome A only — preserved from pre-Phase-2c behavior)
///
/// Demotion also demotes findings that ARE real bugs in libraries that
/// expose dangerous opt-outs (e.g. `if use_legacy: sha1(pwd)` inside a
/// password hasher). We accept this because:
/// 1. The Low finding is still emitted — recoverable via filter.
/// 2. The corresponding call site (the caller who passes the dangerous
///    value) is detected at full severity — reviewers see the actual
///    actionable site.
/// 3. The pre-fix behavior was Critical/High emission for the
///    *implementation line*, which routes maintainer attention to the
///    wrong place.
///
/// Outcome B solves this trade-off properly for InsecureTls by giving
/// the consumer both branches.
///
/// # Performance
///
/// Only files with ≥1 candidate security finding are parsed. On Click
/// that's ~16 files, on HTTPX ~18. With a warm
/// [`FileContentCache`] (populated by AST-using detectors during analyze),
/// the cost is essentially a memoized tree walk per finding (~µs).
///
/// # Return value
///
/// Returns the count of findings *demoted* (Outcome A applied). Findings
/// promoted to dual-branch shape (Outcome B) are NOT counted in this
/// total — they retain visible severity (the alternative branch carries
/// the would-be-demoted value). The return value drives the
/// `summary.security_downgraded` field, which is a "how many findings did
/// I hide from your top-of-list?" counter; dual-branch findings are not
/// hidden.
fn classify_param_gated_security_branches(
    findings: &mut [Finding],
    file_cache: Option<&Arc<FileContentCache>>,
    repo_path: &Path,
    dual_branch: &crate::config::DualBranchConfig,
) -> usize {
    use crate::detectors::security::{
        dual_branch_annotation, node_at_line, python_param_gated_branch_param_name,
    };
    use crate::parsers::lightweight::Language;

    // Use the supplied cache if present; otherwise allocate a local cache for
    // this pass only. Local cache means cold parse on every file with a
    // candidate finding, but only for the small set of files we actually
    // visit, never for the whole repo.
    let local_cache = Arc::new(FileContentCache::new());
    let cache: &Arc<FileContentCache> = file_cache.unwrap_or(&local_cache);

    // Per-detector flag check, once. Hoisted out of the inner loop because
    // the config is shared across all findings and the lookup is a
    // HashSet contains.
    let insecure_tls_flag_on = dual_branch.is_enabled_for("insecure-tls");

    // Resolve a finding's `affected_files` entry to an absolute path that
    // the FileContentCache can read. Findings carry repo-relative paths
    // (e.g. `httpx/_config.py`); we join against `repo_path`. Already-
    // absolute paths are returned as-is.
    let resolve = |p: &Path| -> PathBuf {
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            repo_path.join(p)
        }
    };

    // Group candidate finding indices by the resolved absolute file path so
    // a single parse covers every candidate finding in that file.
    //
    // Candidate set:
    // - Outcome A only path: any security finding at Critical/High/Medium,
    //   Python `.py`, with line_start. (Same as pre-Phase-2c.)
    // - Outcome B path: additionally, InsecureTls findings at *any*
    //   severity (Info/Low included) when the flag is on, because even an
    //   already-Low InsecureTls finding still benefits from dual-branch
    //   shape — the alternative branch carries the upgrade path.
    //
    // The cheap "skip already-Low" optimization is preserved for Outcome A
    // (saves parses on findings nothing would change), but we widen it
    // when Outcome B is in play for that detector.
    let mut by_file: HashMap<PathBuf, Vec<usize>> = HashMap::new();
    for (idx, f) in findings.iter().enumerate() {
        if !is_security_detector(&f.detector) {
            continue;
        }
        let is_insecure_tls = f.detector == "InsecureTlsDetector";
        let outcome_b_eligible = insecure_tls_flag_on && is_insecure_tls;

        if !outcome_b_eligible {
            // Outcome A path: only Critical/High/Medium are demotable
            // (the demotion target is Low).
            if !matches!(
                f.severity,
                Severity::Critical | Severity::High | Severity::Medium
            ) {
                continue;
            }
        }
        let Some(path) = f.affected_files.first() else {
            continue;
        };
        // Python-only for this batch. JS/TS/Go extensions are deliberately
        // out of scope (see design doc) — the predicate is Python-AST
        // specific.
        if path.extension().and_then(|e| e.to_str()) != Some("py") {
            continue;
        }
        if f.line_start.is_none() {
            continue;
        }
        by_file.entry(resolve(path)).or_default().push(idx);
    }

    let mut demoted = 0usize;
    let mut promoted = 0usize;
    for (path, finding_indices) in by_file {
        // Parse path is shared with the cache: warm hits are O(1) tree clone,
        // cold misses pay the parse once for the whole batch.
        let Some((source, tree)) = cache.get_or_parse(&path, Language::Python) else {
            continue;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();
        // Source line index: built lazily once per file because the
        // annotation lookup needs to read individual lines, not the whole
        // file. `source.lines()` is O(n) but we collect once.
        let source_lines: Vec<&str> = source.lines().collect();

        for idx in finding_indices {
            let line = match findings[idx].line_start {
                Some(l) => l,
                None => continue,
            };
            let Some(node) = node_at_line(root, line) else {
                continue;
            };
            let param_name = python_param_gated_branch_param_name(node, bytes);
            let is_param_gated = param_name.is_some();

            let is_insecure_tls = findings[idx].detector == "InsecureTlsDetector";
            let outcome_b = insecure_tls_flag_on && is_insecure_tls;

            // Annotation lookup: check the finding's own line and the
            // immediately preceding line for `# repotoire: tls-disabled[...]`.
            // Two-line window matches `# noqa`/`# type: ignore` ergonomics:
            // user can either put the annotation end-of-line or on the
            // line just above.
            //
            // We only do this lookup under Outcome B; the annotation has
            // no semantic under Outcome A (it doesn't suppress a demotion;
            // a demoted finding is the right severity already).
            let annotation = if outcome_b {
                let line_idx = (line as usize).saturating_sub(1);
                let candidates = [
                    source_lines.get(line_idx).copied(),
                    line_idx
                        .checked_sub(1)
                        .and_then(|i| source_lines.get(i).copied()),
                ];
                candidates
                    .into_iter()
                    .flatten()
                    .find_map(dual_branch_annotation::parse_python_comment)
                    .filter(|a| a.kind.eq_ignore_ascii_case("tls-disabled"))
            } else {
                None
            };

            if !outcome_b {
                // ── Outcome A: existing demotion behavior ──────────────
                if !is_param_gated {
                    continue;
                }
                let f = &mut findings[idx];
                f.severity = Severity::Low;
                let new_conf = (f.confidence.unwrap_or(0.7) * 0.5).min(0.4);
                f.confidence = Some(new_conf);
                f.description.push_str(PARAM_GATED_DEMOTION_NOTE);
                f.threshold_metadata
                    .insert(PARAM_GATED_METADATA_KEY.to_string(), "true".to_string());
                demoted += 1;
                continue;
            }

            // ── Outcome B: promote to dual-branch shape ────────────────
            //
            // Three sub-cases:
            //   B1. Annotation present → force-collapse Benign/Info,
            //       SourceAnnotation resolution signal.
            //   B2. Param-gated, no annotation → predicted Benign/Info,
            //       EnclosingScope prediction reason (+0.9 toward Benign).
            //   B3. Not param-gated, no annotation → predicted RealBug
            //       at original severity, no extra evidence.
            //
            // All three populate `alternative_branch`. B1 and B2 also
            // populate at least one signal; B3 is the pure
            // tiebreaker-conservative emission.
            let f = &mut findings[idx];
            let original_severity = f.severity;
            let original_title = f.title.clone();
            let original_description = f.description.clone();
            let original_suggested_fix = f.suggested_fix.clone();

            let (predicted_label, alt_label) = if annotation.is_some() || is_param_gated {
                (
                    crate::dual_branch::BranchLabel::Benign,
                    crate::dual_branch::BranchLabel::RealBug,
                )
            } else {
                (
                    crate::dual_branch::BranchLabel::RealBug,
                    crate::dual_branch::BranchLabel::Benign,
                )
            };

            let (predicted_severity, alt_severity) = match predicted_label {
                crate::dual_branch::BranchLabel::Benign => (Severity::Info, original_severity),
                crate::dual_branch::BranchLabel::RealBug => (original_severity, Severity::Info),
            };

            // Build the alternative branch's prose. We mirror the predicted
            // branch's prose by reusing the detector's already-rendered
            // title/description/suggested_fix for whichever side ends up
            // being the RealBug branch (the side the detector knows how to
            // describe), and synthesize the Benign-side prose here.
            let benign_title = "Caller-controlled TLS opt-out (likely benign)".to_string();
            let benign_description = format!(
                "**Dual-branch interpretation**\n\n\
                 The TLS-verification opt-out at this site is inside a \
                 parameter-gated conditional branch (the library is implementing \
                 a caller-controlled `verify=...` / `insecure=...` flag). The \
                 actionable security decision is at the call sites that pass \
                 the dangerous value to this function, not at this implementation.\n\n\
                 The {alt_label_str} interpretation is carried in \
                 `alternative_branch` so consumers wanting the conservative \
                 view can still see the underlying issue.",
                alt_label_str = match alt_label {
                    crate::dual_branch::BranchLabel::RealBug => "stricter RealBug",
                    crate::dual_branch::BranchLabel::Benign => "Benign",
                },
            );
            let benign_suggested_fix = Some(
                "If this is intentional opt-out plumbing, no fix is needed at \
                 this site — review the call sites instead. To collapse this \
                 finding definitively, annotate the line with \
                 `# repotoire: tls-disabled[<reason>]`."
                    .to_string(),
            );

            // Assign predicted (primary) fields.
            f.severity = predicted_severity;
            match predicted_label {
                crate::dual_branch::BranchLabel::Benign => {
                    f.title = benign_title.clone();
                    f.description = benign_description.clone();
                    f.suggested_fix = benign_suggested_fix.clone();
                }
                crate::dual_branch::BranchLabel::RealBug => {
                    // Predicted RealBug: leave original prose in place
                    // (the detector already wrote it).
                    let _ = (
                        &original_title,
                        &original_description,
                        &original_suggested_fix,
                    );
                }
            }

            // Build the alternative branch using whichever side wasn't
            // chosen as predicted.
            let (alt_title, alt_description, alt_fix) = match alt_label {
                crate::dual_branch::BranchLabel::Benign => {
                    (benign_title, benign_description, benign_suggested_fix)
                }
                crate::dual_branch::BranchLabel::RealBug => (
                    original_title.clone(),
                    original_description.clone(),
                    original_suggested_fix.clone(),
                ),
            };
            f.alternative_branch = Some(crate::dual_branch::AlternativeBranch {
                label: alt_label,
                severity: alt_severity,
                title: alt_title,
                description: alt_description,
                suggested_fix: alt_fix,
            });

            // Evidence: EnclosingScope reason for the param-gated case.
            if let Some(param) = param_name.as_ref() {
                f.prediction_reasons
                    .push(crate::dual_branch::PredictionReason {
                        kind: crate::dual_branch::PredictionReasonKind::EnclosingScope {
                            scope_kind: "param_gated_conditional".to_string(),
                            name: param.clone(),
                        },
                        weight: 0.9,
                        note: format!(
                            "The TLS opt-out is inside a conditional branch gated by the \
                             enclosing function's `{param}` parameter; the actionable \
                             site is the caller passing the dangerous value."
                        ),
                    });
            }

            // Resolution signal: the annotation, if present.
            if let Some(ann) = annotation {
                let args_str = if ann.args.is_empty() {
                    String::new()
                } else {
                    format!("[{}]", ann.args.join(","))
                };
                f.resolution_signals
                    .push(crate::dual_branch::ResolutionSignal {
                        kind: crate::dual_branch::ResolutionKind::SourceAnnotation {
                            syntax: format!("# repotoire: tls-disabled{args_str}"),
                        },
                        description: "Source-level annotation forces the Benign \
                                      interpretation; remove the annotation to \
                                      surface the underlying TLS opt-out finding."
                            .to_string(),
                        example: Some(
                            "session.verify = False  # repotoire: tls-disabled[trusted-dev-cert]"
                                .to_string(),
                        ),
                        collapses_to: crate::dual_branch::BranchLabel::Benign,
                    });
            }

            promoted += 1;
        }
    }

    if demoted > 0 {
        tracing::info!(
            "Demoted {} security findings inside parameter-gated conditional branches",
            demoted
        );
    }
    if promoted > 0 {
        tracing::info!(
            "Promoted {} InsecureTls findings to dual-branch shape",
            promoted
        );
    }

    demoted
}

/// Rank findings by actionability score (0-100).
///
/// Uses the heuristic classifier to score findings. Sorted in descending order
/// so the most actionable findings appear first.
pub(crate) fn rank_findings(findings: &mut Vec<Finding>, _graph: &dyn crate::graph::GraphQuery) {
    let extractor = crate::classifier::FeatureExtractor::new();
    let classifier = crate::classifier::HeuristicClassifier;
    let mut scored: Vec<(f32, usize)> = findings
        .iter()
        .enumerate()
        .map(|(i, f)| {
            let features = extractor.extract(f);
            (classifier.score(&features), i)
        })
        .collect();
    scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
    let reordered: Vec<Finding> = scored
        .into_iter()
        .map(|(_, i)| findings[i].clone())
        .collect();
    *findings = reordered;
}

/// FP filtering with category-aware thresholds.
///
/// Uses the heuristic classifier with per-category filter thresholds:
/// - Security: conservative (0.35) — don't miss real vulnerabilities
/// - Code Quality: aggressive (0.52) — filter noisy complexity warnings
/// - ML/AI: moderate (0.45) — domain-specific accuracy
fn filter_false_positives(
    findings: &mut Vec<Finding>,
    _graph: &dyn crate::graph::GraphQuery,
    bypass_set: &HashSet<String>,
) {
    use crate::classifier::{
        model::HeuristicClassifier, CategoryThresholds, DetectorCategory, FeatureExtractor,
    };

    let thresholds = CategoryThresholds::default();
    let extractor = FeatureExtractor::new();
    let classifier = HeuristicClassifier;

    let before_count = findings.len();
    let mut filtered_by_category: std::collections::HashMap<DetectorCategory, usize> =
        std::collections::HashMap::new();

    findings.retain(|f| {
        if f.deterministic || bypass_set.contains(&f.detector) {
            return true;
        }

        let features = extractor.extract(f);
        let tp_prob = classifier.score(&features);
        let category = DetectorCategory::from_detector(&f.detector);
        let config = thresholds.get_category(category);

        if tp_prob >= config.filter_threshold {
            true
        } else {
            *filtered_by_category.entry(category).or_insert(0) += 1;
            false
        }
    });

    let total_filtered = before_count - findings.len();
    if total_filtered > 0 {
        tracing::info!(
            "FP classifier filtered {} findings (Security: {}, Quality: {}, ML: {}, Perf: {}, Other: {})",
            total_filtered,
            filtered_by_category.get(&DetectorCategory::Security).unwrap_or(&0),
            filtered_by_category.get(&DetectorCategory::CodeQuality).unwrap_or(&0),
            filtered_by_category.get(&DetectorCategory::MachineLearning).unwrap_or(&0),
            filtered_by_category.get(&DetectorCategory::Performance).unwrap_or(&0),
            filtered_by_category.get(&DetectorCategory::Other).unwrap_or(&0),
        );
    }
}

/// Filter out findings from files that have `repotoire:ignore-file` in the first 10 lines.
///
/// Reads the first 10 lines of each unique affected file. Files that contain
/// the directive are fully suppressed. Caches file content (not the suppressed
/// verdict) so per-finding detector targeting still works without re-reading.
fn filter_file_level_suppressed(findings: &mut Vec<Finding>) {
    use std::collections::HashMap;

    // Cache file content (Option<String>) so we read each file at most once.
    // We can't cache the boolean verdict because it depends on the finding's
    // detector when the file uses a targeted bracket like
    // `repotoire:ignore-file[insecure-crypto]`.
    let mut content_cache: HashMap<PathBuf, Option<String>> = HashMap::new();

    let before = findings.len();
    findings.retain(|f| {
        for path in &f.affected_files {
            let content = content_cache
                .entry(path.clone())
                .or_insert_with(|| std::fs::read_to_string(path).ok());
            if let Some(c) = content.as_deref() {
                if crate::detectors::is_file_suppressed_for(c, Some(&f.detector)) {
                    return false;
                }
            }
        }
        true
    });

    let removed = before - findings.len();
    if removed > 0 {
        tracing::debug!("File-level suppression filtered {} findings", removed);
    }
}

/// Filter findings where the affected line has an inline `repotoire:ignore` comment.
///
/// This is the postprocessor-level suppression check that catches comments for
/// GraphWide detectors (mutual-recursion, infinite-loop, etc.) which don't read
/// file content themselves. Checks both the finding's line and the previous line
/// for suppression comments, with optional targeted detector matching.
fn filter_inline_suppressed(findings: &mut Vec<Finding>) {
    use std::collections::HashMap;

    // Cache file contents to avoid re-reading
    let mut file_cache: HashMap<PathBuf, Vec<String>> = HashMap::new();

    let before = findings.len();
    findings.retain(|f| {
        let line_start = match f.line_start {
            Some(l) if l > 0 => l as usize,
            _ => return true, // No line info — keep
        };

        for path in &f.affected_files {
            let lines = file_cache.entry(path.clone()).or_insert_with(|| {
                std::fs::read_to_string(path)
                    .map(|c| c.lines().map(String::from).collect())
                    .unwrap_or_default()
            });

            if lines.is_empty() {
                continue;
            }

            // Scan a window around line_start: 3 lines before through 3 lines after.
            // This handles suppression comments placed before doc comments, on the
            // function signature, or between decorators/attributes and the definition.
            let line_idx = line_start.saturating_sub(1); // 0-indexed
            let scan_start = line_idx.saturating_sub(3);
            let scan_end = (line_idx + 3).min(lines.len().saturating_sub(1));

            for i in scan_start..=scan_end {
                let line = lines.get(i).map(|s| s.as_str()).unwrap_or("");
                let prev = if i > 0 {
                    lines.get(i - 1).map(|s| s.as_str())
                } else {
                    None
                };
                if crate::detectors::is_line_suppressed_for(line, prev, &f.detector) {
                    return false; // Suppressed
                }
            }
        }
        true
    });

    let removed = before - findings.len();
    if removed > 0 {
        tracing::debug!("Inline suppression filtered {} findings", removed);
    }
}

/// Deduplicate findings with identical detector, title, file, and line_start.
fn deduplicate_findings(findings: &mut Vec<Finding>) {
    use std::collections::HashSet;
    let before = findings.len();
    let mut seen = HashSet::new();
    findings.retain(|f| {
        let file = f
            .affected_files
            .first()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let key = (f.detector.clone(), f.title.clone(), file, f.line_start);
        seen.insert(key)
    });
    let removed = before - findings.len();
    if removed > 0 {
        tracing::debug!("Deduplicated {} findings", removed);
    }
}

/// Auto-suppress findings from detector test fixture files.
///
/// When a detector reports a finding in its OWN test infrastructure, the finding
/// is suppressed. This prevents false positives like the SQL injection detector
/// flagging patterns in `sql_injection/tests.rs` or `taint/mod.rs`.
///
/// Matching logic:
/// - The file path must contain `/detectors/` or `/tests/`
/// - The detector name (converted from PascalCase to snake_case components) must
///   appear as a path segment in the file path
///
/// For example, `SQLInjectionDetector` matches paths containing `sql_injection/`.
fn filter_detector_test_fixtures(findings: &mut Vec<Finding>) {
    let before = findings.len();
    findings.retain(|f| !is_detector_test_fixture(&f.detector, &f.affected_files));

    let removed = before - findings.len();
    if removed > 0 {
        tracing::debug!(
            "Auto-suppressed {} findings from detector test fixtures",
            removed
        );
    }
}

/// Check if a finding is from a detector's own test fixture.
///
/// Returns `true` if the affected file is part of the detector's own test
/// infrastructure, meaning the finding is a false positive from self-analysis.
fn is_detector_test_fixture(detector_name: &str, affected_files: &[PathBuf]) -> bool {
    // Convert PascalCase detector name to snake_case path segment.
    // E.g., "SQLInjectionDetector" -> "sql_injection"
    let slug = detector_name_to_path_slug(detector_name);

    for path in affected_files {
        let path_str = path.to_string_lossy();

        // Must be inside a detectors/ or tests/ directory
        let in_detector_dir =
            path_str.contains("/detectors/") || path_str.contains("\\detectors\\");
        let in_tests_dir = path_str.contains("/tests/") || path_str.contains("\\tests\\");

        if !in_detector_dir && !in_tests_dir {
            continue;
        }

        // Check if the detector's slug appears as a path component or file name
        // E.g., for slug "sql_injection", match paths like:
        //   src/detectors/sql_injection/tests.rs
        //   src/detectors/sql_injection/mod.rs
        //   src/detectors/sql_injection/patterns.rs
        if path_str.contains(&format!("/{}/", &slug))
            || path_str.contains(&format!("\\{}\\", &slug))
            || path_str.contains(&format!("/{}.rs", &slug))
            || path_str.contains(&format!("\\{}.rs", &slug))
        {
            return true;
        }

        // Also match the taint module for security detectors that use taint analysis
        // The taint module contains test fixtures for multiple security detectors
        if is_security_detector(detector_name)
            && (path_str.contains("/taint/")
                || path_str.contains("\\taint\\")
                || path_str.contains("/taint.rs")
                || path_str.contains("\\taint.rs"))
        {
            return true;
        }
    }

    false
}

/// Convert a PascalCase detector name to a snake_case path slug.
///
/// Examples:
/// - `"SQLInjectionDetector"` -> `"sql_injection"`
/// - `"XssDetector"` -> `"xss"`
/// - `"CommandInjectionDetector"` -> `"command_injection"`
/// - `"GodClassDetector"` -> `"god_class"`
fn detector_name_to_path_slug(name: &str) -> String {
    // Strip "Detector" suffix
    let name = name.strip_suffix("Detector").unwrap_or(name);

    let mut slug = String::with_capacity(name.len() + 4);
    let chars: Vec<char> = name.chars().collect();

    for (i, &ch) in chars.iter().enumerate() {
        if ch.is_uppercase() {
            // Insert underscore before uppercase if:
            // - Not the first character
            // - Previous char was lowercase (camelCase boundary)
            // - OR next char is lowercase and previous was uppercase (end of acronym like "SQL")
            if i > 0 {
                let prev_upper = chars[i - 1].is_uppercase();
                let next_lower = chars.get(i + 1).is_some_and(|c| c.is_lowercase());

                if !prev_upper || next_lower {
                    slug.push('_');
                }
            }
            slug.push(
                ch.to_lowercase()
                    .next()
                    .expect("to_lowercase always yields at least one char"),
            );
        } else {
            slug.push(ch);
        }
    }

    slug
}

/// Filter findings below a minimum confidence threshold.
///
/// If `show_all` is true, the filter is bypassed entirely.
/// If `min_confidence` is `None`, no filtering is applied.
/// The threshold is clamped to [0.0, 1.0].
pub(crate) fn filter_by_min_confidence(
    findings: &mut Vec<Finding>,
    min_confidence: Option<f64>,
    show_all: bool,
) {
    if show_all {
        return;
    }
    let Some(threshold) = min_confidence else {
        return;
    };
    let threshold = threshold.clamp(0.0, 1.0);
    let before = findings.len();
    findings.retain(|f| f.effective_confidence() >= threshold);
    let removed = before - findings.len();
    if removed > 0 {
        tracing::debug!(
            "Confidence filter (threshold={:.2}): removed {} findings below threshold",
            threshold,
            removed,
        );
    }
}

/// Check if a detector name is a security-related detector.
fn is_security_detector(name: &str) -> bool {
    const SECURITY_DETECTORS: &[&str] = &[
        "SQLInjectionDetector",
        "CommandInjectionDetector",
        "XssDetector",
        "SsrfDetector",
        "PathTraversalDetector",
        "LogInjectionDetector",
        "EvalDetector",
        "InsecureRandomDetector",
        "HardcodedCredentialsDetector",
        "CleartextCredentialsDetector",
        "NosqlInjectionDetector",
        "XxeDetector",
        "PrototypePollutionDetector",
        "InsecureCryptoDetector",
        "InsecureTlsDetector",
        "JwtWeakDetector",
        "CorsMisconfigDetector",
        "SecretDetector",
        "InsecureCookieDetector",
        "InsecureDeserializeDetector",
    ];
    SECURITY_DETECTORS.contains(&name)
}

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

    // ── detector_name_to_path_slug ───────────────────────────────────

    #[test]
    fn test_slug_sql_injection() {
        assert_eq!(
            detector_name_to_path_slug("SQLInjectionDetector"),
            "sql_injection"
        );
    }

    #[test]
    fn test_slug_xss() {
        assert_eq!(detector_name_to_path_slug("XssDetector"), "xss");
    }

    #[test]
    fn test_slug_command_injection() {
        assert_eq!(
            detector_name_to_path_slug("CommandInjectionDetector"),
            "command_injection"
        );
    }

    #[test]
    fn test_slug_god_class() {
        assert_eq!(detector_name_to_path_slug("GodClassDetector"), "god_class");
    }

    #[test]
    fn test_slug_ssrf() {
        assert_eq!(detector_name_to_path_slug("SsrfDetector"), "ssrf");
    }

    #[test]
    fn test_slug_n_plus_one() {
        assert_eq!(detector_name_to_path_slug("NPlusOneDetector"), "n_plus_one");
    }

    #[test]
    fn test_slug_ai_boilerplate() {
        assert_eq!(
            detector_name_to_path_slug("AIBoilerplateDetector"),
            "ai_boilerplate"
        );
    }

    // ── is_detector_test_fixture ─────────────────────────────────────

    #[test]
    fn test_fixture_match_sql_injection_tests() {
        let files = vec![PathBuf::from("src/detectors/sql_injection/tests.rs")];
        assert!(is_detector_test_fixture("SQLInjectionDetector", &files));
    }

    #[test]
    fn test_fixture_match_sql_injection_mod() {
        let files = vec![PathBuf::from("src/detectors/sql_injection/mod.rs")];
        assert!(is_detector_test_fixture("SQLInjectionDetector", &files));
    }

    #[test]
    fn test_fixture_match_taint_for_security() {
        let files = vec![PathBuf::from("src/detectors/taint/mod.rs")];
        assert!(is_detector_test_fixture("SQLInjectionDetector", &files));
    }

    #[test]
    fn test_fixture_no_match_different_detector() {
        // XSS detector should NOT match sql_injection directory
        let files = vec![PathBuf::from("src/detectors/sql_injection/tests.rs")];
        assert!(!is_detector_test_fixture("XssDetector", &files));
    }

    #[test]
    fn test_fixture_no_match_regular_source() {
        // Regular source file should NOT be suppressed
        let files = vec![PathBuf::from("src/main.rs")];
        assert!(!is_detector_test_fixture("SQLInjectionDetector", &files));
    }

    #[test]
    fn test_fixture_no_match_user_code() {
        // User code in a tests/ directory should NOT match unless detector name matches
        let files = vec![PathBuf::from("tests/integration_test.rs")];
        assert!(!is_detector_test_fixture("SQLInjectionDetector", &files));
    }

    #[test]
    fn test_fixture_match_god_class_file() {
        let files = vec![PathBuf::from("src/detectors/god_class.rs")];
        assert!(is_detector_test_fixture("GodClassDetector", &files));
    }

    #[test]
    fn test_fixture_taint_not_matched_for_non_security() {
        // Taint module should NOT be auto-suppressed for non-security detectors
        let files = vec![PathBuf::from("src/detectors/taint/mod.rs")];
        assert!(!is_detector_test_fixture("GodClassDetector", &files));
    }

    #[test]
    fn test_is_security_detector() {
        assert!(is_security_detector("SQLInjectionDetector"));
        assert!(is_security_detector("XssDetector"));
        assert!(is_security_detector("CommandInjectionDetector"));
        assert!(!is_security_detector("GodClassDetector"));
        assert!(!is_security_detector("DeadCodeDetector"));
    }

    // ── assign_default_confidence ──────────────────────────────────

    #[test]
    fn test_assign_default_confidence_sets_architecture() {
        let mut findings = vec![Finding {
            category: Some("architecture".into()),
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.85));
    }

    #[test]
    fn test_assign_default_confidence_sets_security() {
        let mut findings = vec![Finding {
            category: Some("security".into()),
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.75));
    }

    #[test]
    fn test_assign_default_confidence_sets_design() {
        let mut findings = vec![Finding {
            category: Some("design".into()),
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.65));
    }

    #[test]
    fn test_assign_default_confidence_sets_dead_code() {
        let mut findings = vec![
            Finding {
                category: Some("dead-code".into()),
                confidence: None,
                ..Default::default()
            },
            Finding {
                category: Some("dead_code".into()),
                confidence: None,
                ..Default::default()
            },
        ];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.70));
        assert_eq!(findings[1].confidence, Some(0.70));
    }

    #[test]
    fn test_assign_default_confidence_sets_ai_watchdog() {
        let mut findings = vec![Finding {
            category: Some("ai_watchdog".into()),
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.60));
    }

    #[test]
    fn test_assign_default_confidence_sets_unknown_category() {
        let mut findings = vec![Finding {
            category: Some("testing".into()),
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.70));
    }

    #[test]
    fn test_assign_default_confidence_sets_none_category() {
        let mut findings = vec![Finding {
            category: None,
            confidence: None,
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.70));
    }

    #[test]
    fn test_assign_default_confidence_does_not_overwrite_existing() {
        let mut findings = vec![Finding {
            category: Some("architecture".into()),
            confidence: Some(0.42),
            ..Default::default()
        }];
        assign_default_confidence(&mut findings);
        // Must preserve the detector-set confidence, NOT overwrite with 0.85
        assert_eq!(findings[0].confidence, Some(0.42));
    }

    #[test]
    fn test_assign_default_confidence_mixed_findings() {
        let mut findings = vec![
            Finding {
                category: Some("security".into()),
                confidence: Some(0.99),
                ..Default::default()
            },
            Finding {
                category: Some("architecture".into()),
                confidence: None,
                ..Default::default()
            },
            Finding {
                category: None,
                confidence: None,
                ..Default::default()
            },
        ];
        assign_default_confidence(&mut findings);
        assert_eq!(findings[0].confidence, Some(0.99)); // preserved
        assert_eq!(findings[1].confidence, Some(0.85)); // architecture default
        assert_eq!(findings[2].confidence, Some(0.70)); // fallback default
    }

    // ── filter_by_min_confidence ────────────────────────────────────

    #[test]
    fn test_min_confidence_filters_below_threshold() {
        let mut findings = vec![
            Finding {
                confidence: Some(0.9),
                ..Default::default()
            },
            Finding {
                confidence: Some(0.5),
                ..Default::default()
            },
            Finding {
                confidence: Some(0.7),
                ..Default::default()
            },
        ];
        filter_by_min_confidence(&mut findings, Some(0.6), false);
        assert_eq!(findings.len(), 2);
        assert_eq!(findings[0].confidence, Some(0.9));
        assert_eq!(findings[1].confidence, Some(0.7));
    }

    #[test]
    fn test_min_confidence_none_does_not_filter() {
        let mut findings = vec![
            Finding {
                confidence: Some(0.1),
                ..Default::default()
            },
            Finding {
                confidence: Some(0.9),
                ..Default::default()
            },
        ];
        filter_by_min_confidence(&mut findings, None, false);
        assert_eq!(findings.len(), 2);
    }

    #[test]
    fn test_min_confidence_show_all_bypasses_filter() {
        let mut findings = vec![
            Finding {
                confidence: Some(0.1),
                ..Default::default()
            },
            Finding {
                confidence: Some(0.2),
                ..Default::default()
            },
        ];
        filter_by_min_confidence(&mut findings, Some(0.99), true);
        assert_eq!(findings.len(), 2); // nothing removed
    }

    #[test]
    fn test_min_confidence_exact_threshold_kept() {
        let mut findings = vec![Finding {
            confidence: Some(0.7),
            ..Default::default()
        }];
        filter_by_min_confidence(&mut findings, Some(0.7), false);
        assert_eq!(findings.len(), 1); // exactly at threshold is kept
    }

    #[test]
    fn test_min_confidence_clamps_above_one() {
        let mut findings = vec![Finding {
            confidence: Some(0.99),
            ..Default::default()
        }];
        // Threshold > 1.0 should be clamped to 1.0, filtering everything below 1.0
        filter_by_min_confidence(&mut findings, Some(1.5), false);
        assert_eq!(findings.len(), 0);
    }

    #[test]
    fn test_min_confidence_clamps_below_zero() {
        let mut findings = vec![Finding {
            confidence: Some(0.01),
            ..Default::default()
        }];
        // Threshold < 0.0 should be clamped to 0.0, keeping everything
        filter_by_min_confidence(&mut findings, Some(-0.5), false);
        assert_eq!(findings.len(), 1);
    }

    #[test]
    fn test_min_confidence_uses_effective_confidence_for_none() {
        // Finding with confidence=None should use effective_confidence() which is 0.70
        let mut findings = vec![Finding {
            confidence: None,
            ..Default::default()
        }];
        // 0.70 (effective default) >= 0.5 threshold => kept
        filter_by_min_confidence(&mut findings, Some(0.5), false);
        assert_eq!(findings.len(), 1);

        // 0.70 (effective default) < 0.8 threshold => removed
        filter_by_min_confidence(&mut findings, Some(0.8), false);
        assert_eq!(findings.len(), 0);
    }
}

#[cfg(test)]
mod label_tests {
    use super::*;
    use crate::models::{Finding, Severity};
    use std::collections::HashMap;

    fn make_finding(id: &str, detector: &str) -> Finding {
        Finding {
            id: id.into(),
            detector: detector.into(),
            severity: Severity::Medium,
            title: format!("Finding {}", id),
            ..Default::default()
        }
    }

    #[test]
    fn test_fp_label_removes_finding() {
        let mut findings = vec![make_finding("aaa", "Det1"), make_finding("bbb", "Det2")];
        let labels = HashMap::from([("aaa".to_string(), false)]);

        apply_labels_to_findings(&mut findings, &labels, false);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].id, "bbb");
    }

    #[test]
    fn test_fp_label_show_all_reinserts_with_low_confidence() {
        let mut findings = vec![make_finding("aaa", "Det1"), make_finding("bbb", "Det2")];
        let labels = HashMap::from([("aaa".to_string(), false)]);

        apply_labels_to_findings(&mut findings, &labels, true);

        assert_eq!(findings.len(), 2, "show_all should keep FP finding");
        let fp = findings
            .iter()
            .find(|f| f.id == "aaa")
            .expect("FP finding should exist");
        assert_eq!(fp.confidence, Some(0.05));
        assert_eq!(
            fp.threshold_metadata.get("user_label").map(|s| s.as_str()),
            Some("false_positive")
        );
    }

    #[test]
    fn test_tp_label_pins_finding() {
        let mut findings = vec![make_finding("aaa", "Det1")];
        let labels = HashMap::from([("aaa".to_string(), true)]);

        apply_labels_to_findings(&mut findings, &labels, false);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].confidence, Some(0.95));
        assert!(findings[0].deterministic);
        assert_eq!(
            findings[0]
                .threshold_metadata
                .get("user_label")
                .map(|s| s.as_str()),
            Some("true_positive")
        );
    }

    #[test]
    fn test_unlabeled_findings_unchanged() {
        let mut findings = vec![make_finding("aaa", "Det1")];
        let labels = HashMap::from([("zzz".to_string(), false)]); // no match

        apply_labels_to_findings(&mut findings, &labels, false);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].id, "aaa");
        assert!(findings[0].confidence.is_none()); // unchanged
    }

    #[test]
    fn test_empty_labels_is_noop() {
        let mut findings = vec![make_finding("aaa", "Det1")];
        let labels = HashMap::new();

        apply_labels_to_findings(&mut findings, &labels, false);

        assert_eq!(findings.len(), 1);
    }
}

// ─── classify_param_gated_security_branches integration tests ─────────────────
//
// These exercise the full pass end-to-end against synthesized Python files
// on disk. They verify the universal (not detector-specific) shape: the
// same demotion logic applies to any security detector.
//
// Trade-off acknowledged in `test_demote_applies_to_crypto_findings` and
// `test_demote_applies_to_subprocess_findings`: a real bug in a library
// that exposes a dangerous opt-out is also demoted to Low. That's the
// deliberate cost of universality (see function-level doc).

#[cfg(test)]
mod demote_param_gated_tests {
    use super::*;
    use std::path::PathBuf;

    /// Build a security finding pointing at `path:line` with the given
    /// detector + severity.
    fn finding_at(detector: &str, severity: Severity, path: &Path, line: u32) -> Finding {
        Finding {
            detector: detector.to_string(),
            severity,
            title: format!("{} test finding", detector),
            description: "Original description.".to_string(),
            affected_files: vec![path.to_path_buf()],
            line_start: Some(line),
            line_end: Some(line),
            confidence: Some(0.95),
            category: Some("security".to_string()),
            ..Default::default()
        }
    }

    /// Write `src` to a temp .py file and return the path. The tempdir is
    /// returned so the caller can keep it alive for the lifetime of the test.
    fn write_py(src: &str) -> (tempfile::TempDir, PathBuf) {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.py");
        std::fs::write(&path, src).unwrap();
        (tmp, path)
    }

    #[test]
    fn test_demote_httpx_style_verify_false_branch() {
        // Mirror HTTPX `_config.py` shape exactly: `verify` parameter,
        // elif gate referencing it, CERT_NONE in body. Originally Critical;
        // postprocess should drop it to Low and append the note.
        let src = "def create_ssl_context(verify, trust_env):\n\
                   \x20   if verify is True:\n\
                   \x20       ctx = ssl.create_default_context()\n\
                   \x20   elif verify is False:\n\
                   \x20       ctx = ssl.SSLContext()\n\
                   \x20       ctx.check_hostname = False\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            7,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 1);
        assert_eq!(findings[0].severity, Severity::Low);
        assert!(findings[0].confidence.unwrap() <= 0.4);
        assert!(findings[0].description.contains("parameter-gated"));
        assert_eq!(
            findings[0].threshold_metadata.get(PARAM_GATED_METADATA_KEY),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_dont_demote_module_level_cert_none() {
        // Module-level: no enclosing function. Should stay Critical.
        let src = "import ssl\nctx = ssl.SSLContext()\nctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 0);
        assert_eq!(findings[0].severity, Severity::Critical);
    }

    #[test]
    fn test_dont_demote_global_gated_branch() {
        // Condition references `is_production()`, not a parameter. Stays
        // Critical: the function isn't implementing a caller-controlled
        // opt-out, it's gating on environment.
        let src = "def configure(other_arg):\n\
                   \x20   if not is_production():\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 0);
        assert_eq!(findings[0].severity, Severity::Critical);
    }

    #[test]
    fn test_demote_applies_to_crypto_findings() {
        // TRADE-OFF TEST: This is technically a real bug in a password
        // hasher library — exposing a `use_legacy` opt-out for SHA-1 is
        // dangerous. But our universal predicate demotes it to Low because
        // it's structurally indistinguishable from HTTPX's `verify=False`.
        // Acceptable: (a) reviewers can find via --severity-min low,
        // (b) call sites passing use_legacy=True are themselves flagged
        // at full severity by the same detector.
        let src = "def hash_password(pwd, use_legacy):\n\
                   \x20   if use_legacy:\n\
                   \x20       return hashlib.sha1(pwd).hexdigest()\n\
                   \x20   return hashlib.sha256(pwd).hexdigest()\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "InsecureCryptoDetector",
            Severity::High,
            &path,
            3,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 1);
        assert_eq!(findings[0].severity, Severity::Low);
    }

    #[test]
    fn test_demote_applies_to_subprocess_findings() {
        // Universal applicability — works for command_injection too,
        // without any detector-specific code.
        let src = "def run(cmd, shell_mode):\n\
                   \x20   if shell_mode:\n\
                   \x20       subprocess.run(cmd, shell=True)\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "CommandInjectionDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 1);
        assert_eq!(findings[0].severity, Severity::Low);
    }

    #[test]
    fn test_else_branch_of_param_gated_if_demoted() {
        // The else clause is gated by the inverse of the if's condition,
        // which references `verify`. Treated as param-gated.
        let src = "def f(verify):\n\
                   \x20   if verify:\n\
                   \x20       a = 1\n\
                   \x20   else:\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            5,
        )];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 1);
        assert_eq!(findings[0].severity, Severity::Low);
    }

    #[test]
    fn test_non_security_detector_left_alone() {
        // A non-security detector firing inside the same shape should not
        // be touched — the predicate only applies to the security category.
        let src = "def f(verify):\n\
                   \x20   if verify is False:\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at("GodClassDetector", Severity::High, &path, 3)];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 0);
        assert_eq!(findings[0].severity, Severity::High);
    }

    #[test]
    fn test_low_severity_is_skipped() {
        // Already Low: no work to do; the pass should not redundantly
        // append the note or churn metadata.
        let src = "def f(verify):\n\
                   \x20   if verify is False:\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let mut findings = vec![finding_at("InsecureTlsDetector", Severity::Low, &path, 3)];
        let n = classify_param_gated_security_branches(
            &mut findings,
            None,
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n, 0);
        assert!(!findings[0].description.contains("parameter-gated"));
    }

    #[test]
    fn test_warm_cache_is_reused() {
        // When a shared cache is supplied, the parse is reused on a second
        // invocation. We can't observe parse counts directly, but we can
        // assert that calling twice with the same cache leaves the tree
        // count at exactly 1 entry per file.
        let src = "def f(verify):\n\
                   \x20   if verify is False:\n\
                   \x20       ctx.verify_mode = ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);

        let cache = Arc::new(FileContentCache::new());
        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let n1 = classify_param_gated_security_branches(
            &mut findings,
            Some(&cache),
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(n1, 1);
        assert_eq!(cache.tree_count(), 1);

        // Second invocation, fresh finding (so the demote can fire again),
        // must not create a second tree entry.
        let mut findings2 = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let _ = classify_param_gated_security_branches(
            &mut findings2,
            Some(&cache),
            Path::new("/"),
            &crate::config::DualBranchConfig::default(),
        );
        assert_eq!(cache.tree_count(), 1);
    }

    // ─── Outcome B (dual-branch promotion) tests ─────────────────────────
    //
    // These exercise the Phase 2c path: when `dual_branch.is_enabled_for("insecure-tls")`
    // is true, InsecureTls findings are promoted to dual-branch shape
    // instead of being demoted. Four sub-cases pin the matrix from the
    // decisions doc (D5 + Validation plan):
    //
    //   B1.  Param-gated, no annotation → Benign/Info primary, RealBug/<orig>
    //        alternative, EnclosingScope prediction reason.
    //   B2.  Not param-gated, no annotation → RealBug/<orig> primary,
    //        Benign/Info alternative, no extra evidence.
    //   B3.  Param-gated, annotation present → Benign/Info primary,
    //        SourceAnnotation resolution signal.
    //   B4.  Not param-gated, annotation present → annotation wins,
    //        Benign/Info primary, SourceAnnotation resolution signal.
    //
    // Plus a scope guard: flag off → no dual-branch shape applied, same
    // demotion behavior as pre-Phase-2c.

    /// Build a `DualBranchConfig` with `insecure-tls` enabled. Master
    /// switch on, single detector opt-in.
    fn dual_branch_insecure_tls_on() -> crate::config::DualBranchConfig {
        let mut cfg = crate::config::DualBranchConfig {
            enabled: true,
            detectors: HashMap::new(),
        };
        cfg.detectors.insert("insecure-tls".to_string(), true);
        cfg
    }

    #[test]
    fn b1_param_gated_no_annotation_promotes_to_benign_primary() {
        let src = "def configure(verify):\n\
                   \x20   if not verify:\n\
                   \x20       ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at("InsecureTlsDetector", Severity::High, &path, 3)];
        let cfg = dual_branch_insecure_tls_on();
        let demoted =
            classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        assert_eq!(demoted, 0, "Outcome B does not count toward demoted total");
        let f = &findings[0];
        assert_eq!(f.severity, Severity::Info, "predicted Benign → Info");
        let alt = f
            .alternative_branch
            .as_ref()
            .expect("alternative_branch set");
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
        assert_eq!(
            alt.severity,
            Severity::High,
            "alternative carries orig severity"
        );
        // EnclosingScope prediction reason with the captured param name.
        let scopes: Vec<_> = f
            .prediction_reasons
            .iter()
            .filter_map(|r| match &r.kind {
                crate::dual_branch::PredictionReasonKind::EnclosingScope { scope_kind, name } => {
                    Some((scope_kind.as_str(), name.as_str()))
                }
                _ => None,
            })
            .collect();
        assert_eq!(scopes, vec![("param_gated_conditional", "verify")]);
        // No resolution signal (no annotation present).
        assert!(f.resolution_signals.is_empty());
    }

    #[test]
    fn b2_not_param_gated_no_annotation_keeps_realbug_primary() {
        // Top-level (no enclosing function), so not param-gated.
        let src = "import ssl\n\
                   ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at("InsecureTlsDetector", Severity::High, &path, 2)];
        let cfg = dual_branch_insecure_tls_on();
        let demoted =
            classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        assert_eq!(demoted, 0);
        let f = &findings[0];
        assert_eq!(
            f.severity,
            Severity::High,
            "predicted RealBug keeps orig severity"
        );
        let alt = f
            .alternative_branch
            .as_ref()
            .expect("alternative_branch set");
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
        assert_eq!(alt.severity, Severity::Info);
        // No prediction reasons (the conservative tiebreak emits none).
        assert!(
            f.prediction_reasons.is_empty(),
            "B3 case is the pure tiebreaker-conservative emission"
        );
        assert!(f.resolution_signals.is_empty());
    }

    #[test]
    fn b3_param_gated_with_annotation_attaches_resolution_signal() {
        // Annotation on the same line as the finding.
        let src = "def configure(verify):\n\
                   \x20   if not verify:\n\
                   \x20       ssl.CERT_NONE  # repotoire: tls-disabled[self-signed-dev]\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at("InsecureTlsDetector", Severity::High, &path, 3)];
        let cfg = dual_branch_insecure_tls_on();
        let _ = classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        let f = &findings[0];
        assert_eq!(
            f.severity,
            Severity::Info,
            "annotation forces Benign primary"
        );
        let alt = f
            .alternative_branch
            .as_ref()
            .expect("alternative_branch set");
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);

        // Annotation produces a SourceAnnotation resolution signal.
        let syntaxes: Vec<&str> = f
            .resolution_signals
            .iter()
            .filter_map(|r| match &r.kind {
                crate::dual_branch::ResolutionKind::SourceAnnotation { syntax } => {
                    Some(syntax.as_str())
                }
                _ => None,
            })
            .collect();
        assert_eq!(syntaxes.len(), 1);
        assert!(
            syntaxes[0].contains("tls-disabled[self-signed-dev]"),
            "syntax preserves args: got `{}`",
            syntaxes[0]
        );
        assert_eq!(
            f.resolution_signals[0].collapses_to,
            crate::dual_branch::BranchLabel::Benign
        );

        // Param-gated reason is still present too — both signals coexist.
        let has_enclosing = f.prediction_reasons.iter().any(|r| {
            matches!(
                &r.kind,
                crate::dual_branch::PredictionReasonKind::EnclosingScope { .. }
            )
        });
        assert!(
            has_enclosing,
            "annotation does not erase the AST-derived evidence"
        );
    }

    #[test]
    fn b4_not_param_gated_with_preceding_line_annotation_collapses_to_benign() {
        // Annotation on the line *above* the finding (matches `# noqa` style).
        let src = "import ssl\n\
                   # repotoire: tls-disabled[integration-test-mitm]\n\
                   ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at(
            "InsecureTlsDetector",
            Severity::Critical,
            &path,
            3,
        )];
        let cfg = dual_branch_insecure_tls_on();
        let _ = classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        let f = &findings[0];
        assert_eq!(
            f.severity,
            Severity::Info,
            "annotation collapses even without param-gating"
        );
        let alt = f
            .alternative_branch
            .as_ref()
            .expect("alternative_branch set");
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
        assert_eq!(
            alt.severity,
            Severity::Critical,
            "alternative preserves original Critical severity"
        );
        assert_eq!(f.resolution_signals.len(), 1);
        // No EnclosingScope reason because not param-gated.
        let has_enclosing = f.prediction_reasons.iter().any(|r| {
            matches!(
                &r.kind,
                crate::dual_branch::PredictionReasonKind::EnclosingScope { .. }
            )
        });
        assert!(!has_enclosing);
    }

    #[test]
    fn flag_off_preserves_pre_phase_2c_demotion_for_insecure_tls() {
        // Same source as B1, but flag off → original demotion behavior.
        // Pins backward-compat: shipping Phase 2c does not change the
        // wire shape for users who haven't opted in.
        let src = "def configure(verify):\n\
                   \x20   if not verify:\n\
                   \x20       ssl.CERT_NONE\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at("InsecureTlsDetector", Severity::High, &path, 3)];
        let cfg = crate::config::DualBranchConfig::default();
        let demoted =
            classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        assert_eq!(demoted, 1);
        let f = &findings[0];
        assert_eq!(f.severity, Severity::Low);
        assert!(
            f.alternative_branch.is_none(),
            "flag off → no dual-branch shape"
        );
        assert!(f.prediction_reasons.is_empty());
        assert!(f.resolution_signals.is_empty());
        assert_eq!(
            f.threshold_metadata.get(PARAM_GATED_METADATA_KEY),
            Some(&"true".to_string()),
            "flag off → original threshold metadata still set"
        );
    }

    #[test]
    fn flag_on_does_not_affect_non_insecure_tls_security_findings() {
        // SQLInjection finding in a param-gated branch + flag on for
        // insecure-tls. The SQL finding must still go through Outcome A
        // (demotion), not Outcome B — the flag is per-detector.
        let src = "def query(safe):\n\
                   \x20   if not safe:\n\
                   \x20       cursor.execute(user_input)\n";
        let (_tmp, path) = write_py(src);
        let mut findings = vec![finding_at("SQLInjectionDetector", Severity::High, &path, 3)];
        let cfg = dual_branch_insecure_tls_on();
        let demoted =
            classify_param_gated_security_branches(&mut findings, None, Path::new("/"), &cfg);

        assert_eq!(demoted, 1, "non-TLS findings still go through Outcome A");
        let f = &findings[0];
        assert_eq!(f.severity, Severity::Low);
        assert!(f.alternative_branch.is_none());
    }
}