repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
//! Dual-branch predictor for Python JWT decode/verify call sites.
//!
//! Implements decisions D1 (weights, with the `'none'` RealBug-direction
//! Step 1.5 collapse) and D3 (severity) from
//! `docs/superpowers/specs/2026-05-09-dual-branch-phase2-jwt-weak-decisions.md`.
//!
//! # What this module does
//!
//! Given a Python JWT decode/verify call site (`jwt.decode(...)`,
//! `jwt.verify(...)`, `python_jose.jwt.decode(...)`,
//! `JWTVerifier.verify(...)`), produce a [`Prediction`] that:
//!
//! 1. Picks `RealBug` or `Benign` as the predicted branch.
//! 2. Carries the other branch as the alternative.
//! 3. Lists typed [`PredictionReason`]s the predictor used.
//! 4. Optionally lists [`ResolutionSignal`]s (collapsing or hint-grade).
//!
//! # The RealBug-direction collapse (D1 amendment) — **novel in 2g**
//!
//! Unlike 2e (defusedxml → Benign) and 2f (advocate → Benign), Phase 2g
//! introduces the FIRST RealBug-direction Step 1.5 collapse: `'none'`
//! anywhere in the algorithm slot (singular `algorithm='none'` OR in
//! the `algorithms=[...]` list) collapses to RealBug / Critical
//! regardless of any other defensive coding present.
//!
//! See the predict function's Step 1.5 and decisions doc §6 for the
//! full argument. The principled asymmetry: JWT-land has no
//! safe-by-construction library, so the "argument shape" axis is where
//! decisive evidence lives — and `'none'` is unconditional unsigned-
//! token acceptance on the RealBug side.
//!
//! # Sign convention
//!
//! `weight > 0` leans **Benign**; `weight < 0` leans **RealBug**.
//!
//! # Severity mapping (D3)
//!
//! - Predicted **RealBug** via the `'none'` collapse → `Severity::Critical`.
//! - Predicted **RealBug** otherwise → `Critical` when the sum is
//!   strongly negative (`sum <= -0.7`), `High` for moderately negative
//!   (`-0.7 < sum <= -0.4`), `Medium` for shallow negative.
//! - Predicted **Benign** → `Severity::Info`.
//! - Alternative branch carries the opposite label's severity.
//!
//! # Resolution signals (collapsing)
//!
//! Three annotations / patterns fully collapse the prediction:
//!
//! - `# repotoire: jwt-safe[<reason>]` → `Benign` (Info).
//! - `# repotoire: jwt-vulnerable[<source>]` → `RealBug` (severity per
//!   the legacy `JwtVulnerability::severity` calibration).
//! - `'none'` in the algorithm slot → `RealBug` (Critical). **D1 amendment**.
//!
//! # Why these weights
//!
//! See decision **D1** (with the §6 D1 amendment for the `'none'`
//! collapse). Numbers tagged `TUNABLE`. Phase 3 misprediction logging
//! is the right place to retune.

use super::annotation::parse_python_comment;
use crate::dual_branch::{
    AlternativeBranch, BranchLabel, PredictionReason, PredictionReasonKind, ResolutionKind,
    ResolutionSignal,
};
use crate::models::Severity;

// ─────────────────────────────────────────────────────────────────────────────
// JwtApi — the JWT-library-API enum for Phase 2g
// ─────────────────────────────────────────────────────────────────────────────

/// Which Python JWT-library API the call site uses. Unlike `HttpApi`
/// in 2f, there is NO safe-by-construction member — every JWT library
/// in the Python ecosystem can be used correctly or incorrectly. The
/// `JwtApi` enum is used for labeling/title/description purposes only;
/// it does not contribute a weight to the predictor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum JwtApi {
    /// `jwt.decode`, `jwt.verify` — the PyJWT library. Most popular
    /// Python JWT library. PyJWT >= 2.0 raises if `algorithms=` is
    /// omitted; older versions and python-jose silently accept the
    /// token-header alg.
    PyJwt,
    /// `jose.jwt.decode`, `python_jose.jwt.decode` — the python-jose
    /// library. Closer to JOSE spec than PyJWT but accepts token-
    /// header `alg` if `algorithms=` is omitted.
    PythonJose,
    /// `JWTVerifier.verify`, `Verifier.verify`, etc. — generic JWT
    /// verifier wrappers (e.g. authlib, auth0 SDKs).
    JwtVerifier,
    /// Recognized JWT call but library not classified. No special
    /// weight contribution beyond base detection.
    Unknown,
}

