repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
//! Dual-branch predictor for Python NoSQL-injection call sites.
//!
//! Implements decisions D1 (weights, with **trifecta** Step 1.5 collapses:
//! D1.a Typed-Query Benign collapse + D1.b Operator RealBug collapse +
//! D1.c Dict-Expansion RealBug collapse) and D3 (severity) from
//! `docs/superpowers/specs/2026-05-09-dual-branch-phase2-nosql-injection-decisions.md`.
//!
//! # What this module does
//!
//! Given a Python pymongo / motor query call site
//! (`users.find_one({...})`, `db.users.aggregate([...])`, etc.), 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).
//!
//! # Trifecta Step 1.5 collapse — the structural novelty of 2i
//!
//! Phase 2i extends 2h's bidirectional collapse pattern with a **third
//! structural-collapse trigger** on the RealBug side:
//!
//! - **D1.a — Typed-Query Benign-direction collapse.** When the query
//!   dict literal has no dangerous operators, no dict-expansion, and
//!   all user-input values are wrapped in a type-narrowing cast
//!   (`str(...)`, `ObjectId(...)`, `int(...)`, `float(...)`, pydantic
//!   model instantiation), commit to **Benign / Info** regardless of
//!   additive signals. Same family as 2e's defusedxml and 2f's advocate.
//!
//! - **D1.b — Operator RealBug-direction collapse.** When the query
//!   dict literal contains `$where` / `$function` / `$expr` /
//!   `$accumulator` with a user-input expression value (typically an
//!   f-string or string-concat into the operator's JS code), commit to
//!   **RealBug / Critical**. Same family as 2g's `'none'` collapse.
//!
//! - **D1.c — Dict-Expansion RealBug-direction collapse.** When the
//!   query body is `**request.json` / `**req.body` / `**request.get_json()`
//!   (dict-expansion of raw user input), commit to **RealBug / Critical**.
//!   The textbook auth-bypass vector.
//!
//! # Architectural framing: 2i is primarily FP-reduction
//!
//! Phase 2i is the **third architectural use case** for dual-branch:
//!
//! 1. **2e/2f**: Benign-collapse-only (library identity).
//! 2. **2g/2h**: Bidirectional, both directions surface new findings.
//! 3. **2i** (this phase): Bidirectional, **primarily FP reduction** on
//!    the Benign side. The legacy scanner catches the unsafe shapes;
//!    the dual-branch's headline contribution is recognizing the
//!    structurally safe pymongo idioms and collapsing them to Info.
//!
//! # The D5.2 honest-review-driven UserInputSource split
//!
//! The pre-implementation walk-through surfaced that the framing
//! "Python is structurally safer than JS for MongoDB queries" is
//! **partly wrong**. Python's `request.form`/`request.args` return
//! strings (safer), but `request.json`/`request.get_json()` return
//! parsed JSON (dict/list/scalar) — pymongo will faithfully serialize
//! a dict-typed value as a MongoDB operator expression. The auth-
//! bypass attack works in Python exactly as in JS for `request.json`.
//!
//! The fix: separate the user-input source into two lexicons with
//! asymmetric weights ([`W_USER_INPUT_TYPED_STRING_NEARBY`] = +0.20
//! vs [`W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY`] = -0.30). See D5.2
//! in the decisions doc.
//!
//! # Sign convention
//!
//! `weight > 0` leans **Benign**; `weight < 0` leans **RealBug**.
//!
//! # Severity mapping (D3)
//!
//! - Predicted **RealBug** via the Operator collapse (D1.b) → `Critical`.
//! - Predicted **RealBug** via the Dict-Expansion collapse (D1.c) → `Critical`.
//! - Predicted **RealBug** otherwise → `Critical` (`sum <= -0.7`),
//!   `High` (`-0.7 < sum <= -0.4`), `Medium` (shallow negative or tiebreak).
//! - Predicted **Benign** (via Typed-Query collapse OR weighted-positive)
//!   → `Severity::Info`.
//!
//! # Why these weights
//!
//! See decision **D1** (with §6 D1 amendment for the trifecta
//! 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;

// ─────────────────────────────────────────────────────────────────────────────
// NosqlApi — the API-classification enum for Phase 2i
// ─────────────────────────────────────────────────────────────────────────────

/// Which structural shape the pymongo/motor query call site has, and
/// what safety contract that shape provides.
///
/// The classification drives the Step 1.5 trifecta collapses:
/// `TypedValueQuery` → D1.a Benign collapse; `OperatorInjection` →
/// D1.b RealBug collapse; `DictExpansion` → D1.c RealBug collapse;
/// `Ambiguous` → fall through to weighted scoring.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum NosqlApi {
    /// Typed-value query: dict literal with no dangerous operators,
    /// no `**`-expansion, and either no user input OR all user-input
    /// values are wrapped in a type-narrowing cast (`str`, `ObjectId`,
    /// `int`, `float`, pydantic). Triggers D1.a Benign-direction collapse.
    TypedValueQuery,
    /// Operator-injection query: dict literal contains a dangerous
    /// server-side operator (`$where`, `$function`, `$expr`,
    /// `$accumulator`) with a user-input expression value. Triggers
    /// D1.b RealBug-direction collapse.
    OperatorInjection,
    /// Dict-expansion query: the query body is `**request.json` /
    /// `**req.body` (the attacker controls every key and value).
    /// Triggers D1.c RealBug-direction collapse.
    DictExpansion,
    /// Recognized pymongo / motor query but the safety shape depends
    /// on additional context the v0 predictor cannot statically
    /// resolve. Falls through to weighted scoring.
    Ambiguous,
    /// Recognized query call but not classified. Treated as Ambiguous
    /// for scoring; preserved as a distinct variant for labels.
    Unknown,
}

impl NosqlApi {
    /// Human-readable label for the API used in titles/descriptions.
    pub(super) fn callee_label(self) -> &'static str {
        match self {
            NosqlApi::TypedValueQuery => "typed-value-pymongo-query",
            NosqlApi::OperatorInjection => "operator-injection-pymongo-query",
            NosqlApi::DictExpansion => "dict-expansion-pymongo-query",
            NosqlApi::Ambiguous => "ambiguous-pymongo-query",
            NosqlApi::Unknown => "pymongo query",
        }
    }

    /// True iff the API is one of the recognized pymongo query shapes.
    /// Gates the Phase 2i dual-branch emission path: only recognized
    /// Python sites get the predictor-aware shape; non-Python and
    /// unrecognized calls still go through the legacy regex scanner
    /// per decisions D5.1 / D5.5.
    #[cfg(test)]
    pub(super) fn is_recognized(self) -> bool {
        !matches!(self, NosqlApi::Unknown)
    }

    /// True iff this shape triggers the D1.a Typed-Query Benign collapse.
    pub(super) fn collapses_typed_query(self) -> bool {
        matches!(self, NosqlApi::TypedValueQuery)
    }

    /// True iff this shape triggers the D1.b Operator RealBug collapse.
    pub(super) fn collapses_operator(self) -> bool {
        matches!(self, NosqlApi::OperatorInjection)
    }

    /// True iff this shape triggers the D1.c Dict-Expansion RealBug collapse.
    pub(super) fn collapses_dict_expansion(self) -> bool {
        matches!(self, NosqlApi::DictExpansion)
    }
}

/// The two user-input source families distinguished by the D5.2
/// honest-review finding.
///
/// Python pymongo is **structurally safer** for `TypedString` sources
/// (`request.form`, `request.args`, explicit `str()` cast) than for
/// `UnstructuredJson` sources (`request.json`, `request.get_json()`,
/// `request.body`). pymongo serializes whatever Python value it gets;
/// strings become BSON strings (safe), dicts become BSON query
/// expressions (operator injection). The asymmetric weights in
/// [`W_USER_INPUT_TYPED_STRING_NEARBY`] vs
/// [`W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY`] encode this distinction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) enum UserInputSource {
    /// `request.form`, `request.args`, `request.values`, explicit
    /// `str(...)` cast of user input. Always-string typing → safe.
    TypedString,
    /// `request.json`, `request.get_json()`, `request.body`, raw
    /// `json.loads(request.data)`. Dict/list/scalar typing → operator-
    /// injection-vulnerable.
    UnstructuredJson,
    /// No user-input identifier detected within ±10 lines of the call.
    #[default]
    None,
}

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

// TUNABLE: see Phase 3 misprediction logging.
//
// Sign convention: positive leans Benign, negative leans RealBug.
//
// Calibration target (per decisions doc §6 worked examples Case A-G):
//   A. users.find_one({"username": req.json["user"]}) in handler:
//      Ambiguous → -0.30 (UnstructuredJson) - 0.20 (handler) = -0.50
//      → RealBug High. ✅
//   B. users.find_one({"username": str(req.form["user"])}):
//      TypedValueQuery collapse → Benign Info. ✅
//   C. users.find_one({"$where": f"... '{req.form['user']}'"}):
//      OperatorInjection collapse → RealBug Critical. ✅
//   D. users.find_one({"role": {"$ne": "admin"}}) (no user input):
//      Ambiguous → +0.10 (developer-written operator) = +0.10
//      → Benign Info. ✅ HEADLINE FP REDUCTION.
//   E. users.find_one({**req.json}):
//      DictExpansion collapse → RealBug Critical. ✅
//   F. users.find({"_id": ObjectId(req.form["id"])}):
//      TypedValueQuery collapse → Benign Info. ✅

/// Informational weight for the D1.a Typed-Query Step 1.5 Benign-direction
/// collapse.
pub(super) const W_API_TYPED_QUERY_COLLAPSE: f32 = 1.0;

/// Informational weight for the D1.b Operator Step 1.5 RealBug-direction
/// collapse.
pub(super) const W_API_OPERATOR_COLLAPSE: f32 = -1.0;

/// Informational weight for the D1.c Dict-Expansion Step 1.5 RealBug-
/// direction collapse.
pub(super) const W_API_DICT_EXPANSION_COLLAPSE: f32 = -1.0;

/// User input from a TypedString source (`request.form`, `request.args`,
/// `request.values`, explicit `str()` cast). Positive — Python str-
/// typed input flowing into pymongo is structurally safe because BSON
/// String serialization cannot become operator interpretation.
pub(super) const W_USER_INPUT_TYPED_STRING_NEARBY: f32 = 0.20;

/// User input from an UnstructuredJson source (`request.json`,
/// `request.get_json()`, `request.body`, raw `json.loads`). Negative —
/// Python dict-typed input flowing into pymongo IS operator-injection-
/// vulnerable because pymongo will faithfully serialize a dict value
/// as a query operator expression. This is the D5.2 honest-review-
/// driven distinction.
pub(super) const W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY: f32 = -0.30;

/// Query dict literal contains `$regex` field with a value derived
/// from user input. Negative — user-supplied regex enables ReDoS
/// via crafted exponential-backtracking patterns.
pub(super) const W_HAS_DOLLAR_REGEX_WITH_USER_INPUT: f32 = -0.30;

/// Query dict literal contains `$ne` / `$gt` / `$lt` / `$in` operator
/// whose value is a **literal** (not user-derived). Positive (soft) —
/// the developer is the author of the operator semantics; this is
/// normal MongoDB query construction, NOT injection. **The headline
/// FP-reduction signal for Phase 2i.**
pub(super) const W_DEVELOPER_WRITTEN_OPERATOR: f32 = 0.10;

/// `ObjectId(...)`, `int(...)`, `float(...)`, `bool(...)`, `UUID(...)`,
/// or pydantic model instantiation appears within ±5 lines of the
/// call. Positive — strong type-narrowing signal even when not part
/// of the D1.a collapse pattern.
pub(super) const W_OBJECTID_OR_TYPE_CAST_NEARBY: f32 = 0.40;

/// Enclosing function is a route handler. Negative; lighter than
/// 2e–2h's `-0.30` because Python pymongo is structurally safer than
/// the deserialize/XXE/SSRF families.
pub(super) const W_ENCLOSING_ROUTE_HANDLER: f32 = -0.20;

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

/// Enclosing function name contains `_trusted`, `_admin`, `_internal`,
/// `_validated`, `_signed`. Positive (soft).
pub(super) const W_TRUST_BOUNDARY_NAME: f32 = 0.10;

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

/// User-input identifier substrings for the `TypedString` source family.
/// These return Python `str` objects deterministically.
pub(super) const TYPED_STRING_USER_INPUT_SUBSTRINGS: &[&str] = &[
    "request.form",
    "request.args",
    "request.values",
    "request.cookies",
    "request.headers",
    "request.path_params",
];