impl JwtApi {
    /// Human-readable label for the API used in titles/descriptions.
    pub(super) fn callee_label(self) -> &'static str {
        match self {
            JwtApi::PyJwt => "jwt",
            JwtApi::PythonJose => "python-jose",
            JwtApi::JwtVerifier => "JWTVerifier",
            JwtApi::Unknown => "JWT client",
        }
    }

    /// True iff the API is a recognized Python JWT-library family.
    /// Gates the Phase 2g dual-branch emission path: only Python sites
    /// get the predictor-aware shape; JS/Java/etc. still go through
    /// the legacy regex scanner per decisions D5.
    pub(super) fn is_python(self) -> bool {
        matches!(
            self,
            JwtApi::PyJwt | JwtApi::PythonJose | JwtApi::JwtVerifier
        )
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tunable weights
// ─────────────────────────────────────────────────────────────────────────────

// TUNABLE: see Phase 3 misprediction logging.
//
// Sign convention: positive leans Benign, negative leans RealBug.
//
// Calibration target (per decisions doc D1 worked examples Case A-E):
//   A. `jwt.decode(token, key, algorithms=['RS256'])` in login handler:
//      +0.50 + 0.10 - 0.20 = +0.40 → Benign. ✅
//   B. `jwt.decode(token, key)` in login handler:
//      -0.40 - 0.20 = -0.60 → RealBug High. ✅
//   C. `jwt.decode(token, "supersecret", algorithm='none')`:
//      Step 1.5 collapse → RealBug Critical. ✅
//   D. `jwt.decode(token, key, algorithms=['none', 'HS256'])`:
//      Step 1.5 collapse → RealBug Critical. ✅ (vs naive -0.30 → Medium)
//   E. `jwt.decode(token, public_key, algorithms=['HS256'])`:
//      +0.50 - 0.50 = 0.00 → tiebreak RealBug Medium. ✅

/// Explicit `algorithms=` kwarg present with any non-`'none'` value.
/// THE biggest Benign signal — the CVE-2015-2951 / CVE-2016-10555
/// family is about callers omitting this kwarg and letting the JWT
/// header pick. Compounds with `W_ASYMMETRIC_ALGORITHM`.
pub(super) const W_EXPLICIT_ALGORITHMS_KWARG: f32 = 0.50;

/// Additive on top of `W_EXPLICIT_ALGORITHMS_KWARG` when the allowlist
/// is asymmetric (`RS256`, `ES256`, `EdDSA`, `PS256`, etc.).
pub(super) const W_ASYMMETRIC_ALGORITHM: f32 = 0.10;

/// Explicit `verify=True` or `options={'verify_signature': True}`.
/// Defensive coding — the developer wrote the kwarg even though `True`
/// is the default. Weak positive signal.
pub(super) const W_EXPLICIT_VERIFY_TRUE: f32 = 0.10;

/// `from cryptography.hazmat.primitives import serialization` or
/// similar strong-key constant import near the JWT call site. Soft
/// positive signal.
pub(super) const W_IMPORT_STRONG_KEY_LIB: f32 = 0.05;

/// Enclosing function looks like a test fixture.
pub(super) const W_ENCLOSING_TEST_FUNCTION: f32 = 0.15;

/// `algorithms=` kwarg is omitted on `jwt.decode`. The algorithm-
/// confusion gateway. PyJWT >= 2.0 raises if omitted, but older code
/// and python-jose accept the token-header alg.
pub(super) const W_ALGORITHMS_KWARG_OMITTED: f32 = -0.40;

/// Explicit `verify=False` or `options={'verify_signature': False}`.
/// Disables signature check entirely. Near-decisive on its own.
pub(super) const W_EXPLICIT_VERIFY_FALSE: f32 = -0.70;

/// HS256 (symmetric) with a key argument whose name suggests a public
/// key (`pub_key`, `public_key`, or path containing `.pem`). The JWT
/// key-confusion attack.
pub(super) const W_HS256_WITH_PUBLIC_KEY: f32 = -0.50;

/// HS256 with a short hardcoded string secret. Soft weak-secret signal.
pub(super) const W_HS256_WITH_SHORT_SECRET: f32 = -0.20;

/// Enclosing function looks like an auth flow (`auth`, `login`,
/// `token`, `verify`, `session`, `middleware`). Multiplies the cost of
/// any unsafe signal (mirrors legacy `is_auth_flow`).
pub(super) const W_ENCLOSING_AUTH_FLOW: f32 = -0.20;

/// `'none'` in the algorithm slot (singular OR list). **D1 amendment**:
/// this is the first RealBug-direction Step 1.5 collapse in the dual-
/// branch series. The emitted PredictionReason carries weight `-1.0` to
/// mirror an annotation collapse in the RealBug direction.
///
/// Honest review note (2026-05-11): without this collapse,
/// `algorithms=['none', 'HS256']` scores `+0.50 - 0.80 = -0.30` → Medium,
/// which is too quiet for "algorithm=none accepted in the allowlist."
/// See decisions doc §6 for the full argument.
pub(super) const W_ALGORITHM_NONE_COLLAPSE: f32 = -1.0;

// ─────────────────────────────────────────────────────────────────────────────
// Lexicons used by source-classification helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Substrings that identify an asymmetric JWT algorithm in an allowlist
/// value. Compared case-insensitively after stripping quotes.
const ASYMMETRIC_ALGORITHM_NAMES: &[&str] = &[
    "rs256", "rs384", "rs512", // RSA + SHA
    "es256", "es384", "es512", // ECDSA + SHA
    "ps256", "ps384", "ps512", // RSA-PSS + SHA
    "eddsa", "ed25519", "ed448",
];

/// Substrings that identify test code. Mirrors 2d/2e/2f.
const TEST_FUNCTION_SUBSTRINGS: &[&str] = &["test_", "_test", "fixture", "setup", "teardown"];

/// Substrings that identify an auth-flow function. Mirrors the legacy
/// `is_auth_flow` lexicon at the pre-Phase-2g `jwt_weak.rs:77-90`.
const AUTH_FLOW_FUNCTION_SUBSTRINGS: &[&str] =
    &["auth", "login", "token", "verify", "session", "middleware"];

/// Substrings that suggest a key argument is a *public* key (HMAC with
/// a public key is the JWT key-confusion attack).
const PUBLIC_KEY_NAME_SUBSTRINGS: &[&str] = &[
    "pub_key",
    "public_key",
    "publickey",
    ".pem",
    "rsa_pub",
    "ecdsa_pub",
    "verify_key",
    "verifying_key",
];

// ─────────────────────────────────────────────────────────────────────────────
// Evidence
// ─────────────────────────────────────────────────────────────────────────────

/// Structured evidence extracted from a JWT decode/verify call site.
#[derive(Debug, Clone, Default, PartialEq)]
pub(super) struct Evidence {
    /// Which JWT-library API the call site uses.
    pub api: Option<JwtApi>,

    /// Name of the enclosing function, if any.
    pub enclosing_function: Option<String>,

    /// Name of the enclosing class, if any (informational; no weight).
    pub enclosing_class: Option<String>,

    /// File path string, used to compute auth-flow scope from
    /// directory components (mirror of legacy `is_auth_flow`).
    pub file_path: Option<String>,

    /// `cryptography.hazmat.primitives.serialization` or similar strong-
    /// key library imported anywhere in the file. File-scoped (D5 v0
    /// limitation).
    pub import_strong_key_lib: bool,

    /// Explicit `algorithms=` kwarg present and value is non-empty.
    pub explicit_algorithms_kwarg: bool,

    /// `algorithms=` kwarg explicitly contains `'none'` as one of its
    /// values, OR the singular `algorithm='none'` kwarg is present.
    /// **Triggers the Step 1.5 RealBug-direction collapse.**
    pub algorithm_none_in_slot: bool,

    /// The `algorithms=` allowlist contains at least one asymmetric
    /// algorithm (RS*, ES*, PS*, EdDSA).
    pub asymmetric_algorithm_in_allowlist: bool,

    /// Explicit `verify=True` kwarg OR `options={'verify_signature':
    /// True}` present.
    pub explicit_verify_true: bool,

    /// Explicit `verify=False` kwarg OR `options={'verify_signature':
    /// False}` present.
    pub explicit_verify_false: bool,

    /// `algorithm='none'` (singular) is present. Subset of
    /// `algorithm_none_in_slot` but recorded separately for the legacy
    /// `JwtVulnerability` classifier.
    pub algorithm_singular_none: bool,

    /// HS256 (symmetric) algorithm is in use AND the key argument's
    /// identifier name suggests a public key. Triggers `KeyConfusion`
    /// classification in the legacy taxonomy.
    pub hs256_with_public_key: bool,

    /// HS256 is in use AND the key is a short hardcoded string literal
    /// (≤ 16 chars). Weak-secret heuristic.
    pub hs256_with_short_secret: bool,

    /// `Some(reason)` if a `# repotoire: jwt-safe[<reason>]` annotation
    /// appears on the call line. **Collapsing**.
    pub jwt_safe_annotation: Option<String>,

    /// `Some(source)` if a `# repotoire: jwt-vulnerable[<source>]`
    /// annotation appears on the call line. **Collapsing**.
    pub jwt_vulnerable_annotation: Option<String>,
}

impl Evidence {
    #[cfg(test)]
    pub(super) fn empty() -> Self {
        Self::default()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Prediction
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub(super) struct Prediction {
    pub predicted: BranchLabel,
    pub alternative_branch: AlternativeBranch,
    pub predicted_severity: Severity,
    pub reasons: Vec<PredictionReason>,
    pub resolutions: Vec<ResolutionSignal>,
}

// ─────────────────────────────────────────────────────────────────────────────
// Scorer
// ─────────────────────────────────────────────────────────────────────────────

/// Build a [`Prediction`] from extracted [`Evidence`].
///
/// # Algorithm
///
/// 1. **Collapsing annotations first.** If `jwt_safe_annotation` or
///    `jwt_vulnerable_annotation` is set, commit to the corresponding
///    branch with confidence 1.0 and skip weighted scoring.
/// 2. **Step 1.5 `'none'` collapse (D1 amendment).** If
///    `algorithm_none_in_slot` is set, commit to **RealBug / Critical**
///    regardless of any other signals. This is the first RealBug-
///    direction collapse in the dual-branch series.
/// 3. **Weighted scoring.** Sum weights for each present signal.
/// 4. **Tiebreak**: sum exactly 0.0 → predict RealBug. Conservative
///    default for security findings.
///
/// # Severity mapping (D3)
///
/// - `'none'` collapse → `Severity::Critical`.
/// - Annotation `jwt-vulnerable` → severity from `severity_for_branch`.
/// - Predicted RealBug otherwise → severity bucketed from the weighted
///   sum: `<= -0.7` Critical, `(-0.7, -0.4]` High, `(-0.4, 0.0)` Medium.
/// - Predicted Benign → `Severity::Info`.
pub(super) fn predict(evidence: &Evidence) -> Prediction {
    let api = evidence.api.unwrap_or(JwtApi::Unknown);
    let api_label = api.callee_label();

    // ── Step 1: collapsing annotations. ──
    if let Some(reason) = &evidence.jwt_safe_annotation {
        return collapse(
            BranchLabel::Benign,
            api,
            0.0, // benign collapse always severity Info regardless of sum
            ResolutionSignal {
                kind: ResolutionKind::SourceAnnotation {
                    syntax: format!("# repotoire: jwt-safe[{reason}]"),
                },
                description: format!(
                    "`jwt-safe[{reason}]` annotation declares this JWT \
                     decode call as safe (verified at edge, signed by \
                     internal service, etc.); the finding collapses to \
                     Info."
                ),
                example: Some(format!(
                    "{api_label}.decode(...)  # repotoire: jwt-safe[{reason}]"
                )),
                collapses_to: BranchLabel::Benign,
            },
            PredictionReason {
                kind: PredictionReasonKind::Custom {
                    description: format!("jwt-safe[{reason}] annotation"),
                },
                weight: 1.0,
                note: format!(
                    "Annotated as verified-elsewhere ({reason}); not a \
                     JWT security risk."
                ),
            },
        );
    }
    if let Some(source) = &evidence.jwt_vulnerable_annotation {
        return collapse(
            BranchLabel::RealBug,
            api,
            -1.0, // strongly negative → Critical
            ResolutionSignal {
                kind: ResolutionKind::SourceAnnotation {
                    syntax: format!("# repotoire: jwt-vulnerable[{source}]"),
                },
                description: format!(
                    "`jwt-vulnerable[{source}]` annotation declares this \
                     JWT decode as exposed (attacker-controlled algorithm, \
                     audited-untrusted, etc.); the finding stays at the \
                     existing severity."
                ),
                example: Some(format!(
                    "{api_label}.decode(...)  # repotoire: jwt-vulnerable[{source}]"
                )),
                collapses_to: BranchLabel::RealBug,
            },
            PredictionReason {
                kind: PredictionReasonKind::Custom {
                    description: format!("jwt-vulnerable[{source}] annotation"),
                },
                weight: -1.0,
                note: format!("Annotated as JWT-exposed (source: {source})."),
            },
        );
    }

    // ── Step 1.5: `'none'` RealBug-direction collapse (D1 amendment). ──
    //
    // `'none'` in any algorithm slot (singular `algorithm='none'` or
    // anywhere in the `algorithms=[...]` list) is unconditional
    // unsigned-token acceptance. No other defensive coding compensates;
    // the verification path is bypassed by design.
    //
    // This is the FIRST RealBug-direction Step 1.5 collapse in the
    // dual-branch series. Phases 2e (defusedxml) and 2f (advocate)
    // added Benign-direction collapses for safe-by-construction
    // library detection. JWT-land has no safe-by-construction library;
    // decisive evidence on the RealBug side lives in argument shape.
    if evidence.algorithm_none_in_slot {
        return collapse(
            BranchLabel::RealBug,
            api,
            -1.0, // forces Critical via severity_for_realbug_sum
            ResolutionSignal {
                kind: ResolutionKind::StructuralPattern {
                    description:
                        "'none' in JWT algorithm slot (unconditional unsigned-token acceptance)"
                            .to_string(),
                },
                description: "The JWT call accepts `'none'` as an \
                     algorithm — either via `algorithm='none'` (singular) \
                     or as an entry in the `algorithms=[...]` list. This \
                     is unconditional acceptance of unsigned tokens. No \
                     other defensive coding compensates because the `none` \
                     algorithm path bypasses signature verification by \
                     design."
                    .to_string(),
                example: Some(format!(
                    "{api_label}.decode(token, key, algorithms=['RS256'])  # not ['none', ...]"
                )),
                collapses_to: BranchLabel::RealBug,
            },
            PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description:
                        "'none' in JWT algorithm slot (unconditional unsigned-token acceptance)"
                            .to_string(),
                },
                weight: W_ALGORITHM_NONE_COLLAPSE,
                note: "The call site has `'none'` in the algorithm slot. \
                       This is the textbook CVE-2015-2951 / CVE-2016-10555 \
                       failure mode: unsigned tokens are accepted, \
                       regardless of any other verification coding present. \
                       First RealBug-direction collapse in the dual-branch \
                       series (Phase 2g D1 amendment)."
                    .to_string(),
            },
        );
    }

    // ── Step 2: weighted scoring. ──
    let mut sum: f32 = 0.0;
    let mut reasons: Vec<PredictionReason> = Vec::new();

    if evidence.explicit_algorithms_kwarg {
        sum += W_EXPLICIT_ALGORITHMS_KWARG;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::KeywordArgument {
                name: "algorithms".to_string(),
                value: "<list>".to_string(),
            },
            weight: W_EXPLICIT_ALGORITHMS_KWARG,
            note: "Explicit `algorithms=` kwarg is provided. The CVE-2015-\
                   2951 / CVE-2016-10555 family is about omitting this \
                   kwarg and letting the JWT header pick the algorithm. \
                   Decisive Benign signal on its own short of the `'none'` \
                   collapse path."
                .to_string(),
        });
    }

    if evidence.asymmetric_algorithm_in_allowlist {
        sum += W_ASYMMETRIC_ALGORITHM;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "asymmetric algorithm (RS*/ES*/PS*/EdDSA) in algorithms=[...]"
                    .to_string(),
            },
            weight: W_ASYMMETRIC_ALGORITHM,
            note: "The `algorithms=` allowlist contains at least one \
                   asymmetric algorithm (RS256, ES256, EdDSA, etc.) — \
                   stronger than an HS-only allowlist because the JWT \
                   key-confusion attack class is closed at the algorithm \
                   layer."
                .to_string(),
        });
    }

    if evidence.explicit_verify_true {
        sum += W_EXPLICIT_VERIFY_TRUE;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::KeywordArgument {
                name: "verify".to_string(),
                value: "True".to_string(),
            },
            weight: W_EXPLICIT_VERIFY_TRUE,
            note: "Explicit `verify=True` or `options={'verify_signature': \
                   True}`. Defensive coding — the developer wrote the \
                   kwarg even though `True` is the library's default."
                .to_string(),
        });
    }

    if evidence.import_strong_key_lib {
        sum += W_IMPORT_STRONG_KEY_LIB;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::ImportPresence {
                module: "cryptography.hazmat.primitives.serialization".to_string(),
            },
            weight: W_IMPORT_STRONG_KEY_LIB,
            note: "Strong-key constant library imported near the JWT call \
                   site. Soft positive signal — the code path appears to \
                   load proper keys."
                .to_string(),
        });
    }

    if !evidence.explicit_algorithms_kwarg
        && !evidence.algorithm_singular_none
        && matches!(
            api,
            JwtApi::PyJwt | JwtApi::PythonJose | JwtApi::JwtVerifier
        )
    {
        sum += W_ALGORITHMS_KWARG_OMITTED;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "algorithms= kwarg omitted on JWT decode".to_string(),
            },
            weight: W_ALGORITHMS_KWARG_OMITTED,
            note: "The `algorithms=` kwarg is not provided. PyJWT >= 2.0 \
                   raises if this is omitted, but older PyJWT and \
                   python-jose accept the algorithm from the token \
                   header — the algorithm-confusion gateway."
                .to_string(),
        });
    }

    if evidence.explicit_verify_false {
        sum += W_EXPLICIT_VERIFY_FALSE;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::KeywordArgument {
                name: "verify".to_string(),
                value: "False".to_string(),
            },
            weight: W_EXPLICIT_VERIFY_FALSE,
            note: "Signature verification is explicitly disabled via \
                   `verify=False` or `options={'verify_signature': \
                   False}`. Tokens are accepted without signature \
                   validation."
                .to_string(),
        });
    }

    if evidence.hs256_with_public_key {
        sum += W_HS256_WITH_PUBLIC_KEY;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "HS256 with public-key argument (JWT key confusion)".to_string(),
            },
            weight: W_HS256_WITH_PUBLIC_KEY,
            note: "The JWT call uses HS256 (HMAC) but the key argument's \
                   name (`pub_key`, `public_key`, `*.pem`) suggests it \
                   is an RSA public key. Attackers can sign tokens with \
                   the public key as if it were an HMAC secret — the \
                   classic JWT key-confusion attack."
                .to_string(),
        });
    }

    if evidence.hs256_with_short_secret {
        sum += W_HS256_WITH_SHORT_SECRET;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "HS256 with short hardcoded secret".to_string(),
            },
            weight: W_HS256_WITH_SHORT_SECRET,
            note: "The JWT call uses HS256 with a short hardcoded string \
                   secret (≤ 16 chars). Weak secrets are vulnerable to \
                   offline brute-force attacks."
                .to_string(),
        });
    }

    if let Some(fn_name) = &evidence.enclosing_function {
        let in_auth_path = evidence
            .file_path
            .as_deref()
            .map(path_matches_auth_flow)
            .unwrap_or(false);
        if matches_test_function(fn_name) {
            sum += W_ENCLOSING_TEST_FUNCTION;
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::EnclosingScope {
                    scope_kind: "function".to_string(),
                    name: fn_name.clone(),
                },
                weight: W_ENCLOSING_TEST_FUNCTION,
                note: format!(
                    "Enclosing function `{fn_name}` looks like a \
                     test/fixture; test code rarely the actionable \
                     security target."
                ),
            });
        } else if matches_auth_flow_function(fn_name) || in_auth_path {
            sum += W_ENCLOSING_AUTH_FLOW;
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::EnclosingScope {
                    scope_kind: "auth_flow".to_string(),
                    name: fn_name.clone(),
                },
                weight: W_ENCLOSING_AUTH_FLOW,
                note: format!(
                    "Enclosing function `{fn_name}` (or file path) looks \
                     like an auth flow (`auth`/`login`/`token`/`verify`/\
                     `session`/`middleware`); higher prior on attacker-\
                     reachable JWT verification code."
                ),
            });
        }
    } else if let Some(path) = evidence.file_path.as_deref() {
        if path_matches_auth_flow(path) {
            sum += W_ENCLOSING_AUTH_FLOW;
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::EnclosingScope {
                    scope_kind: "auth_flow".to_string(),
                    name: path.to_string(),
                },
                weight: W_ENCLOSING_AUTH_FLOW,
                note: format!(
                    "File path `{path}` is in an auth-flow directory \
                     (auth/security/middleware); higher prior on \
                     attacker-reachable JWT code."
                ),
            });
        }
    }

    // ── Step 3: tiebreak + severity mapping. ──
    let predicted = if sum > 0.0 {
        BranchLabel::Benign
    } else {
        BranchLabel::RealBug
    };

    build_prediction(predicted, api, sum, reasons, Vec::new())
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