/// User-input identifier substrings for the `UnstructuredJson` source
/// family. These return parsed JSON (dict / list / scalar). Pymongo
/// will faithfully serialize a dict value as a query operator
/// expression — operator-injection-vulnerable.
pub(super) const UNSTRUCTURED_JSON_USER_INPUT_SUBSTRINGS: &[&str] = &[
    "request.json",
    "request.get_json",
    "request.body",
    "request.data",
    "flask.request.json",
    "self.request.body",
];

/// Route-handler decorator substrings (line-level check on decorator
/// lines preceding the function definition).
pub(super) const ROUTE_HANDLER_DECORATOR_SUBSTRINGS: &[&str] = &[
    "@app.route",
    "@app.get",
    "@app.post",
    "@app.put",
    "@app.delete",
    "@router.get",
    "@router.post",
    "@router.put",
    "@router.delete",
    "@view",
    "@api_view",
    "@require_http_methods",
    "@csrf_exempt",
    "@login_required",
    "@blueprint.route",
];

/// Function-name substrings that suggest a route handler.
pub(super) const ROUTE_HANDLER_NAME_SUBSTRINGS: &[&str] =
    &["_handler", "_endpoint", "_view", "_route"];

/// Function-name substrings suggesting a trust boundary has already
/// been crossed.
pub(super) const TRUST_BOUNDARY_NAME_SUBSTRINGS: &[&str] =
    &["_trusted", "_admin", "_internal", "_validated", "_signed"];

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

/// Type-narrowing cast / validation identifier substrings. Presence of
/// any of these within ±5 lines of the call is the
/// `W_OBJECTID_OR_TYPE_CAST_NEARBY` signal, AND is also a precondition
/// for the D1.a typed-query collapse (the evidence extractor checks
/// that every user-input value position has one of these wrappers).
pub(super) const TYPE_CAST_SUBSTRINGS: &[&str] = &[
    "ObjectId(",
    "bson.ObjectId(",
    "int(",
    "float(",
    "bool(",
    "UUID(",
    "uuid.UUID(",
    ".parse_obj(",
    ".model_validate(",
    "schema.load(",
];

/// Dangerous server-side MongoDB operators that trigger D1.b
/// OperatorInjection collapse when paired with user input.
pub(super) const DANGEROUS_OPERATORS: &[&str] = &["$where", "$function", "$expr", "$accumulator"];

/// "Developer-grade" MongoDB operators — these are legitimate query
/// construction when the value is a literal (not user-derived).
/// The presence of one of these with a literal value triggers
/// [`W_DEVELOPER_WRITTEN_OPERATOR`]. The presence with a user-derived
/// value falls through (an operator-injection concern, but not the
/// $where-grade RCE).
pub(super) const DEVELOPER_OPERATORS: &[&str] = &[
    "$ne", "$gt", "$gte", "$lt", "$lte", "$in", "$nin", "$exists",
];

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

/// Structured evidence extracted from a Python pymongo query call
/// site.
///
/// Populated by `evidence::extract_python_evidence` (Commit 4) and
/// consumed by [`predict`].
#[derive(Debug, Clone, Default, PartialEq)]
pub(super) struct Evidence {
    /// Which pymongo query shape the call site exhibits, post-
    /// structural-classification.
    pub api: Option<NosqlApi>,

    /// The raw callee text (`users.find_one`, `db.users.aggregate`,
    /// etc.). Used for the title/description; the predictor itself
    /// only reads `api`.
    pub callee_label: Option<String>,

    /// 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 for diagnostics; no weight in this phase.
    pub file_path: Option<String>,

    /// Which user-input source family appears within ±10 lines of the
    /// call. See [`UserInputSource`].
    pub user_input_source: UserInputSource,

    /// Enclosing function is decorated with a recognized route-handler
    /// decorator (e.g. `@app.route`) OR has a recognized handler name.
    pub enclosing_route_handler: bool,

    /// Enclosing function name suggests a trust boundary has already
    /// been crossed (`_trusted`, `_admin`, `_internal`, `_validated`,
    /// `_signed`).
    pub trust_boundary_name: bool,

    /// Query dict literal contains `$regex` field with a value derived
    /// from user input. Triggers [`W_HAS_DOLLAR_REGEX_WITH_USER_INPUT`].
    pub has_dollar_regex_with_user_input: bool,

    /// Query dict literal contains `$ne`/`$gt`/`$lt`/`$in` operator
    /// with a **literal** value (not user-derived). Triggers
    /// [`W_DEVELOPER_WRITTEN_OPERATOR`].
    pub has_developer_written_operator: bool,

    /// Type-narrowing cast (`ObjectId`, `int`, `float`, pydantic) or
    /// validation appears within ±5 lines of the call. Triggers
    /// [`W_OBJECTID_OR_TYPE_CAST_NEARBY`].
    pub type_cast_nearby: bool,

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