/// True iff the given algorithm string (post-strip-quotes) names an
/// asymmetric JWT algorithm.
pub(super) fn is_asymmetric_algorithm(name: &str) -> bool {
    let lower = name.trim().trim_matches(['\'', '"']).to_lowercase();
    ASYMMETRIC_ALGORITHM_NAMES
        .iter()
        .any(|sub| lower == *sub || lower.contains(sub))
}

/// True iff any token in `algorithm_list` (a list-like text such as
/// `['RS256', 'HS256']`) is `'none'` (case-insensitive).
pub(super) fn algorithm_list_contains_none(list_text: &str) -> bool {
    let lower = list_text.to_lowercase();
    // Match `'none'` or `"none"` as an exact list element (avoid
    // matching `'something-none'`).
    lower.contains("'none'") || lower.contains("\"none\"")
}

/// True iff the given identifier-like string suggests a public-key
/// argument (used for the JWT key-confusion attack heuristic).
pub(super) fn matches_public_key_name(name: &str) -> bool {
    let lower = name.to_lowercase();
    PUBLIC_KEY_NAME_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
}

fn matches_test_function(name: &str) -> bool {
    let lower = name.to_lowercase();
    TEST_FUNCTION_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
}

pub(super) fn matches_auth_flow_function(name: &str) -> bool {
    let lower = name.to_lowercase();
    AUTH_FLOW_FUNCTION_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
}

pub(super) fn path_matches_auth_flow(path: &str) -> bool {
    let lower = path.to_lowercase();
    lower.contains("auth") || lower.contains("security") || lower.contains("middleware")
}

fn collapse(
    label: BranchLabel,
    api: JwtApi,
    forced_sum: f32,
    resolution: ResolutionSignal,
    reason: PredictionReason,
) -> Prediction {
    build_prediction(label, api, forced_sum, vec![reason], vec![resolution])
}

fn build_prediction(
    predicted: BranchLabel,
    api: JwtApi,
    sum: f32,
    reasons: Vec<PredictionReason>,
    resolutions: Vec<ResolutionSignal>,
) -> Prediction {
    let api_label = api.callee_label();
    let predicted_severity = severity_for_branch(predicted, sum);
    let alternative_label = predicted.opposite();
    let alternative_severity = severity_for_branch(alternative_label, sum);

    let alternative_branch = AlternativeBranch {
        label: alternative_label,
        severity: alternative_severity,
        title: title_for_branch(alternative_label, api_label),
        description: description_for_branch(alternative_label, api_label),
        suggested_fix: suggested_fix_for_branch(alternative_label, api_label),
    };

    Prediction {
        predicted,
        alternative_branch,
        predicted_severity,
        reasons,
        resolutions,
    }
}