    /// `Some(source)` if a `# repotoire: nosql-vulnerable[<source>]`
    /// annotation appears on the call line. **Collapsing**.
    pub nosql_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.** `nosql_safe_annotation` →
///    Benign; `nosql_vulnerable_annotation` → RealBug.
/// 2. **Step 1.5 D1.a Typed-Query Benign collapse.** If `api ==
///    NosqlApi::TypedValueQuery`, commit to **Benign / Info**.
/// 3. **Step 1.5 D1.b Operator RealBug collapse.** If `api ==
///    NosqlApi::OperatorInjection`, commit to **RealBug / Critical**.
/// 4. **Step 1.5 D1.c Dict-Expansion RealBug collapse.** If `api ==
///    NosqlApi::DictExpansion`, commit to **RealBug / Critical**.
/// 5. **Weighted scoring** (Ambiguous / Unknown only). Sum weights.
/// 6. **Tiebreak**: sum exactly 0.0 → predict RealBug. Conservative
///    default for security findings.
pub(super) fn predict(evidence: &Evidence) -> Prediction {
    let api = evidence.api.unwrap_or(NosqlApi::Unknown);
    let api_label = api.callee_label();

    // ── Step 1: collapsing annotations. ──
    if let Some(reason) = &evidence.nosql_safe_annotation {
        return collapse(
            BranchLabel::Benign,
            api,
            0.0,
            ResolutionSignal {
                kind: ResolutionKind::SourceAnnotation {
                    syntax: format!("# repotoire: nosql-safe[{reason}]"),
                },
                description: format!(
                    "`nosql-safe[{reason}]` annotation declares this \
                     pymongo query as safe (pydantic-validated, cross-\
                     statement type cast, audited internal source, etc.); \
                     the finding collapses to Info."
                ),
                example: Some(format!(
                    "{api_label}(...)  # repotoire: nosql-safe[{reason}]"
                )),
                collapses_to: BranchLabel::Benign,
            },
            PredictionReason {
                kind: PredictionReasonKind::Custom {
                    description: format!("nosql-safe[{reason}] annotation"),
                },
                weight: 1.0,
                note: format!(
                    "Annotated as safely-constructed ({reason}); not a NoSQL injection risk."
                ),
            },
        );
    }
    if let Some(source) = &evidence.nosql_vulnerable_annotation {
        return collapse(
            BranchLabel::RealBug,
            api,
            -1.0,
            ResolutionSignal {
                kind: ResolutionKind::SourceAnnotation {
                    syntax: format!("# repotoire: nosql-vulnerable[{source}]"),
                },
                description: format!(
                    "`nosql-vulnerable[{source}]` annotation declares this \
                     pymongo query as exposed (third-party shim, helper-\
                     assembled-query the predictor can't trace, audited-\
                     untrusted, etc.); the finding stays at the existing \
                     severity."
                ),
                example: Some(format!(
                    "{api_label}(...)  # repotoire: nosql-vulnerable[{source}]"
                )),
                collapses_to: BranchLabel::RealBug,
            },
            PredictionReason {
                kind: PredictionReasonKind::Custom {
                    description: format!("nosql-vulnerable[{source}] annotation"),
                },
                weight: -1.0,
                note: format!("Annotated as nosql-exposed (source: {source})."),
            },
        );
    }

    // ── Step 1.5a: D1.a Typed-Query Benign-direction collapse. ──
    if api.collapses_typed_query() {
        return collapse(
            BranchLabel::Benign,
            api,
            0.0,
            ResolutionSignal {
                kind: ResolutionKind::StructuralPattern {
                    description:
                        "Typed-value pymongo query (no dangerous operators, all user-input values cast)"
                            .to_string(),
                },
                description: "The query passes user input as a structured \
                     typed value: every user-derived value is wrapped in \
                     a type-narrowing cast (`str(...)`, `ObjectId(...)`, \
                     `int(...)`, pydantic-validated model), the dict literal \
                     has no dangerous server-side operators (`$where`, \
                     `$function`, `$expr`), and there is no `**`-expansion \
                     of raw user input. pymongo serializes Python `str` \
                     values to BSON String — there is no operator-\
                     interpretation path. The query is safe by structural \
                     construction."
                    .to_string(),
                example: Some(
                    "users.find_one({\"username\": str(request.form['user'])})  # safe"
                        .to_string(),
                ),
                collapses_to: BranchLabel::Benign,
            },
            PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description: "Typed-value pymongo query".to_string(),
                },
                weight: W_API_TYPED_QUERY_COLLAPSE,
                note: "The call site is a structurally-typed pymongo \
                       query: no dangerous operators, no `**`-expansion, \
                       and all user-input values are cast (str / ObjectId \
                       / int / pydantic). Phase 2i D1.a amendment: \
                       trifecta Step 1.5 collapse — Benign direction. \
                       This is the headline FP-reduction case for Phase 2i."
                    .to_string(),
            },
        );
    }

    // ── Step 1.5b: D1.b Operator RealBug-direction collapse. ──
    if api.collapses_operator() {
        return collapse(
            BranchLabel::RealBug,
            api,
            -1.0,
            ResolutionSignal {
                kind: ResolutionKind::StructuralPattern {
                    description:
                        "Dangerous server-side operator ($where/$function/$expr) with user input"
                            .to_string(),
                },
                description: "The query dict literal contains a dangerous \
                     server-side MongoDB operator (`$where`, `$function`, \
                     `$expr`, `$accumulator`) whose value derives from \
                     user input. `$where` executes JavaScript on the \
                     database server; `$function` and `$accumulator` \
                     allow aggregation-pipeline JavaScript execution; \
                     `$expr` with a user-controlled dict enables \
                     aggregation-expression injection. The textbook \
                     CWE-943 RCE shape regardless of language."
                    .to_string(),
                example: Some(
                    "users.find_one({\"$where\": f\"this.name=='{request.form['name']}'\"})"
                        .to_string(),
                ),
                collapses_to: BranchLabel::RealBug,
            },
            PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description: "Dangerous server-side operator with user input".to_string(),
                },
                weight: W_API_OPERATOR_COLLAPSE,
                note: "The query embeds a dangerous server-side operator \
                       (`$where` / `$function` / `$expr` / `$accumulator`) \
                       with a user-input expression value. Phase 2i D1.b \
                       amendment: trifecta Step 1.5 collapse — RealBug \
                       direction via dangerous-operator structural pattern. \
                       Server-side JavaScript / aggregation-expression \
                       execution."
                    .to_string(),
            },
        );
    }

    // ── Step 1.5c: D1.c Dict-Expansion RealBug-direction collapse. ──
    if api.collapses_dict_expansion() {
        return collapse(
            BranchLabel::RealBug,
            api,
            -1.0,
            ResolutionSignal {
                kind: ResolutionKind::StructuralPattern {
                    description: "Dict-expansion of raw user input into pymongo query".to_string(),
                },
                description: "The query body is a `**`-expansion of raw \
                     user input (`request.json`, `request.get_json()`, \
                     `request.body`). The attacker controls every key \
                     and value in the resulting query dict — they can \
                     supply `{\"$ne\": null}` to bypass equality checks, \
                     `{\"$where\": \"...\"}` to inject JavaScript, etc. \
                     The textbook NoSQL auth-bypass vector."
                    .to_string(),
                example: Some(
                    "users.find_one({**request.get_json()})  # auth bypass via $ne".to_string(),
                ),
                collapses_to: BranchLabel::RealBug,
            },
            PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description: "Dict-expansion of raw user input".to_string(),
                },
                weight: W_API_DICT_EXPANSION_COLLAPSE,
                note: "The query body is `**request.json` / `**req.body` / \
                       similar — the attacker controls every key. Phase 2i \
                       D1.c amendment: trifecta Step 1.5 collapse — RealBug \
                       direction via dict-expansion structural pattern. \
                       This is the canonical NoSQL auth-bypass shape."
                    .to_string(),
            },
        );
    }

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

    match evidence.user_input_source {
        UserInputSource::TypedString => {
            sum += W_USER_INPUT_TYPED_STRING_NEARBY;
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description:
                        "user input from typed-string source (request.form / request.args)"
                            .to_string(),
                },
                weight: W_USER_INPUT_TYPED_STRING_NEARBY,
                note: "User input from a typed-string source \
                       (`request.form`, `request.args`, `request.values`). \
                       Python str values flowing into pymongo become BSON \
                       String — no operator interpretation possible. \
                       Structural-safety signal (D5.2 honest-review \
                       finding: this is the source family where Python is \
                       genuinely safer than JS)."
                    .to_string(),
            });
        }
        UserInputSource::UnstructuredJson => {
            sum += W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY;
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description:
                        "user input from unstructured-JSON source (request.json / request.body)"
                            .to_string(),
                },
                weight: W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY,
                note: "User input from an unstructured-JSON source \
                       (`request.json`, `request.get_json()`, \
                       `request.body`). The attacker can send a dict \
                       value (e.g. `{\"$ne\": null}`) and pymongo will \
                       faithfully serialize it as a MongoDB operator \
                       expression. **Python is NOT structurally safer \
                       than JS for this source family.** D5.2 honest-\
                       review finding."
                    .to_string(),
            });
        }
        UserInputSource::None => {}
    }

    if evidence.has_dollar_regex_with_user_input {
        sum += W_HAS_DOLLAR_REGEX_WITH_USER_INPUT;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "$regex field with user-supplied pattern".to_string(),
            },
            weight: W_HAS_DOLLAR_REGEX_WITH_USER_INPUT,
            note: "Query contains a `$regex` field whose pattern is \
                   user-derived. Allowing user-supplied regex enables \
                   ReDoS via crafted exponential-backtracking patterns."
                .to_string(),
        });
    }

    if evidence.has_developer_written_operator {
        sum += W_DEVELOPER_WRITTEN_OPERATOR;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "developer-written $ne/$gt/$lt operator with literal value"
                    .to_string(),
            },
            weight: W_DEVELOPER_WRITTEN_OPERATOR,
            note: "Query contains `$ne`/`$gt`/`$lt`/`$in` with a literal \
                   value (not user-derived). The developer is the author \
                   of the operator semantics — normal MongoDB query \
                   construction, NOT operator injection. **This is the \
                   headline FP-reduction signal for Phase 2i: the legacy \
                   detector flags this idiom; the predictor doesn't.**"
                .to_string(),
        });
    }

    if evidence.type_cast_nearby {
        sum += W_OBJECTID_OR_TYPE_CAST_NEARBY;
        reasons.push(PredictionReason {
            kind: PredictionReasonKind::StructuralPattern {
                description: "type-narrowing cast nearby (ObjectId / int / pydantic)".to_string(),
            },
            weight: W_OBJECTID_OR_TYPE_CAST_NEARBY,
            note: "`ObjectId(...)`, `int(...)`, `float(...)`, or pydantic \
                   model instantiation appears within ±5 lines of the \
                   call. Strong type-narrowing signal — even when not \
                   part of the D1.a collapse pattern, the presence of \
                   these casts indicates the developer is type-asserting \
                   user input before query construction."
                .to_string(),
        });
    }

    if evidence.enclosing_route_handler {
        sum += W_ENCLOSING_ROUTE_HANDLER;
        if let Some(fn_name) = &evidence.enclosing_function {
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::EnclosingScope {
                    scope_kind: "route_handler".to_string(),
                    name: fn_name.clone(),
                },
                weight: W_ENCLOSING_ROUTE_HANDLER,
                note: "Enclosing function is a route handler (decorator \
                       or naming convention); higher prior on attacker- \
                       reachable query code. Lighter weight than 2e–2h \
                       because Python pymongo is structurally safer."
                    .to_string(),
            });
        } else {
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::StructuralPattern {
                    description: "enclosing route handler context".to_string(),
                },
                weight: W_ENCLOSING_ROUTE_HANDLER,
                note: "Call site is in a route-handler context.".to_string(),
            });
        }
    }

    if evidence.trust_boundary_name {
        sum += W_TRUST_BOUNDARY_NAME;
        if let Some(fn_name) = &evidence.enclosing_function {
            reasons.push(PredictionReason {
                kind: PredictionReasonKind::EnclosingScope {
                    scope_kind: "trust_boundary".to_string(),
                    name: fn_name.clone(),
                },
                weight: W_TRUST_BOUNDARY_NAME,
                note: "Enclosing function name contains a trust-boundary \
                       keyword (_trusted/_admin/_internal/_validated/_signed) \
                       — developer-authored signal that data has been verified."
                    .to_string(),
            });
        }
    }

    if let Some(fn_name) = &evidence.enclosing_function {
        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."
                ),
            });
        }
    }

    // ── 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