/// D3 severity mapping. RealBug severity buckets from the weighted sum
/// (or forced to Critical for the `'none'` collapse path):
///
/// - `sum <= -0.7` → Critical
/// - `-0.7 < sum <= -0.4` → High
/// - `-0.4 < sum < 0.0` → Medium
/// - `sum == 0.0` → Medium (tiebreak)
///
/// Benign → Info.
fn severity_for_branch(label: BranchLabel, sum: f32) -> Severity {
    match label {
        BranchLabel::RealBug => {
            if sum <= -0.7 {
                Severity::Critical
            } else if sum <= -0.4 {
                Severity::High
            } else {
                Severity::Medium
            }
        }
        BranchLabel::Benign => Severity::Info,
    }
}

fn title_for_branch(label: BranchLabel, api_label: &str) -> String {
    match label {
        BranchLabel::RealBug => format!("Potential JWT vulnerability in {api_label} call"),
        BranchLabel::Benign => {
            format!("JWT decode via {api_label} appears correctly verified (informational)")
        }
    }
}

fn description_for_branch(label: BranchLabel, api_label: &str) -> String {
    match label {
        BranchLabel::RealBug => format!(
            "The `{api_label}` JWT call appears to be missing an explicit \
             `algorithms=` allowlist, OR has `verify=False`, OR uses a \
             dangerous symmetric/asymmetric key pairing. JWT \
             vulnerabilities allow attackers to forge authentication \
             tokens, impersonate users, escalate privileges, or bypass \
             authorization entirely."
        ),
        BranchLabel::Benign => format!(
            "The `{api_label}` JWT call appears to enforce an explicit \
             algorithm allowlist (`algorithms=[...]`) and signature \
             verification. The call site is carried as Info; the \
             RealBug interpretation is preserved in `alternative_branch` \
             in case the predictor is wrong."
        ),
    }
}