// ─────────────────────────────────────────────────────────────────────────────

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

/// True iff the function name matches any route-handler naming
/// convention. The evidence extractor combines this with decorator
/// detection.
pub(super) fn matches_route_handler_name(name: &str) -> bool {
    let lower = name.to_lowercase();
    ROUTE_HANDLER_NAME_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
}

/// True iff the function name contains a trust-boundary keyword.
pub(super) fn matches_trust_boundary_name(name: &str) -> bool {
    let lower = name.to_lowercase();
    TRUST_BOUNDARY_NAME_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
}

/// True iff a line (intended to be a decorator line preceding a
/// function definition) matches any route-handler decorator pattern.
pub(super) fn matches_route_handler_decorator(line: &str) -> bool {
    let trimmed = line.trim();
    ROUTE_HANDLER_DECORATOR_SUBSTRINGS
        .iter()
        .any(|sub| trimmed.starts_with(sub))
}

/// Classify a line's user-input source family. Returns the first
/// match found (UnstructuredJson takes priority over TypedString if
/// both appear on the same line, because the dict-typed source is
/// the dominant safety concern). Returns `None` if no recognized
/// user-input identifier appears.
pub(super) fn classify_user_input_source(line: &str) -> UserInputSource {
    let lower = line.to_lowercase();
    // UnstructuredJson takes priority — it's the operator-injection
    // vulnerable source family.
    for s in UNSTRUCTURED_JSON_USER_INPUT_SUBSTRINGS {
        if lower.contains(s) {
            return UserInputSource::UnstructuredJson;
        }
    }
    for s in TYPED_STRING_USER_INPUT_SUBSTRINGS {
        if lower.contains(s) {
            return UserInputSource::TypedString;
        }
    }
    UserInputSource::None
}