fn suggested_fix_for_branch(label: BranchLabel, _api_label: &str) -> Option<String> {
    match label {
        BranchLabel::RealBug => Some(
            "Always provide an explicit algorithm allowlist and never \
             include `'none'`:\n\n\
             ```python\n\
             jwt.decode(token, key, algorithms=['RS256'])  # explicit, non-'none'\n\
             ```\n\n\
             If using HS256, ensure the key argument is NOT a public \
             key (the JWT key-confusion attack); prefer asymmetric \
             algorithms with proper key pairs. If this is intentional \
             safe usage (the JWT is verified upstream by an edge \
             proxy, etc.), annotate `# repotoire: jwt-safe[<reason>]` \
             to collapse the finding to Info definitively."
                .to_string(),
        ),
        BranchLabel::Benign => Some(
            "If this is intentional safe usage, annotate \
             `# repotoire: jwt-safe[<reason>]` to collapse the finding \
             to Info definitively. If the alternative branch is \
             correct (the JWT IS exposed to attacker-controlled \
             algorithm choice), audit the algorithm allowlist for \
             `'none'`, audit `verify=` for `False`, and verify the key \
             argument is appropriate for the algorithm."
                .to_string(),
        ),
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Annotation lookup helpers (called by evidence extraction)
// ─────────────────────────────────────────────────────────────────────────────

/// If `line` carries `# repotoire: jwt-safe[<reason>]`, return the
/// reason. Defaults to `"unspecified"` if no arg supplied.
pub(super) fn extract_jwt_safe_reason(line: &str) -> Option<String> {
    let ann = parse_python_comment(line)?;
    if ann.kind != "jwt-safe" {
        return None;
    }
    if ann.args.is_empty() {
        Some("unspecified".to_string())
    } else {
        Some(ann.args[0].clone())
    }
}

/// If `line` carries `# repotoire: jwt-vulnerable[<source>]`, return
/// the source. Defaults to `"unspecified"` if no arg supplied.
pub(super) fn extract_jwt_vulnerable_source(line: &str) -> Option<String> {
    let ann = parse_python_comment(line)?;
    if ann.kind != "jwt-vulnerable" {
        return None;
    }
    if ann.args.is_empty() {
        Some("unspecified".to_string())
    } else {
        Some(ann.args[0].clone())
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    // ─── Worked example A (decisions D1): explicit RS256 in handler. ───
    #[test]
    fn case_a_explicit_rs256_in_auth_handler_predicts_benign() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            asymmetric_algorithm_in_allowlist: true,
            enclosing_function: Some("login_handler".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
        assert_eq!(p.predicted_severity, Severity::Info);
        // +0.50 + 0.10 - 0.20 = +0.40
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total - 0.40).abs() < 1e-6, "expected +0.40, got {total}");
    }

    // ─── Worked example B (decisions D1): naked decode in handler. ───
    #[test]
    fn case_b_naked_decode_in_handler_predicts_realbug_high() {
        // no `algorithms=`, in auth flow → -0.40 - 0.20 = -0.60 → High
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            enclosing_function: Some("login_handler".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::High);
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total + 0.60).abs() < 1e-6, "expected -0.60, got {total}");
    }

    // ─── Worked example C (decisions D1): algorithm='none' singular. ───
    #[test]
    fn case_c_algorithm_none_singular_collapses_to_realbug_critical() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            algorithm_none_in_slot: true,
            algorithm_singular_none: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
        // collapse path emits exactly one reason
        assert_eq!(p.reasons.len(), 1);
        assert_eq!(p.resolutions.len(), 1);
        assert!(matches!(
            p.resolutions[0].kind,
            ResolutionKind::StructuralPattern { .. }
        ));
    }

    // ─── Worked example D (decisions D1 amendment): 'none' in list. ───
    #[test]
    fn case_d_algorithm_none_in_list_collapses_to_realbug_critical() {
        // The textbook CVE-2015-2951 mitigation-period bug. Without
        // the collapse: +0.50 (algorithms=) - 0.80 = -0.30 → Medium.
        // With the collapse: Critical regardless.
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            algorithm_none_in_slot: true,
            enclosing_function: Some("login_handler".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
        assert_eq!(p.reasons.len(), 1, "collapse emits exactly one reason");
    }

    // ─── Worked example E: HS256 with public key. ───
    #[test]
    fn case_e_hs256_with_public_key_predicts_realbug() {
        // +0.50 (algorithms=) - 0.50 (HS256 + pubkey) = 0.00 → tiebreak RealBug
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            hs256_with_public_key: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!(total.abs() < 1e-6, "expected 0.00, got {total}");
    }

    // ─── 'none' collapse dominates other Benign signals ───
    #[test]
    fn algorithm_none_collapse_dominates_other_benign_signals() {
        // Even with verify=True, import_strong_key_lib, asymmetric, and
        // a test-function context, 'none' still collapses to Critical.
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            asymmetric_algorithm_in_allowlist: true,
            explicit_verify_true: true,
            import_strong_key_lib: true,
            algorithm_none_in_slot: true,
            enclosing_function: Some("test_jwt_decode".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
    }

    // ─── verify=False fires deep RealBug ───
    #[test]
    fn explicit_verify_false_predicts_realbug_high_or_critical() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            explicit_verify_false: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        // +0.50 - 0.70 = -0.20 → Medium
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total + 0.20).abs() < 1e-6, "expected -0.20, got {total}");
    }

    #[test]
    fn verify_false_with_auth_flow_predicts_realbug_high() {
        // verify=False + auth flow + no algorithms= would be -0.70 - 0.40 - 0.20 = -1.30 → Critical
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_verify_false: true,
            enclosing_function: Some("authenticate_user".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
    }

    // ─── Asymmetric algorithm in allowlist compounds ───
    #[test]
    fn asymmetric_algorithm_compounds_benign() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            asymmetric_algorithm_in_allowlist: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
        // +0.50 + 0.10 = +0.60
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total - 0.60).abs() < 1e-6);
    }

    // ─── verify=True compounds Benign ───
    #[test]
    fn verify_true_compounds_benign() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            explicit_verify_true: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
    }

    // ─── jwt-safe annotation collapses to Benign regardless ───
    #[test]
    fn jwt_safe_annotation_collapses_to_benign() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            // would normally collapse to RealBug:
            algorithm_none_in_slot: true,
            jwt_safe_annotation: Some("verified-at-edge".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        // Annotation collapse has higher priority than 'none' collapse
        assert_eq!(p.predicted, BranchLabel::Benign);
        assert_eq!(p.predicted_severity, Severity::Info);
        assert_eq!(p.resolutions.len(), 1);
        assert!(matches!(
            p.resolutions[0].kind,
            ResolutionKind::SourceAnnotation { .. }
        ));
    }

    // ─── jwt-vulnerable annotation collapses to RealBug ───
    #[test]
    fn jwt_vulnerable_annotation_collapses_to_realbug() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            // would normally be Benign:
            explicit_algorithms_kwarg: true,
            asymmetric_algorithm_in_allowlist: true,
            jwt_vulnerable_annotation: Some("alg-from-header".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
    }

    // ─── Tiebreak ───
    #[test]
    fn empty_evidence_tiebreaks_realbug() {
        let p = predict(&Evidence::empty());
        assert_eq!(p.predicted, BranchLabel::RealBug);
        // Empty evidence: no api means W_ALGORITHMS_KWARG_OMITTED gate skipped → sum=0 → Medium
        assert_eq!(p.predicted_severity, Severity::Medium);
    }

    // ─── Sign convention ───
    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn realbug_signal_weights_are_negative() {
        assert!(W_ALGORITHMS_KWARG_OMITTED < 0.0);
        assert!(W_EXPLICIT_VERIFY_FALSE < 0.0);
        assert!(W_HS256_WITH_PUBLIC_KEY < 0.0);
        assert!(W_HS256_WITH_SHORT_SECRET < 0.0);
        assert!(W_ENCLOSING_AUTH_FLOW < 0.0);
        assert!(W_ALGORITHM_NONE_COLLAPSE < 0.0);
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn benign_signal_weights_are_positive() {
        assert!(W_EXPLICIT_ALGORITHMS_KWARG > 0.0);
        assert!(W_ASYMMETRIC_ALGORITHM > 0.0);
        assert!(W_EXPLICIT_VERIFY_TRUE > 0.0);
        assert!(W_IMPORT_STRONG_KEY_LIB > 0.0);
        assert!(W_ENCLOSING_TEST_FUNCTION > 0.0);
    }

    // ─── Honest review pin: D1 amendment justification ───
    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn d1_amendment_required_case_d_predicts_medium_under_additive_only() {
        // Pins the math that justified the D1 amendment: under additive
        // scoring alone, Case D (algorithms=['none', 'HS256']) without
        // the collapse would score:
        //   +0.50 (algorithms=) ... and 'none' would need its own negative
        // We don't represent 'none' as additive in v0 — that's the whole
        // point of the collapse. If a future contributor refactors the
        // collapse OUT, the pin below asserts that the additive-only
        // math would only reach Medium, not the Critical the bug deserves.
        let additive_sum = W_EXPLICIT_ALGORITHMS_KWARG + W_ENCLOSING_AUTH_FLOW;
        // +0.50 - 0.20 = +0.30 → Benign actually! Even worse than Medium.
        // This is WHY we need the collapse: without it, the additive
        // model predicts the wrong branch entirely.
        assert!(
            additive_sum > 0.0,
            "Under additive-only, Case D would predict Benign — \
             unconditional unsigned-token acceptance classified as safe. \
             This is the bug the D1 amendment fixes. Pin: {additive_sum}"
        );
    }

    // ─── Auth-flow file path detection ───
    #[test]
    fn auth_flow_path_contributes_negative_weight() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            asymmetric_algorithm_in_allowlist: true,
            file_path: Some("/app/auth/jwt_handlers.py".to_string()),
            enclosing_function: Some("validate".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        // +0.50 + 0.10 - 0.20 (auth via path AND function name match `verify`-ish? actually validate doesn't match auth-flow lexicon)
        // Actually "validate" contains nothing in the lexicon. file_path triggers auth.
        // But enclosing_function block fires first; since matches_auth_flow_function("validate") is false (no auth/login/etc.),
        // we fall through to the in_auth_path check which IS true. So -0.20 fires.
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total - 0.40).abs() < 1e-6, "expected +0.40, got {total}");
    }

    // ─── HS256 + public key in auth flow → deep RealBug ───
    #[test]
    fn hs256_pubkey_in_auth_flow_predicts_realbug_high() {
        let evidence = Evidence {
            api: Some(JwtApi::PyJwt),
            explicit_algorithms_kwarg: true,
            hs256_with_public_key: true,
            enclosing_function: Some("authenticate".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        // +0.50 - 0.50 - 0.20 = -0.20 → Medium
        let total: f32 = p.reasons.iter().map(|r| r.weight).sum();
        assert!((total + 0.20).abs() < 1e-6, "expected -0.20, got {total}");
    }

    // ─── Lexicon checks ───
    #[test]
    fn asymmetric_algorithm_lexicon() {
        assert!(is_asymmetric_algorithm("RS256"));
        assert!(is_asymmetric_algorithm("'RS256'"));
        assert!(is_asymmetric_algorithm("\"ES256\""));
        assert!(is_asymmetric_algorithm("EdDSA"));
        assert!(is_asymmetric_algorithm("PS512"));
        assert!(!is_asymmetric_algorithm("HS256"));
        assert!(!is_asymmetric_algorithm("none"));
    }

    #[test]
    fn algorithm_list_contains_none_detector() {
        assert!(algorithm_list_contains_none("['none', 'HS256']"));
        assert!(algorithm_list_contains_none("[\"none\"]"));
        assert!(algorithm_list_contains_none("['HS256', 'NONE']"));
        assert!(!algorithm_list_contains_none("['HS256', 'RS256']"));
        // Don't match substrings of other words
        assert!(!algorithm_list_contains_none("['nonexistent']"));
    }

    #[test]
    fn public_key_name_lexicon() {
        assert!(matches_public_key_name("pub_key"));
        assert!(matches_public_key_name("public_key"));
        assert!(matches_public_key_name("PublicKey"));
        assert!(matches_public_key_name("/etc/keys/rsa.pem"));
        assert!(matches_public_key_name("verify_key"));
        assert!(!matches_public_key_name("secret"));
        assert!(!matches_public_key_name("private_key"));
    }

    #[test]
    fn auth_flow_function_lexicon() {
        assert!(matches_auth_flow_function("authenticate_user"));
        assert!(matches_auth_flow_function("login_handler"));
        assert!(matches_auth_flow_function("decode_token"));
        assert!(matches_auth_flow_function("verify_jwt"));
        assert!(matches_auth_flow_function("get_session"));
        assert!(matches_auth_flow_function("auth_middleware"));
        assert!(!matches_auth_flow_function("calculate_total"));
    }

    #[test]
    fn auth_flow_path_lexicon() {
        assert!(path_matches_auth_flow("/app/auth/jwt.py"));
        assert!(path_matches_auth_flow("src/security/decode.py"));
        assert!(path_matches_auth_flow("middleware/jwt_check.py"));
        assert!(!path_matches_auth_flow("src/payments/checkout.py"));
    }

    #[test]
    fn test_function_lexicon() {
        assert!(matches_test_function("test_jwt_decode"));
        assert!(matches_test_function("jwt_test"));
        assert!(matches_test_function("setup_fixture"));
        assert!(!matches_test_function("decode_token"));
    }

    // ─── Extract helpers ───
    #[test]
    fn extract_jwt_safe_with_reason() {
        assert_eq!(
            extract_jwt_safe_reason(
                "jwt.decode(token, key)  # repotoire: jwt-safe[verified-at-edge]"
            ),
            Some("verified-at-edge".to_string())
        );
    }

    #[test]
    fn extract_jwt_safe_without_reason() {
        assert_eq!(
            extract_jwt_safe_reason("jwt.decode(token, key)  # repotoire: jwt-safe"),
            Some("unspecified".to_string())
        );
    }

    #[test]
    fn extract_jwt_vulnerable_with_source() {
        assert_eq!(
            extract_jwt_vulnerable_source(
                "jwt.decode(token, key)  # repotoire: jwt-vulnerable[alg-from-header]"
            ),
            Some("alg-from-header".to_string())
        );
    }

    #[test]
    fn extract_jwt_safe_ignores_other_kinds() {
        assert_eq!(
            extract_jwt_safe_reason("subprocess.run(...)  # repotoire: command-static[ok]"),
            None
        );
        assert_eq!(
            extract_jwt_safe_reason("ET.parse(blob)  # repotoire: xxe-safe[ok]"),
            None
        );
        assert_eq!(
            extract_jwt_safe_reason("requests.get(url)  # repotoire: ssrf-safe[ok]"),
            None
        );
    }

    #[test]
    fn extract_jwt_vulnerable_ignores_other_kinds() {
        assert_eq!(
            extract_jwt_vulnerable_source(
                "requests.get(url)  # repotoire: ssrf-vulnerable[audited]"
            ),
            None
        );
    }

    // ─── JwtApi helpers ───
    #[test]
    fn jwt_api_is_python_includes_recognized_libs() {
        assert!(JwtApi::PyJwt.is_python());
        assert!(JwtApi::PythonJose.is_python());
        assert!(JwtApi::JwtVerifier.is_python());
        assert!(!JwtApi::Unknown.is_python());
    }

    #[test]
    fn jwt_api_callee_label_is_stable() {
        assert_eq!(JwtApi::PyJwt.callee_label(), "jwt");
        assert_eq!(JwtApi::PythonJose.callee_label(), "python-jose");
        assert_eq!(JwtApi::JwtVerifier.callee_label(), "JWTVerifier");
        assert_eq!(JwtApi::Unknown.callee_label(), "JWT client");
    }
}