/// True iff `line` contains any recognized type-narrowing cast or
/// validation identifier (ObjectId, int, float, pydantic).
pub(super) fn line_contains_type_cast(line: &str) -> bool {
    TYPE_CAST_SUBSTRINGS.iter().any(|s| line.contains(s))
}

/// True iff `line` contains any of the dangerous server-side MongoDB
/// operators (`$where`, `$function`, `$expr`, `$accumulator`).
pub(super) fn line_contains_dangerous_operator(line: &str) -> bool {
    DANGEROUS_OPERATORS.iter().any(|s| line.contains(s))
}

/// True iff `line` contains any of the developer-grade MongoDB
/// operators (`$ne`, `$gt`, `$lt`, etc.).
pub(super) fn line_contains_developer_operator(line: &str) -> bool {
    DEVELOPER_OPERATORS.iter().any(|s| line.contains(s))
}

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

fn build_prediction(
    predicted: BranchLabel,
    api: NosqlApi,
    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 Operator / Dict-Expansion collapse
/// paths):
///
/// - `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 NoSQL injection via {api_label}"),
        BranchLabel::Benign => {
            format!("Safe pymongo query ({api_label}) — informational")
        }
    }
}

fn description_for_branch(label: BranchLabel, api_label: &str) -> String {
    match label {
        BranchLabel::RealBug => format!(
            "The `{api_label}` call appears to construct a MongoDB query \
             with attacker-reachable input flowing into a dangerous \
             operator (`$where`/`$function`/`$expr`/`$accumulator`) or via \
             dict-expansion of raw user input. NoSQL injection allows \
             attackers to bypass authentication, extract data via \
             `$regex` probing, execute arbitrary JavaScript on the \
             database server (via `$where`/`$function`), or trigger ReDoS."
        ),
        BranchLabel::Benign => format!(
            "The `{api_label}` call appears to construct a typed-value \
             MongoDB query (no dangerous operators, no `**`-expansion, \
             user-input values cast to BSON-safe types via `str`, \
             `ObjectId`, pydantic). The call 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(
            "Sanitize the query construction:\n\n\
             ```python\n\
             # Instead of:\n\
             users.find_one({\"$where\": f\"this.name=='{req.form['n']}'\"})\n\
             users.find_one({**request.get_json()})\n\
             \n\
             # Use typed-value queries:\n\
             users.find_one({\"name\": str(request.form['n'])})\n\
             users.find_one({\"_id\": ObjectId(request.form['id'])})\n\
             \n\
             # Or pydantic-validate the payload first:\n\
             class Query(BaseModel):\n\
             \x20   name: str\n\
             q = Query.model_validate(request.get_json())\n\
             users.find_one({\"name\": q.name})\n\
             ```\n\n\
             If the call is intentionally constructing a complex query \
             that the predictor cannot trace (cross-statement assembly, \
             helper-built filter, etc.), annotate the call site with \
             `# repotoire: nosql-safe[<reason>]` to collapse the finding \
             to Info."
                .to_string(),
        ),
        BranchLabel::Benign => Some(
            "If this is intentional safe usage, annotate \
             `# repotoire: nosql-safe[<reason>]` to collapse the finding \
             to Info definitively. If the alternative branch is correct \
             (the query IS exposed to attacker-controlled operators via a \
             path the predictor missed), audit the call's input source \
             classification and consider tightening the type cast on \
             user-derived values."
                .to_string(),
        ),
    }
}

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

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

/// If `line` carries `# repotoire: nosql-vulnerable[<source>]`, return
/// the source. Defaults to `"unspecified"` if no arg supplied.
pub(super) fn extract_nosql_vulnerable_source(line: &str) -> Option<String> {
    let ann = parse_python_comment(line)?;
    if ann.kind != "nosql-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 §6): UnstructuredJson + handler. ───
    #[test]
    fn case_a_request_json_in_handler_predicts_realbug_high() {
        // -0.30 (UnstructuredJson) - 0.20 (handler) = -0.50 → High.
        // The D5.2 honest-review case.
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            user_input_source: UserInputSource::UnstructuredJson,
            enclosing_route_handler: 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::High);
    }

    // ─── Worked example B (decisions §6): TypedValueQuery collapse. ───
    #[test]
    fn case_b_typed_query_collapse_dominates_handler_signal() {
        let evidence = Evidence {
            api: Some(NosqlApi::TypedValueQuery),
            user_input_source: UserInputSource::TypedString,
            enclosing_route_handler: true,
            enclosing_function: Some("login".to_string()),
            type_cast_nearby: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
        assert_eq!(p.predicted_severity, Severity::Info);
        assert_eq!(p.reasons.len(), 1);
        assert_eq!(p.resolutions.len(), 1);
        assert!(matches!(
            p.resolutions[0].kind,
            ResolutionKind::StructuralPattern { .. }
        ));
        assert_eq!(p.resolutions[0].collapses_to, BranchLabel::Benign);
    }

    // ─── Worked example C: $where with user input. ───
    #[test]
    fn case_c_where_operator_collapse_dominates() {
        let evidence = Evidence {
            api: Some(NosqlApi::OperatorInjection),
            user_input_source: UserInputSource::TypedString,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
        assert_eq!(p.resolutions.len(), 1);
        assert_eq!(p.resolutions[0].collapses_to, BranchLabel::RealBug);
    }

    // ─── Worked example D (HEADLINE FP REDUCTION): developer-written $ne. ───
    #[test]
    fn case_d_developer_written_operator_predicts_benign() {
        // +0.10 (developer-written) = +0.10 → Benign Info.
        // This is the headline FP-reduction signal for Phase 2i.
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            has_developer_written_operator: true,
            enclosing_function: Some("list_users".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
        assert_eq!(p.predicted_severity, Severity::Info);
    }

    // ─── Worked example E: dict-expansion of raw user input. ───
    #[test]
    fn case_e_dict_expansion_collapse_dominates() {
        let evidence = Evidence {
            api: Some(NosqlApi::DictExpansion),
            user_input_source: UserInputSource::UnstructuredJson,
            enclosing_route_handler: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
        assert_eq!(p.resolutions.len(), 1);
        assert_eq!(p.resolutions[0].collapses_to, BranchLabel::RealBug);
    }

    // ─── Worked example F: ObjectId cast. ───
    #[test]
    fn case_f_objectid_cast_typed_query_predicts_benign() {
        let evidence = Evidence {
            api: Some(NosqlApi::TypedValueQuery),
            user_input_source: UserInputSource::TypedString,
            type_cast_nearby: true,
            enclosing_route_handler: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
        assert_eq!(p.predicted_severity, Severity::Info);
    }

    // ─── D1.a Typed-Query collapse dominates every other signal ───
    #[test]
    fn typed_query_collapse_dominates_handler_and_user_input() {
        let evidence = Evidence {
            api: Some(NosqlApi::TypedValueQuery),
            user_input_source: UserInputSource::UnstructuredJson,
            enclosing_route_handler: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        // Note: the typed-query API classification implies the
        // evidence extractor already verified all user values are
        // cast. The collapse dominates.
        assert_eq!(p.predicted, BranchLabel::Benign);
    }

    // ─── D1.b Operator collapse dominates every other signal ───
    #[test]
    fn operator_collapse_dominates_typed_string_source() {
        let evidence = Evidence {
            api: Some(NosqlApi::OperatorInjection),
            user_input_source: UserInputSource::TypedString, // even safe source
            type_cast_nearby: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
    }

    // ─── Ambiguous: weighted scoring fires ───
    #[test]
    fn ambiguous_with_unstructured_json_and_handler_predicts_realbug_high() {
        // -0.30 - 0.20 = -0.50 → High (just over the -0.7 Critical threshold).
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            user_input_source: UserInputSource::UnstructuredJson,
            enclosing_route_handler: true,
            enclosing_function: Some("user_endpoint".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::High);
    }

    #[test]
    fn ambiguous_with_typed_string_predicts_benign() {
        // +0.20 → Benign.
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            user_input_source: UserInputSource::TypedString,
            enclosing_function: Some("get_user".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
    }

    #[test]
    fn ambiguous_test_function_predicts_benign() {
        // +0.15 (test) → Benign.
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            enclosing_function: Some("test_user_query".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
    }

    #[test]
    fn ambiguous_dollar_regex_with_user_input_predicts_realbug() {
        // -0.30 (regex) = -0.30 → Medium (between -0.4 and 0.0).
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            has_dollar_regex_with_user_input: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Medium);
    }

    #[test]
    fn ambiguous_type_cast_nearby_predicts_benign() {
        // +0.40 → Benign.
        let evidence = Evidence {
            api: Some(NosqlApi::Ambiguous),
            type_cast_nearby: true,
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::Benign);
    }

    // ─── Annotations ───
    #[test]
    fn nosql_safe_annotation_collapses_to_benign() {
        let evidence = Evidence {
            api: Some(NosqlApi::OperatorInjection), // even Unsafe shape
            nosql_safe_annotation: Some("hmac-verified".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        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 { .. }
        ));
    }

    #[test]
    fn nosql_vulnerable_annotation_collapses_to_realbug() {
        let evidence = Evidence {
            api: Some(NosqlApi::TypedValueQuery), // even safe shape
            nosql_vulnerable_annotation: Some("helper-assembled-query".to_string()),
            ..Default::default()
        };
        let p = predict(&evidence);
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Critical);
    }

    // ─── Tiebreak ───
    #[test]
    fn empty_evidence_tiebreaks_realbug_medium() {
        let p = predict(&Evidence::empty());
        assert_eq!(p.predicted, BranchLabel::RealBug);
        assert_eq!(p.predicted_severity, Severity::Medium);
    }

    // ─── Sign convention ───
    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn realbug_signal_weights_are_negative() {
        assert!(W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY < 0.0);
        assert!(W_HAS_DOLLAR_REGEX_WITH_USER_INPUT < 0.0);
        assert!(W_ENCLOSING_ROUTE_HANDLER < 0.0);
        assert!(W_API_OPERATOR_COLLAPSE < 0.0);
        assert!(W_API_DICT_EXPANSION_COLLAPSE < 0.0);
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn benign_signal_weights_are_positive() {
        assert!(W_USER_INPUT_TYPED_STRING_NEARBY > 0.0);
        assert!(W_DEVELOPER_WRITTEN_OPERATOR > 0.0);
        assert!(W_OBJECTID_OR_TYPE_CAST_NEARBY > 0.0);
        assert!(W_TRUST_BOUNDARY_NAME > 0.0);
        assert!(W_ENCLOSING_TEST_FUNCTION > 0.0);
        assert!(W_API_TYPED_QUERY_COLLAPSE > 0.0);
    }

    // ─── Honest review pin: D5.2 asymmetric source weights ───
    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn d5_2_typed_string_vs_unstructured_json_asymmetry() {
        // Pin the math: TypedString is positive (Python is safer),
        // UnstructuredJson is negative (Python is NOT safer for this
        // source family). The asymmetric magnitudes encode the D5.2
        // honest-review finding.
        assert!(
            W_USER_INPUT_TYPED_STRING_NEARBY > 0.0,
            "TypedString (request.form/args) must be positive (Python is structurally safer)"
        );
        assert!(
            W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY < 0.0,
            "UnstructuredJson (request.json/body) must be negative (Python is NOT safer here)"
        );
        // The magnitude of the unsafe direction should dominate when
        // both signals would fire (they can't simultaneously, but the
        // magnitude reflects design intent).
        assert!(
            W_USER_INPUT_UNSTRUCTURED_JSON_NEARBY.abs() > W_USER_INPUT_TYPED_STRING_NEARBY.abs(),
            "UnstructuredJson magnitude must exceed TypedString magnitude (D5.2 design)"
        );
    }

    // ─── NosqlApi helpers ───
    #[test]
    fn nosql_api_collapses_predicates() {
        assert!(NosqlApi::TypedValueQuery.collapses_typed_query());
        assert!(!NosqlApi::TypedValueQuery.collapses_operator());
        assert!(!NosqlApi::TypedValueQuery.collapses_dict_expansion());

        assert!(NosqlApi::OperatorInjection.collapses_operator());
        assert!(!NosqlApi::OperatorInjection.collapses_typed_query());
        assert!(!NosqlApi::OperatorInjection.collapses_dict_expansion());

        assert!(NosqlApi::DictExpansion.collapses_dict_expansion());
        assert!(!NosqlApi::DictExpansion.collapses_typed_query());
        assert!(!NosqlApi::DictExpansion.collapses_operator());

        assert!(!NosqlApi::Ambiguous.collapses_typed_query());
        assert!(!NosqlApi::Ambiguous.collapses_operator());
        assert!(!NosqlApi::Ambiguous.collapses_dict_expansion());

        assert!(!NosqlApi::Unknown.collapses_typed_query());
        assert!(!NosqlApi::Unknown.collapses_operator());
        assert!(!NosqlApi::Unknown.collapses_dict_expansion());
    }

    #[test]
    fn nosql_api_is_recognized() {
        assert!(NosqlApi::TypedValueQuery.is_recognized());
        assert!(NosqlApi::OperatorInjection.is_recognized());
        assert!(NosqlApi::DictExpansion.is_recognized());
        assert!(NosqlApi::Ambiguous.is_recognized());
        assert!(!NosqlApi::Unknown.is_recognized());
    }

    // ─── User-input-source classifier ───
    #[test]
    fn classify_request_form_as_typed_string() {
        assert_eq!(
            classify_user_input_source("u = request.form['user']"),
            UserInputSource::TypedString
        );
        assert_eq!(
            classify_user_input_source("ids = request.args.getlist('id')"),
            UserInputSource::TypedString
        );
    }

    #[test]
    fn classify_request_json_as_unstructured_json() {
        assert_eq!(
            classify_user_input_source("p = request.json"),
            UserInputSource::UnstructuredJson
        );
        assert_eq!(
            classify_user_input_source("body = request.get_json()"),
            UserInputSource::UnstructuredJson
        );
        assert_eq!(
            classify_user_input_source("b = request.body"),
            UserInputSource::UnstructuredJson
        );
    }

    #[test]
    fn classify_unstructured_json_priority_when_both_present() {
        // If both appear on the same line (rare but defensible),
        // UnstructuredJson takes priority — it's the more dangerous
        // source family.
        let src = "x = request.form['a'] or request.json";
        assert_eq!(
            classify_user_input_source(src),
            UserInputSource::UnstructuredJson
        );
    }

    #[test]
    fn classify_no_user_input() {
        assert_eq!(
            classify_user_input_source("x = compute()"),
            UserInputSource::None
        );
    }

    // ─── Type-cast classifier ───
    #[test]
    fn line_contains_type_cast_recognizes_objectid() {
        assert!(line_contains_type_cast("_id = ObjectId(x)"));
        assert!(line_contains_type_cast(
            "from bson import ObjectId; q = ObjectId(s)"
        ));
    }

    #[test]
    fn line_contains_type_cast_recognizes_pydantic() {
        assert!(line_contains_type_cast(
            "q = QuerySchema.model_validate(payload)"
        ));
        assert!(line_contains_type_cast(
            "q = QuerySchema.parse_obj(payload)"
        ));
    }

    #[test]
    fn line_contains_type_cast_no_match() {
        assert!(!line_contains_type_cast("x = compute(payload)"));
    }

    // ─── Operator classifiers ───
    #[test]
    fn dangerous_operator_recognition() {
        assert!(line_contains_dangerous_operator("{\"$where\": \"...\"}"));
        assert!(line_contains_dangerous_operator("{\"$function\": ...}"));
        assert!(line_contains_dangerous_operator("{\"$expr\": ...}"));
        assert!(line_contains_dangerous_operator("{\"$accumulator\": ...}"));
        assert!(!line_contains_dangerous_operator("{\"$ne\": null}"));
    }

    #[test]
    fn developer_operator_recognition() {
        assert!(line_contains_developer_operator("{\"$ne\": null}"));
        assert!(line_contains_developer_operator("{\"$gt\": 0}"));
        assert!(line_contains_developer_operator("{\"$in\": [1, 2]}"));
        assert!(!line_contains_developer_operator("{\"$where\": \"...\"}"));
    }

    // ─── Lexicon helpers ───
    #[test]
    fn route_handler_decorator_matches() {
        assert!(matches_route_handler_decorator("@app.route('/foo')"));
        assert!(matches_route_handler_decorator("    @app.post('/x')"));
        assert!(matches_route_handler_decorator("@router.get('/v1')"));
        assert!(matches_route_handler_decorator("@blueprint.route('/x')"));
        assert!(!matches_route_handler_decorator("@dataclass"));
    }

    #[test]
    fn route_handler_name_matches() {
        assert!(matches_route_handler_name("login_handler"));
        assert!(matches_route_handler_name("user_endpoint"));
        assert!(matches_route_handler_name("posts_view"));
        assert!(!matches_route_handler_name("compute_total"));
    }

    #[test]
    fn trust_boundary_name_matches() {
        assert!(matches_trust_boundary_name("query_trusted"));
        assert!(matches_trust_boundary_name("load_admin_query"));
        assert!(matches_trust_boundary_name("post_validated_filter"));
        assert!(matches_trust_boundary_name("read_internal_state"));
        assert!(!matches_trust_boundary_name("plain_query"));
    }

    // ─── Extract helpers ───
    #[test]
    fn extract_nosql_safe_with_reason() {
        assert_eq!(
            extract_nosql_safe_reason(
                "users.find_one({...})  # repotoire: nosql-safe[pydantic-validated]"
            ),
            Some("pydantic-validated".to_string())
        );
    }

    #[test]
    fn extract_nosql_safe_without_reason() {
        assert_eq!(
            extract_nosql_safe_reason("users.find({})  # repotoire: nosql-safe"),
            Some("unspecified".to_string())
        );
    }

    #[test]
    fn extract_nosql_vulnerable_with_source() {
        assert_eq!(
            extract_nosql_vulnerable_source(
                "users.find(q)  # repotoire: nosql-vulnerable[helper-assembled]"
            ),
            Some("helper-assembled".to_string())
        );
    }

    #[test]
    fn extract_nosql_ignores_other_kinds() {
        assert_eq!(
            extract_nosql_safe_reason("x  # repotoire: deserialize-safe[ok]"),
            None
        );
        assert_eq!(
            extract_nosql_vulnerable_source("x  # repotoire: jwt-vulnerable[ok]"),
            None
        );
    }
}