patronus-ark 0.1.17

Hybrid Rust security scanners for prompt injection, DLP, PII, and agentic tool risks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{HashMap, HashSet};
use std::ops::{Deref, DerefMut};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::PathBuf;
use std::sync::{
    atomic::{AtomicU64, AtomicUsize, Ordering},
    mpsc, Arc, Mutex, OnceLock,
};
use std::time::Instant;

use super::decision_cache::DecisionCache;
use crate::{
    assets::{DYNAMIC_PII_ASSET, SHELL_COMMAND_ASSET},
    detectors::{
        shell::{ShellPolicyConfig, ShellRiskPipeline},
        threat::ThreatPipeline,
        NativeDetection,
    },
    diagnostics::PhaseMetricScope,
    ml::ntdb_executor::{NtdbExecutor, NtdbModelChunkInferences, PreparedNtdbChunk},
    pipeline::{L3Worker, RequestRegistry},
    post_prediction::filter_evidence,
    DynamicPiiConfig, EvaluationResult, ExecutionBackend, ExternalL1Detector, ExternalL1Input,
    LayerResult, NtdbOperatingPoint, OnnxBatchMode, ScanExecution, ScanGateMatrix,
    SecurityCategory, SecurityFailure, SecurityFailureKind, SecurityFailureStage, SecurityLevel,
    SecurityLevelReadiness, SecurityRuntimeReadiness, SecurityScanResult,
};
use patronus_ark_core::{
    native::{NativeEngine, NativeProducerOutcome},
    ScanControl, ScanError,
};

mod direct_l3;
mod injection_l1;
mod ntdb_l2;
mod request_queue;
mod warmup;

use ntdb_l2::{ntdb_l2_cache_namespace, ntdb_l2_error_scan_result};
#[cfg(feature = "test-util")]
pub use ntdb_l2::{ntdb_l2_enabled_for_category, ntdb_l2_model_config_for_id, NtdbL2ModelConfig};
pub use ntdb_l2::{ntdb_l2_model_configs_for_category, ntdb_l2_scan_result, restore_l2_decision};

const DEFAULT_QUEUE_WORKER_COUNT: usize = 2;

fn distributed_unified_l3_fingerprint(base_dir: &std::path::Path) -> Result<String, String> {
    use std::io::Read;

    let asset = crate::assets::UNIFIED_L3_ASSET;
    let bundle_dir = base_dir.join(asset.destination_path);
    let mut files = crate::assets::selected_pipeline_model_files(asset)
        .into_iter()
        .map(str::to_string)
        .collect::<Vec<_>>();
    for generated in ["tokenizer.mmbpe", ".patronus-revision"] {
        if bundle_dir.join(generated).is_file() {
            files.push(generated.to_string());
        }
    }
    files.sort();
    files.dedup();
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"patronus-unified-l3-assets-v1\0");
    for relative in files {
        let path = bundle_dir.join(&relative);
        let file = std::fs::File::open(&path).map_err(|error| {
            format!("failed to fingerprint L3 asset {}: {error}", path.display())
        })?;
        hasher.update(&(relative.len() as u64).to_le_bytes());
        hasher.update(relative.as_bytes());
        let mut reader = std::io::BufReader::new(file);
        let mut buffer = [0_u8; 64 * 1024];
        loop {
            let read = reader.read(&mut buffer).map_err(|error| {
                format!("failed to fingerprint L3 asset {}: {error}", path.display())
            })?;
            if read == 0 {
                break;
            }
            hasher.update(&buffer[..read]);
        }
    }
    Ok(hasher.finalize().to_hex().to_string())
}

#[cfg(test)]
mod distributed_fingerprint_tests {
    use super::distributed_unified_l3_fingerprint;

    #[test]
    fn unified_l3_fingerprint_tracks_selected_file_contents() {
        let root = std::env::temp_dir().join(format!(
            "ark-l3-fingerprint-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let bundle = root.join(crate::assets::UNIFIED_L3_ASSET.destination_path);
        let selected =
            crate::assets::selected_pipeline_model_files(crate::assets::UNIFIED_L3_ASSET);
        for relative in &selected {
            let path = bundle.join(relative);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, format!("fixture:{relative}")).unwrap();
        }
        std::fs::write(bundle.join(".patronus-revision"), "revision-a").unwrap();
        let before = distributed_unified_l3_fingerprint(&root).unwrap();
        std::fs::write(bundle.join(selected[0]), "changed").unwrap();
        let after = distributed_unified_l3_fingerprint(&root).unwrap();
        assert_ne!(before, after);
        std::fs::remove_dir_all(root).unwrap();
    }
}

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

    #[test]
    fn tool_tags_plan_preserves_all_canonical_model_bindings() {
        let gateway = SecurityGateway::with_max_level(
            vec![SecurityCategory::ToolTags],
            SecurityLevel::L2,
            None,
            false,
        );
        let execution = ScanExecution::new(SecurityLevel::L2);
        let pipelines = gateway.distributed_l2_pipelines(&[SecurityCategory::ToolTags], &execution);

        assert_eq!(pipelines.len(), 3);
        assert!(pipelines
            .iter()
            .all(|pipeline| pipeline.category == SecurityCategory::ToolTags));
        assert_eq!(
            pipelines
                .iter()
                .map(|pipeline| pipeline.model_id.as_str())
                .collect::<Vec<_>>(),
            vec![
                "tool_tags_sink_external",
                "tool_tags_source_sensitive",
                "tool_tags_source_untrusted",
            ]
        );
    }

    #[test]
    fn distributed_l2_plan_marks_l3_as_deferred_for_central_aggregation() {
        let gateway = SecurityGateway::with_max_level(
            vec![SecurityCategory::Injection],
            SecurityLevel::L3,
            None,
            false,
        );
        let execution = ScanExecution::new(SecurityLevel::L3);
        let inputs = [ExternalL1Input::new(
            SecurityCategory::Injection,
            "ordinary prose",
        )];

        let plan = gateway.plan_distributed_l2(&inputs, &serde_json::json!({}), &execution);

        assert!(plan.execution.defer_l3());
    }
}

fn run_measured_l1_detector<F>(
    category: SecurityCategory,
    model: &str,
    text_bytes: usize,
    evaluate: F,
) -> SecurityScanResult
where
    F: FnOnce() -> SecurityScanResult,
{
    let mut metrics = PhaseMetricScope::new(
        "security_l1_detector",
        format!(
            "category={} model={} text_bytes={}",
            category.as_str(),
            model,
            text_bytes
        ),
    );
    let result = evaluate();
    metrics.checkpoint(
        "after_evaluate",
        format!("category={} model={model}", category.as_str()),
    );
    result
}

/// Main scanner gateway for native and model-backed security categories.
pub struct SecurityGateway {
    core: Arc<SecurityGatewayCore>,
    queue_sender: OnceLock<mpsc::SyncSender<request_queue::QueueWork>>,
}

#[derive(Debug, Clone)]
pub struct DistributedL2Plan {
    pub l1_results: Vec<SecurityScanResult>,
    pub l1_failures: Vec<SecurityFailure>,
    pub categories: Vec<SecurityCategory>,
    pub model_ids: Vec<String>,
    pub pipelines: Vec<DistributedL2Pipeline>,
    pub execution: ScanExecution,
    pub gate_results: Vec<crate::GateResult>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DistributedL2Pipeline {
    pub pipeline_id: String,
    pub category: SecurityCategory,
    pub model_id: String,
    pub public_model: String,
    pub has_l3: bool,
}

#[derive(Debug, Clone)]
pub struct DistributedL3Plan {
    pub categories: Vec<SecurityCategory>,
    pub execution: ScanExecution,
    pub gate_results: Vec<crate::GateResult>,
}

#[doc(hidden)]
pub struct SecurityGatewayCore {
    /// Categories configured for `scan_all`.
    categories: Vec<SecurityCategory>,
    /// Maximum layer to evaluate for configured categories.
    max_level: SecurityLevel,
    /// Optional asset root. Defaults to the platform cache directory.
    model_dir: Option<PathBuf>,
    /// Whether missing model assets may be downloaded during `warmup`.
    download_files: bool,
    /// Optional allowlist of categories that may download missing assets.
    download_categories: Option<Vec<SecurityCategory>>,
    /// Execution gates consumed by scan methods.
    execution: Mutex<ScanExecution>,
    /// Application-provided L1 heuristics, grouped in registration order by category.
    external_l1: Mutex<HashMap<SecurityCategory, Vec<Arc<dyn ExternalL1Detector>>>>,
    /// Request-independent configuration for the L3-only dynamic entity pipeline.
    dynamic_pii_config: Mutex<DynamicPiiConfig>,
    /// User policies and allowlist of the `shell_command` verdict.
    shell_command_policy_config: Mutex<ShellPolicyConfig>,
    /// sha256 of the `shell_command` release manifest that warmup accepts.
    shell_command_manifest_sha256: String,
    queue_worker_count: AtomicUsize,

    ntdb_executor: Option<Mutex<NtdbExecutor>>,
    distributed_fingerprints: OnceLock<(String, String)>,

    // Shared native producer state, initialized only for configured categories.
    native_engine: NativeEngine,
    threat_pipeline: Option<ThreatPipeline>,
    /// Shell command risk model, loaded from local assets during warmup.
    shell_command_pipeline: Option<ShellRiskPipeline>,

    request_counter: AtomicU64,
    requests: Arc<RequestRegistry>,
    l3_worker: L3Worker,
    ntdb_decision_cache: DecisionCache,
}

impl Deref for SecurityGateway {
    type Target = SecurityGatewayCore;

    fn deref(&self) -> &Self::Target {
        &self.core
    }
}

impl DerefMut for SecurityGateway {
    fn deref_mut(&mut self) -> &mut Self::Target {
        Arc::get_mut(&mut self.core).expect("warmup must run before queue processing starts")
    }
}

fn scan_result(
    category: SecurityCategory,
    model: impl Into<String>,
    result: EvaluationResult,
    layers: Vec<LayerResult>,
) -> SecurityScanResult {
    let duration_ms = layers.iter().map(|layer| layer.duration_ms).sum();
    SecurityScanResult {
        category: category.as_str().to_string(),
        class_name: result.class_name,
        confidence: result.confidence,
        level: result.level,
        model: model.into(),
        duration_ms,
        layers,
        internal_l2_chunk_outputs: Vec::new(),
        evidence_spans: Vec::new(),
        label_scores: Vec::new(),
        decision: None,
    }
}

pub(super) fn dynamic_pii_pending_result(execution: &ScanExecution) -> SecurityScanResult {
    let result = EvaluationResult {
        class_name: "pending".to_string(),
        confidence: 0.0,
        level: SecurityLevel::L3.as_str().to_string(),
    };
    scan_result(
        SecurityCategory::DynamicPii,
        DYNAMIC_PII_ASSET.model,
        result.clone(),
        vec![crate::pipeline::l3_pending_layer(&result, execution)],
    )
}

fn l1_scan_result_with_duration(
    category: SecurityCategory,
    model: impl Into<String>,
    layer_type: &str,
    result: EvaluationResult,
    duration_ms: f64,
) -> SecurityScanResult {
    let layer = LayerResult {
        level: result.level.clone(),
        layer_type: layer_type.to_string(),
        class_name: result.class_name.clone(),
        confidence: result.confidence,
        matched: true,
        duration_ms,
        thresholds: HashMap::new(),
        details: HashMap::new(),
    };
    scan_result(category, model, result, vec![layer])
}

fn timed_native_detection_scan_result<F>(
    category: SecurityCategory,
    model: impl Into<String>,
    text: &str,
    detect: F,
) -> SecurityScanResult
where
    F: FnOnce() -> NativeDetection,
{
    let model = model.into();
    let started = Instant::now();
    match catch_unwind(AssertUnwindSafe(detect)) {
        Ok(detection) => native_detection_scan_result(
            category,
            model,
            text,
            detection,
            started.elapsed().as_secs_f64() * 1000.0,
        ),
        Err(payload) => scanner_error_scan_result(category, model, panic_message(payload)),
    }
}

fn native_detection_scan_result(
    category: SecurityCategory,
    model: String,
    text: &str,
    detection: NativeDetection,
    duration_ms: f64,
) -> SecurityScanResult {
    let mut result =
        l1_scan_result_with_duration(category, model, "native", detection.result, duration_ms);
    result.evidence_spans = filter_evidence(category, text, detection.evidence_spans);
    result.layers[0].details = detection.details;
    result
}

fn native_engine_scan_result(
    category: SecurityCategory,
    model: &str,
    text: &str,
    outcome: Result<NativeProducerOutcome, ScanError>,
    execution: &ScanExecution,
) -> SecurityScanResult {
    let outcome = match outcome {
        Ok(outcome) => outcome,
        Err(ScanError::Detector(message)) => {
            return scanner_error_scan_result(category, model, message);
        }
        Err(error) => return scanner_error_scan_result(category, model, error.to_string()),
    };
    let mut result = native_detection_scan_result(
        category,
        model.into(),
        text,
        outcome.detection,
        outcome.duration_ms,
    );
    // Keep Ark's existing result policy: only scored native PII/DLP update
    // confidence after evidence filtering. Other producer scores stay untouched.
    let scored = match model {
        "native:pii" => execution.gates().native.pii_mode.min_score().is_some(),
        "native:dlp" => execution.gates().native.dlp_mode.min_score().is_some(),
        _ => false,
    };
    if scored {
        if let Some(best) = result
            .evidence_spans
            .iter()
            .map(|span| span.score)
            .reduce(f64::max)
        {
            result.confidence = best;
            result.layers[0].confidence = best;
        }
    }
    result
}

fn scanner_error_scan_result(
    category: SecurityCategory,
    model: impl Into<String>,
    message: String,
) -> SecurityScanResult {
    let model = model.into();
    let result = EvaluationResult {
        class_name: "error".to_string(),
        confidence: 0.0,
        level: SecurityLevel::L1.as_str().to_string(),
    };
    let layer = LayerResult {
        level: result.level.clone(),
        layer_type: "scanner_error".to_string(),
        class_name: result.class_name.clone(),
        confidence: 0.0,
        matched: false,
        duration_ms: 0.0,
        thresholds: HashMap::new(),
        details: HashMap::from([("error".to_string(), serde_json::json!(message))]),
    };
    scan_result(category, model, result, vec![layer])
}

fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "scanner panicked".to_string()
    }
}

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

    #[test]
    fn engine_detector_errors_preserve_the_legacy_producer_error_result() {
        let legacy = timed_native_detection_scan_result(
            SecurityCategory::Injection,
            "native:injection_rule_catalog",
            "hello",
            || panic!("detector fixture failure"),
        );
        let migrated = native_engine_scan_result(
            SecurityCategory::Injection,
            "native:injection_rule_catalog",
            "hello",
            Err(ScanError::Detector("detector fixture failure".into())),
            &ScanExecution::new(SecurityLevel::L1),
        );
        let legacy: patronus_ark_core::NativeResult = legacy.into();
        let migrated: patronus_ark_core::NativeResult = migrated.into();
        assert_eq!(
            serde_json::to_value(legacy).unwrap(),
            serde_json::to_value(migrated).unwrap(),
        );
    }

    #[test]
    fn ark_only_categories_do_not_initialize_shared_native_producers() {
        let gateway = SecurityGateway::with_max_level(
            vec![SecurityCategory::ShellCommand, SecurityCategory::Threat],
            SecurityLevel::L1,
            None,
            false,
        );
        for category in patronus_ark_core::native::NATIVE_CATEGORIES {
            assert!(gateway.native_engine.producers(category).is_empty());
        }
        assert!(gateway.threat_pipeline.is_some());
    }
}

impl SecurityGateway {
    /// Flush queued persistent cache writes. Memory-only gateways are a no-op.
    pub fn flush_cache(&self) -> Result<(), crate::CacheError> {
        self.l3_worker.flush_cache()
    }

    /// Flush queued persistent cache writes and reopen storage on the next cache access.
    pub fn reset_cache_connections(&self) -> Result<(), crate::CacheError> {
        self.l3_worker.reset_cache_connections()
    }

    /// Remove hot and persistent cache records created before `until_unix_ms`.
    pub fn reset_cache(&self, until_unix_ms: u64) -> Result<usize, crate::CacheError> {
        self.l3_worker.reset_cache(until_unix_ms)
    }

    /// Explicit persistent cache location configured for this gateway.
    pub fn cache_storage_location(&self) -> Option<PathBuf> {
        self.l3_worker.cache_storage_location()
    }

    /// Set the number of Ark queue workers spawned on first queued request.
    pub fn set_queue_worker_count(&self, worker_count: usize) {
        self.core
            .queue_worker_count
            .store(worker_count.max(1), Ordering::Relaxed);
    }

    /// Configure dedicated Wolf windowing and batching for subsequent scans.
    pub fn set_wolf_execution_options(
        &self,
        options: crate::WolfExecutionOptions,
    ) -> Result<(), String> {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_wolf_execution_options(options)
    }

    /// Choose the dedicated Wolf model and ONNX export; set before warmup.
    pub fn set_wolf_selection(&self, selection: crate::WolfSelection) -> Result<(), String> {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_wolf_selection(selection)
    }

    /// Set ONNX Runtime session options for subsequent scans.
    pub fn set_onnx_runtime_options(&self, options: crate::OnnxRuntimeOptions) {
        self.execution
            .lock()
            .expect("scan execution mutex poisoned")
            .set_onnx_runtime_options(options);
    }

    /// Create a gateway with `SecurityLevel::L2` as the maximum level.
    pub fn new(
        categories: Vec<SecurityCategory>,
        model_dir: Option<PathBuf>,
        download_files: bool,
    ) -> Self {
        Self::with_max_level(categories, SecurityLevel::L2, model_dir, download_files)
    }

    /// Create a gateway with an explicit maximum security level.
    pub fn with_max_level(
        categories: Vec<SecurityCategory>,
        max_level: SecurityLevel,
        model_dir: Option<PathBuf>,
        download_files: bool,
    ) -> Self {
        Self::with_download_categories(categories, max_level, model_dir, download_files, None)
    }

    /// Create a gateway with an optional per-category asset download allowlist.
    ///
    /// When `download_categories` is `None`, all configured categories may
    /// download missing assets if `download_files` is `true`.
    pub fn with_download_categories(
        categories: Vec<SecurityCategory>,
        max_level: SecurityLevel,
        model_dir: Option<PathBuf>,
        download_files: bool,
        download_categories: Option<Vec<SecurityCategory>>,
    ) -> Self {
        Self::try_with_download_categories_and_cache(
            categories,
            max_level,
            model_dir,
            download_files,
            download_categories,
            crate::ExactCacheConfig::default(),
        )
        .expect("memory-only exact cache must initialize")
    }

    /// Create a gateway with lifecycle-scoped exact-cache configuration.
    ///
    /// Persistent caching is enabled only when `cache_config.persistent`
    /// contains an explicit storage location. Requests cannot override it.
    pub fn try_with_download_categories_and_cache(
        categories: Vec<SecurityCategory>,
        max_level: SecurityLevel,
        model_dir: Option<PathBuf>,
        download_files: bool,
        download_categories: Option<Vec<SecurityCategory>>,
        cache_config: crate::ExactCacheConfig,
    ) -> Result<Self, crate::CacheError> {
        let requests = Arc::new(RequestRegistry::default());
        let l3_worker = L3Worker::start_with_cache(Arc::clone(&requests), cache_config)?;
        let native_engine = NativeEngine::new(&categories);
        let threat_pipeline = categories
            .contains(&SecurityCategory::Threat)
            .then(ThreatPipeline::new);
        let core = SecurityGatewayCore {
            categories,
            max_level,
            model_dir,
            download_files,
            download_categories,
            execution: Mutex::new(ScanExecution::new(max_level)),
            external_l1: Mutex::new(HashMap::new()),
            dynamic_pii_config: Mutex::new(DynamicPiiConfig::default()),
            shell_command_policy_config: Mutex::new(ShellPolicyConfig::default()),
            shell_command_manifest_sha256: patronus_ark_core::warmup::SHELL_MANIFEST_SHA256
                .to_string(),
            queue_worker_count: AtomicUsize::new(DEFAULT_QUEUE_WORKER_COUNT),
            ntdb_executor: None,
            distributed_fingerprints: OnceLock::new(),
            native_engine,
            threat_pipeline,
            shell_command_pipeline: None,
            request_counter: AtomicU64::new(1),
            requests,
            l3_worker,
            ntdb_decision_cache: DecisionCache::default(),
        };

        Ok(SecurityGateway {
            core: Arc::new(core),
            queue_sender: OnceLock::new(),
        })
    }

    /// Categories configured for `scan_all`.
    pub fn categories(&self) -> &[SecurityCategory] {
        &self.categories
    }

    /// Maximum level evaluated for configured categories.
    pub fn max_level(&self) -> SecurityLevel {
        self.max_level
    }

    /// Return runtime readiness for the currently configured levels and models.
    pub fn runtime_readiness(&self) -> SecurityRuntimeReadiness {
        let execution = self.scan_execution();
        let external_l1 = self
            .external_l1
            .lock()
            .expect("external L1 registry mutex poisoned");
        let has_l1_category = self.categories.iter().any(|category| {
            matches!(
                category,
                SecurityCategory::Injection
                    | SecurityCategory::Dlp
                    | SecurityCategory::Pii
                    | SecurityCategory::Threat
            ) || external_l1
                .get(category)
                .is_some_and(|detectors| !detectors.is_empty())
        });
        let shell_command_configured = self.shell_command_configured(&execution);
        let l1 = if !execution.allows_level(SecurityLevel::L1)
            || !(has_l1_category || shell_command_configured)
        {
            SecurityLevelReadiness::NotConfigured
        } else if shell_command_configured && self.shell_command_pipeline.is_none() {
            SecurityLevelReadiness::NotReady {
                failures: vec![SecurityFailure {
                    stage: SecurityFailureStage::Inference,
                    level: Some(SecurityLevel::L1),
                    detector_id: Some(SHELL_COMMAND_ASSET.model.to_string()),
                    kind: SecurityFailureKind::NotReady,
                    retryable: true,
                    message: format!("{} model is not loaded", SHELL_COMMAND_ASSET.model),
                }],
            }
        } else {
            SecurityLevelReadiness::Ready
        };

        let l2_configs = self
            .categories
            .iter()
            .copied()
            .flat_map(|category| ntdb_l2_model_configs_for_category(&execution, category))
            .collect::<Vec<_>>();
        let l2 = if l2_configs.is_empty() {
            SecurityLevelReadiness::NotConfigured
        } else if self.ntdb_executor.is_some() {
            SecurityLevelReadiness::Ready
        } else {
            SecurityLevelReadiness::NotReady {
                failures: l2_configs
                    .iter()
                    .map(|config| SecurityFailure {
                        stage: SecurityFailureStage::Inference,
                        level: Some(SecurityLevel::L2),
                        detector_id: Some(config.public_model.to_string()),
                        kind: SecurityFailureKind::NotReady,
                        retryable: true,
                        message: format!("{} L2 runtime is not initialized", config.public_model),
                    })
                    .collect(),
            }
        };

        let l3_configs = self
            .categories
            .iter()
            .copied()
            .flat_map(|category| {
                ntdb_l2::classifier_model_configs_for_category(&execution, category)
            })
            .collect::<Vec<_>>();
        let has_classifier_l3 = l3_configs
            .iter()
            .any(|config| config.has_l3 && execution.allows_level(SecurityLevel::L3));
        let mut l3_models = match execution.l3_strategy() {
            crate::L3Strategy::Multi
                if has_classifier_l3
                    && execution
                        .gates()
                        .native
                        .allows_model(crate::ml::unified_onnx::UNIFIED_MODEL) =>
            {
                vec![crate::ml::unified_onnx::UNIFIED_MODEL]
            }
            crate::L3Strategy::Multi => Vec::new(),
            crate::L3Strategy::Dedicated => l3_configs
                .iter()
                .filter(|config| config.has_l3 && execution.allows_level(SecurityLevel::L3))
                .map(|config| config.public_model)
                .collect::<Vec<_>>(),
        };
        if self.categories.contains(&SecurityCategory::DynamicPii)
            && execution.allows_level(SecurityLevel::L3)
            && execution
                .gates()
                .native
                .allows_model(DYNAMIC_PII_ASSET.model)
        {
            l3_models.push(DYNAMIC_PII_ASSET.model);
        }
        let l3_failures = l3_models
            .iter()
            .filter(|model| !self.l3_worker.has_model(model))
            .map(|model| SecurityFailure {
                stage: SecurityFailureStage::Worker,
                level: Some(SecurityLevel::L3),
                detector_id: Some((*model).to_string()),
                kind: SecurityFailureKind::NotReady,
                retryable: true,
                message: format!("{model} L3 worker model is not registered"),
            })
            .collect::<Vec<_>>();
        let l3 = if l3_models.is_empty() {
            SecurityLevelReadiness::NotConfigured
        } else if l3_failures.is_empty() {
            SecurityLevelReadiness::Ready
        } else {
            SecurityLevelReadiness::NotReady {
                failures: l3_failures,
            }
        };

        SecurityRuntimeReadiness { l1, l2, l3 }
    }

    /// Register an external L1 heuristic for the category returned by the detector.
    ///
    /// Detectors run after the built-in L1 heuristics in registration order.
    pub fn register_external_l1(
        &self,
        detector: Arc<dyn ExternalL1Detector>,
    ) -> Result<(), String> {
        let category = detector.category();
        let id = detector.id();
        if id.is_empty() {
            return Err("external L1 detector id must not be empty".to_string());
        }

        let mut registry = self
            .external_l1
            .lock()
            .expect("external L1 registry mutex poisoned");
        let detectors = registry.entry(category).or_default();
        if detectors.iter().any(|registered| registered.id() == id) {
            return Err(format!(
                "external L1 detector '{id}' is already registered for {}",
                category.as_str()
            ));
        }
        detectors.push(detector);
        Ok(())
    }

    #[doc(hidden)]
    pub fn should_download_assets_for(&self, category: SecurityCategory) -> bool {
        if !self.download_files {
            return false;
        }

        match &self.download_categories {
            Some(categories) => categories.contains(&category),
            None => true,
        }
    }

    /// Replace the execution gate matrix used by subsequent scans.
    pub fn set_execution_gates(&self, gates: ScanGateMatrix) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_gates(gates);
    }

    /// Replace the ONNX batch mode used by subsequent batch scans.
    pub fn set_onnx_batch_mode(&self, mode: OnnxBatchMode) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_onnx_batch_mode(mode);
    }

    /// Replace the execution backend and apply its default L3 mode.
    pub fn set_execution_backend(&self, backend: ExecutionBackend) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_backend(backend);
    }

    /// Select the calibrated NTDB operating point used by subsequent scans.
    pub fn set_ntdb_operating_point(&self, point: NtdbOperatingPoint) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_ntdb_operating_point(point);
    }

    /// Select the calibrated NTDB final-decision threshold set used by subsequent scans.
    pub fn set_ntdb_decision_threshold_point(&self, point: NtdbOperatingPoint) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_ntdb_decision_threshold_point(point);
    }

    /// Select dedicated per-pipeline L3 models or the shared multi-head model.
    pub fn set_l3_strategy(&self, strategy: crate::L3Strategy) {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .set_l3_strategy(strategy);
    }

    /// Unload resident L3 model sessions while keeping registered model metadata.
    ///
    /// Subsequent L3 scans can reload the same configured models without another
    /// gateway construction or asset warmup.
    pub fn stop_l3_models(&self) {
        self.l3_worker.stop_models();
    }

    /// Return the active global L3 model strategy.
    pub fn l3_strategy(&self) -> crate::L3Strategy {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .l3_strategy()
    }

    /// Return the calibrated NTDB operating point used by subsequent scans.
    pub fn ntdb_operating_point(&self) -> NtdbOperatingPoint {
        self.scan_execution().ntdb_operating_point()
    }

    /// Runtime identities used to reject incompatible distributed batches.
    pub fn distributed_ntdb_fingerprints(&self) -> Result<(String, String), String> {
        if let Some(fingerprints) = self.distributed_fingerprints.get() {
            return Ok(fingerprints.clone());
        }
        let executor = self
            .ntdb_executor
            .as_ref()
            .ok_or_else(|| "NTDB L2 runtime is not initialized".to_string())?
            .lock()
            .map_err(|error| format!("NTDB executor mutex poisoned: {error}"))?;
        let (tokenizer, ntdb_models) = executor
            .distributed_fingerprints()
            .map_err(|error| error.to_string())?;
        let mut models = blake3::Hasher::new();
        models.update(b"patronus-distributed-models-v1\0");
        models.update(ntdb_models.as_bytes());
        models.update(&[0]);
        if self
            .l3_worker
            .has_model(crate::ml::unified_onnx::UNIFIED_MODEL)
        {
            let base_dir = self.model_base_dir().map_err(|error| error.to_string())?;
            models.update(distributed_unified_l3_fingerprint(&base_dir)?.as_bytes());
        } else {
            models.update(b"unified-l3-not-loaded");
        }
        let fingerprints = (tokenizer, models.finalize().to_hex().to_string());
        let _ = self.distributed_fingerprints.set(fingerprints.clone());
        Ok(self
            .distributed_fingerprints
            .get()
            .cloned()
            .unwrap_or(fingerprints))
    }

    /// Tokenize a document once for distributed Package-v4 execution.
    pub fn prepare_distributed_ntdb_chunks(
        &self,
        text: &str,
    ) -> Result<Vec<PreparedNtdbChunk>, String> {
        self.prepare_distributed_ntdb_chunks_with_execution(text, &self.scan_execution())
    }

    /// Tokenize a document for distributed execution with request-local options.
    pub fn prepare_distributed_ntdb_chunks_with_execution(
        &self,
        text: &str,
        execution: &ScanExecution,
    ) -> Result<Vec<PreparedNtdbChunk>, String> {
        self.ntdb_executor
            .as_ref()
            .ok_or_else(|| "NTDB L2 runtime is not initialized".to_string())?
            .lock()
            .map_err(|error| format!("NTDB executor mutex poisoned: {error}"))?
            .prepare_chunks_with_overlap(text, execution.chunk_overlap_tokens())
            .map_err(|error| error.to_string())
    }

    /// Infer independent, pre-tokenized NTDB chunks without L1 or document aggregation.
    pub fn infer_distributed_ntdb_chunks(
        &self,
        model_ids: HashSet<String>,
        chunks: &[PreparedNtdbChunk],
        document_chunk_count: usize,
        operating_point: NtdbOperatingPoint,
    ) -> Result<Vec<NtdbModelChunkInferences>, String> {
        self.ntdb_executor
            .as_ref()
            .ok_or_else(|| "NTDB L2 runtime is not initialized".to_string())?
            .lock()
            .map_err(|error| format!("NTDB executor mutex poisoned: {error}"))?
            .infer_prepared_chunks_for_models(
                model_ids,
                chunks,
                document_chunk_count,
                operating_point,
            )
            .map_err(|error| error.to_string())
    }

    /// Run immediate unified L3 inference for promoted chunks without document aggregation.
    pub fn infer_distributed_unified_l3_chunks(
        &self,
        chunks: &[crate::ml::ntdb_executor::NtdbChunkInference],
        execution: &ScanExecution,
    ) -> Result<Vec<crate::pipeline::DistributedL3ChunkInference>, String> {
        self.l3_worker
            .infer_distributed_unified_chunks(chunks, execution)
    }

    /// Aggregate all unified L3 chunk outputs with the normal final result mapping.
    pub fn aggregate_distributed_unified_l3_chunks(
        &self,
        chunks: &[crate::pipeline::DistributedL3ChunkInference],
        l2_fallbacks: &[SecurityScanResult],
        execution: &ScanExecution,
        duration_ms: f64,
    ) -> Result<Vec<SecurityScanResult>, String> {
        self.l3_worker.aggregate_distributed_unified_chunks(
            chunks,
            l2_fallbacks,
            execution,
            duration_ms,
        )
    }

    /// Aggregate all worker L2 evidence and map it through the normal gateway thresholds.
    pub fn aggregate_distributed_ntdb_chunks(
        &self,
        inferred: &[NtdbModelChunkInferences],
        categories: &[SecurityCategory],
        execution: &ScanExecution,
        duration_ms: f64,
    ) -> Result<Vec<SecurityScanResult>, String> {
        let decisions = self
            .ntdb_executor
            .as_ref()
            .ok_or_else(|| "NTDB L2 runtime is not initialized".to_string())?
            .lock()
            .map_err(|error| format!("NTDB executor mutex poisoned: {error}"))?
            .aggregate_chunk_inferences(inferred, execution.ntdb_operating_point())
            .map_err(|error| error.to_string())?;
        let configs = categories
            .iter()
            .copied()
            .flat_map(|category| ntdb_l2_model_configs_for_category(execution, category))
            .collect::<Vec<_>>();
        Ok(decisions
            .iter()
            .filter_map(|decision| {
                configs
                    .iter()
                    .find(|config| config.model_id == decision.model_id)
                    .map(|config| ntdb_l2_scan_result(*config, decision, execution, duration_ms))
            })
            .collect())
    }

    /// Execute only the normal L1 portion with the gateway's effective configuration.
    pub fn distributed_execution(&self) -> ScanExecution {
        self.scan_execution()
    }

    pub fn scan_distributed_l1(
        &self,
        inputs: &[ExternalL1Input],
        execution: &ScanExecution,
    ) -> Vec<SecurityScanResult> {
        self.scan_l1_inputs(inputs, execution)
    }

    /// Resolve canonical distributed pipeline bindings without executing scanners.
    pub fn distributed_l2_pipelines(
        &self,
        categories: &[SecurityCategory],
        execution: &ScanExecution,
    ) -> Vec<DistributedL2Pipeline> {
        categories
            .iter()
            .flat_map(|category| ntdb_l2_model_configs_for_category(execution, *category))
            .map(|config| DistributedL2Pipeline {
                pipeline_id: config.model_id.to_string(),
                category: config.category,
                model_id: config.model_id.to_string(),
                public_model: config.public_model.to_string(),
                has_l3: config.has_l3,
            })
            .collect()
    }

    /// Run L1 and resolve the exact conditional-gate/model plan for distributed L2.
    pub fn plan_distributed_l2(
        &self,
        inputs: &[ExternalL1Input],
        metadata: &serde_json::Value,
        execution: &ScanExecution,
    ) -> DistributedL2Plan {
        let (l1_results, l1_failures) =
            request_queue::split_results(self.scan_l1_inputs(inputs, execution));
        let mut gate_results = l1_results
            .iter()
            .filter_map(request_queue::gate_result)
            .collect::<Vec<_>>();
        gate_results.extend(request_queue::rejected_l1_candidate_gate_results(
            &l1_results,
        ));
        let categories = inputs
            .iter()
            .filter(|input| {
                crate::pipeline::conditional_gate::pipeline_allowed(
                    execution,
                    SecurityLevel::L2,
                    input.category.as_str(),
                    metadata,
                    &gate_results,
                )
            })
            .map(|input| input.category)
            .collect::<Vec<_>>();
        let mut l2_execution = execution.clone();
        let mut gates = l2_execution.gates().clone();
        for category in &categories {
            for config in ntdb_l2_model_configs_for_category(&l2_execution, *category) {
                if ![config.model_id, config.public_model]
                    .into_iter()
                    .all(|model| {
                        crate::pipeline::conditional_gate::pipeline_allowed(
                            execution,
                            SecurityLevel::L2,
                            model,
                            metadata,
                            &gate_results,
                        )
                    })
                {
                    gates.set_model(config.model_id, false);
                    gates.set_model(config.public_model, false);
                }
            }
        }
        l2_execution.set_gates(gates);
        if l2_execution.allows_level(SecurityLevel::L3) && l2_execution.l3_policy().enabled {
            l2_execution.set_defer_l3(true);
        }
        let pipelines = self.distributed_l2_pipelines(&categories, &l2_execution);
        let model_ids = pipelines
            .iter()
            .map(|pipeline| pipeline.model_id.clone())
            .collect();
        DistributedL2Plan {
            l1_results,
            l1_failures,
            categories,
            model_ids,
            pipelines,
            execution: l2_execution,
            gate_results,
        }
    }

    /// Resolve L3 policy overrides and eligibility after distributed L2 aggregation.
    pub fn plan_distributed_l3(
        &self,
        l1_gate_results: &[crate::GateResult],
        l2_results: &[SecurityScanResult],
        metadata: &serde_json::Value,
        execution: &ScanExecution,
    ) -> DistributedL3Plan {
        let mut gate_results = l1_gate_results.to_vec();
        gate_results.extend(l2_results.iter().filter_map(request_queue::gate_result));
        let execution = crate::pipeline::conditional_gate::apply_l3_policy_overrides(
            execution,
            metadata,
            &gate_results,
        );
        let categories = l2_results
            .iter()
            .filter(|result| crate::pipeline::has_l3_pending(result))
            .filter(|result| {
                crate::pipeline::conditional_gate::pipeline_allowed(
                    &execution,
                    SecurityLevel::L3,
                    &result.category,
                    metadata,
                    &gate_results,
                ) && crate::pipeline::conditional_gate::pipeline_allowed(
                    &execution,
                    SecurityLevel::L3,
                    &result.model,
                    metadata,
                    &gate_results,
                )
            })
            .filter_map(|result| result.category.parse().ok())
            .collect();
        DistributedL3Plan {
            categories,
            execution,
            gate_results,
        }
    }

    /// Return the calibrated NTDB final-decision threshold set used by subsequent scans.
    pub fn ntdb_decision_threshold_point(&self) -> NtdbOperatingPoint {
        self.scan_execution().ntdb_decision_threshold_point()
    }

    /// Replace the pipeline-specific `dynamic-pii` configuration.
    pub fn set_dynamic_pii_config(&self, config: DynamicPiiConfig) -> Result<(), String> {
        let config = config.validated()?;
        *self
            .dynamic_pii_config
            .lock()
            .expect("dynamic-pii config mutex poisoned") = config;
        Ok(())
    }

    /// Replace the user policies and allowlist of the `shell_command` verdict.
    /// A loaded pipeline applies them at once (a refused configuration changes
    /// nothing); otherwise `warmup` applies them.
    pub fn set_shell_command_policy_config(&self, config: ShellPolicyConfig) -> Result<(), String> {
        if let Some(pipeline) = &self.shell_command_pipeline {
            pipeline.configure(&config)?;
        }
        *self
            .shell_command_policy_config
            .lock()
            .expect("shell_command policy config mutex poisoned") = config;
        Ok(())
    }

    /// Accept a `shell_command` bundle with this manifest instead of the
    /// pinned release (synthetic bundles in tests).
    #[cfg(feature = "test-util")]
    pub fn pin_shell_command_manifest_for_tests(&mut self, manifest_sha256: impl Into<String>) {
        self.shell_command_manifest_sha256 = manifest_sha256.into();
    }

    /// Return the configured `shell_command` user policies and allowlist.
    pub fn shell_command_policy_config(&self) -> ShellPolicyConfig {
        self.shell_command_policy_config
            .lock()
            .expect("shell_command policy config mutex poisoned")
            .clone()
    }

    /// Return the currently configured `dynamic-pii` settings.
    pub fn dynamic_pii_config(&self) -> DynamicPiiConfig {
        self.dynamic_pii_config
            .lock()
            .expect("dynamic-pii config mutex poisoned")
            .clone()
    }

    /// Return the execution state that should be consumed by this scan.
    fn scan_execution(&self) -> ScanExecution {
        self.execution
            .lock()
            .expect("execution mutex poisoned")
            .clone()
            .with_max_level(self.max_level)
    }

    /// Whether the shell command model is configured and allowed by the gates.
    fn shell_command_configured(&self, execution: &ScanExecution) -> bool {
        self.categories.contains(&SecurityCategory::ShellCommand)
            && execution.allows_level(SecurityLevel::L1)
            && execution
                .gates()
                .native
                .allows_model(SHELL_COMMAND_ASSET.model)
    }

    fn level_enabled(&self, execution: &ScanExecution, level: SecurityLevel) -> bool {
        execution.allows_level(level)
    }

    fn model_enabled(&self, execution: &ScanExecution, model: &str) -> bool {
        execution.gates().native.allows_model(model)
    }

    #[cfg(test)]
    fn scan_category_with_execution(
        &self,
        input: &ExternalL1Input,
        execution: &ScanExecution,
    ) -> Vec<SecurityScanResult> {
        self.scan_category_prepared(
            input,
            execution,
            &crate::threat::NativeText::new(input.text.as_ref()),
        )
    }

    fn scan_category_prepared(
        &self,
        input: &ExternalL1Input,
        execution: &ScanExecution,
        prepared: &crate::threat::NativeText<'_>,
    ) -> Vec<SecurityScanResult> {
        let category = input.category;
        let text = input.text.as_ref();
        let mut results = Vec::new();
        let producers = self.native_engine.producers(category);
        if !producers.is_empty() && self.level_enabled(execution, SecurityLevel::L1) {
            let control = ScanControl::default();
            let gates = &execution.gates().native;
            let native_results = producers
                .iter()
                .filter(|producer| producer.enabled(gates))
                .map(|producer| {
                    run_measured_l1_detector(category, producer.id(), text.len(), || {
                        native_engine_scan_result(
                            category,
                            producer.id(),
                            text,
                            self.native_engine
                                .run_producer(producer, prepared, gates, &control),
                            execution,
                        )
                    })
                })
                .collect::<Vec<_>>();
            if category == SecurityCategory::Injection {
                if !native_results.is_empty() {
                    results.push(injection_l1::aggregate(text, native_results));
                }
            } else {
                results.extend(native_results);
            }
        }
        match category {
            SecurityCategory::Threat => {
                if self.level_enabled(execution, SecurityLevel::L1)
                    && self.model_enabled(execution, "native:threat_l1")
                {
                    if let Some(ref native) = self.threat_pipeline {
                        results.push(run_measured_l1_detector(
                            category,
                            "native:threat_l1",
                            text.len(),
                            || {
                                timed_native_detection_scan_result(
                                    category,
                                    "native:threat_l1",
                                    text,
                                    || {
                                        native.detect_prepared(prepared, |id| {
                                            execution.gates().native.allows_rule(id)
                                        })
                                    },
                                )
                            },
                        ));
                    }
                }
            }
            SecurityCategory::ShellCommand => {
                if self.level_enabled(execution, SecurityLevel::L1)
                    && self.model_enabled(execution, SHELL_COMMAND_ASSET.model)
                {
                    let model = SHELL_COMMAND_ASSET.model;
                    results.push(run_measured_l1_detector(
                        category,
                        model,
                        text.len(),
                        || match self.shell_command_pipeline {
                            Some(ref pipeline) => {
                                timed_native_detection_scan_result(category, model, text, || {
                                    pipeline.detect_with_rules(text, |id| {
                                        execution.gates().native.allows_rule(id)
                                    })
                                })
                            }
                            None => scanner_error_scan_result(
                                category,
                                model,
                                format!("{model} model is not loaded; call warmup first"),
                            ),
                        },
                    ));
                }
            }
            SecurityCategory::Pii
            | SecurityCategory::Dlp
            | SecurityCategory::Injection
            | SecurityCategory::DynamicPii => {}
            SecurityCategory::SensitiveDocument
            | SecurityCategory::ToolClass
            | SecurityCategory::ToolAction
            | SecurityCategory::ToolTags
            | SecurityCategory::Routing => {}
        }

        if self.level_enabled(execution, SecurityLevel::L1) {
            let detectors = self
                .external_l1
                .lock()
                .expect("external L1 registry mutex poisoned")
                .get(&category)
                .cloned()
                .unwrap_or_default();
            for detector in detectors {
                let model = format!("external:{}", detector.id());
                if !self.model_enabled(execution, &model) {
                    continue;
                }
                results.push(run_measured_l1_detector(
                    category,
                    &model,
                    text.len(),
                    || {
                        let started = Instant::now();
                        match catch_unwind(AssertUnwindSafe(|| detector.evaluate(input))) {
                            Ok(mut result) => {
                                result.level = SecurityLevel::L1.as_str().to_string();
                                l1_scan_result_with_duration(
                                    category,
                                    model.clone(),
                                    "external_l1",
                                    result,
                                    started.elapsed().as_secs_f64() * 1000.0,
                                )
                            }
                            Err(payload) => scanner_error_scan_result(
                                category,
                                model.clone(),
                                panic_message(payload),
                            ),
                        }
                    },
                ));
            }
        }
        results
    }

    fn scan_ntdb_l2_categories(
        &self,
        categories: &[SecurityCategory],
        text: &str,
        execution: &ScanExecution,
    ) -> Vec<SecurityScanResult> {
        let mut metrics = PhaseMetricScope::new(
            "security_ntdb_l2_categories",
            format!("categories={} text_bytes={}", categories.len(), text.len()),
        );
        let requested = categories
            .iter()
            .copied()
            .flat_map(|category| ntdb_l2_model_configs_for_category(execution, category))
            .collect::<Vec<_>>();
        if requested.is_empty() {
            return Vec::new();
        }

        let Some(executor_mutex) = &self.ntdb_executor else {
            return requested
                .into_iter()
                .map(|config| {
                    ntdb_l2_error_scan_result(config, "NTDB L2 runtime is not initialized")
                })
                .collect();
        };

        let mut cached_results: HashMap<&'static str, Vec<SecurityScanResult>> = HashMap::new();
        let mut missing_configs = Vec::new();
        {
            let executor = match executor_mutex.lock() {
                Ok(executor) => executor,
                Err(err) => {
                    return requested
                        .into_iter()
                        .map(|config| {
                            ntdb_l2_error_scan_result(
                                config,
                                format!("NTDB executor mutex poisoned: {err}"),
                            )
                        })
                        .collect();
                }
            };

            for config in &requested {
                let Some(aggregator_ids) = executor.model_aggregator_ids(config.model_id) else {
                    missing_configs.push(*config);
                    continue;
                };

                let mut cached_for_category = Vec::with_capacity(aggregator_ids.len());
                let mut all_cached = true;
                for aggregator_id in aggregator_ids {
                    let namespace = ntdb_l2_cache_namespace(config.model_id, &aggregator_id);
                    if let Some((result, layers, parts)) =
                        self.ntdb_decision_cache.get(&namespace, text, execution)
                    {
                        let mut cached =
                            scan_result(config.category, config.public_model, result, layers);
                        cached.decision = parts.decision;
                        cached.label_scores = parts.label_scores;
                        cached.evidence_spans = parts.evidence_spans;
                        cached_for_category.push(cached);
                    } else {
                        all_cached = false;
                        break;
                    }
                }

                if all_cached {
                    cached_results.insert(config.model_id, cached_for_category);
                } else {
                    missing_configs.push(*config);
                }
            }
        }
        metrics.checkpoint(
            "after_cache_check",
            format!(
                "requested={} cached_models={} missing={}",
                requested.len(),
                cached_results.len(),
                missing_configs.len()
            ),
        );
        let mut scored_results = cached_results;
        if !missing_configs.is_empty() {
            let model_ids = missing_configs
                .iter()
                .map(|config| config.model_id)
                .collect::<Vec<_>>();
            let scoring_started = Instant::now();
            metrics.checkpoint(
                "before_executor_score",
                format!("model_ids={}", model_ids.len()),
            );
            let decisions = match executor_mutex.lock() {
                Ok(mut executor) => executor.score_models_with_overlap(
                    model_ids.iter().copied(),
                    text,
                    execution.ntdb_operating_point(),
                    execution.chunk_overlap_tokens(),
                ),
                Err(err) => Err(Box::new(std::io::Error::other(format!(
                    "NTDB executor mutex poisoned: {err}"
                )))
                    as Box<dyn std::error::Error + Send + Sync>),
            };
            metrics.checkpoint(
                "after_executor_score",
                format!("model_ids={}", model_ids.len()),
            );
            let duration_ms = scoring_started.elapsed().as_secs_f64() * 1000.0;

            match decisions {
                Ok(decisions) => {
                    for decision in decisions {
                        let Some(config) = missing_configs
                            .iter()
                            .find(|config| config.model_id == decision.model_id)
                            .copied()
                        else {
                            continue;
                        };
                        let mut result =
                            ntdb_l2_scan_result(config, &decision, execution, duration_ms);
                        for layer in &mut result.layers {
                            layer
                                .details
                                .entry("decision_cache_hit".to_string())
                                .or_insert_with(|| serde_json::json!(false));
                        }
                        let evaluation = EvaluationResult {
                            class_name: result.class_name.clone(),
                            confidence: result.confidence,
                            level: result.level.clone(),
                        };
                        let namespace =
                            ntdb_l2_cache_namespace(&decision.model_id, &decision.aggregator_id);
                        self.ntdb_decision_cache.insert(
                            &namespace,
                            text,
                            execution,
                            &evaluation,
                            &result.layers,
                            super::decision_cache::CachedScanParts {
                                decision: result.decision.clone(),
                                label_scores: result.label_scores.clone(),
                                evidence_spans: result.evidence_spans.clone(),
                            },
                        );
                        scored_results
                            .entry(config.model_id)
                            .or_default()
                            .push(result);
                    }
                    metrics.checkpoint("after_result_build", "");
                }
                Err(err) => {
                    let message = err.to_string();
                    for config in &missing_configs {
                        scored_results
                            .entry(config.model_id)
                            .or_default()
                            .push(ntdb_l2_error_scan_result(*config, message.clone()));
                    }
                }
            }
        }

        let mut results = Vec::new();
        for config in requested {
            if let Some(mut scored) = scored_results.remove(config.model_id) {
                results.append(&mut scored);
            }
        }
        metrics.checkpoint("after_result_mapping", format!("results={}", results.len()));
        results
    }

    fn scan_l1_inputs(
        &self,
        inputs: &[ExternalL1Input],
        execution: &ScanExecution,
    ) -> Vec<SecurityScanResult> {
        use rayon::prelude::*;

        let mut execution = execution.clone();
        if execution.allows_level(SecurityLevel::L3) && execution.l3_policy().enabled {
            execution.set_defer_l3(true);
        }

        // Equal text supplied for different categories shares request-local views.
        // Distinct external inputs retain independent preparation and offsets.
        let mut prepared = HashMap::new();
        for input in inputs {
            let text = input.text.as_ref();
            prepared
                .entry(text)
                .or_insert_with(|| crate::threat::NativeText::new(text));
        }
        let mut results = inputs
            .par_iter()
            .map(|input| {
                self.scan_category_prepared(input, &execution, &prepared[input.text.as_ref()])
            })
            .collect::<Vec<_>>();
        crate::post_prediction::resolve_dlp_pii_overlaps(inputs, &mut results);
        results.into_iter().flatten().collect()
    }

    fn scan_l2_inputs(
        &self,
        inputs: &[ExternalL1Input],
        execution: &ScanExecution,
        metadata: &serde_json::Value,
        gate_results: &[crate::GateResult],
    ) -> Vec<SecurityScanResult> {
        let mut metrics = PhaseMetricScope::new(
            "security_scan_l2_inputs",
            format!(
                "inputs={} gate_results={}",
                inputs.len(),
                gate_results.len()
            ),
        );
        if !execution.allows_level(SecurityLevel::L2) {
            return self.direct_l3_results(inputs, execution, metadata, gate_results);
        }
        let mut execution = execution.clone();
        if execution.allows_level(SecurityLevel::L3) && execution.l3_policy().enabled {
            execution.set_defer_l3(true);
        }
        let allowed_categories = inputs
            .iter()
            .filter(|input| {
                crate::pipeline::conditional_gate::pipeline_allowed(
                    &execution,
                    SecurityLevel::L2,
                    input.category.as_str(),
                    metadata,
                    gate_results,
                )
            })
            .collect::<Vec<_>>();
        metrics.checkpoint(
            "after_allowed_categories",
            format!("allowed={}", allowed_categories.len()),
        );
        let mut l2_execution = execution.clone();
        let mut l2_gates = l2_execution.gates().clone();
        for input in &allowed_categories {
            for config in ntdb_l2_model_configs_for_category(&l2_execution, input.category) {
                let model_allowed =
                    [config.model_id, config.public_model]
                        .into_iter()
                        .all(|model| {
                            crate::pipeline::conditional_gate::pipeline_allowed(
                                &execution,
                                SecurityLevel::L2,
                                model,
                                metadata,
                                gate_results,
                            )
                        });
                if !model_allowed {
                    l2_gates.set_model(config.model_id, false);
                    l2_gates.set_model(config.public_model, false);
                }
            }
        }
        l2_execution.set_gates(l2_gates);
        metrics.checkpoint("after_gate_filtering", "");
        let mut results = Vec::new();
        if let Some(first) = allowed_categories.first() {
            if allowed_categories
                .iter()
                .all(|input| input.text == first.text)
            {
                let categories = allowed_categories
                    .iter()
                    .map(|input| input.category)
                    .collect::<Vec<_>>();
                metrics.checkpoint(
                    "before_shared_ntdb_l2",
                    format!("categories={}", categories.len()),
                );
                results.extend(self.scan_ntdb_l2_categories(
                    &categories,
                    &first.text,
                    &l2_execution,
                ));
                metrics.checkpoint("after_shared_ntdb_l2", format!("results={}", results.len()));
            } else {
                for input in allowed_categories {
                    metrics.checkpoint(
                        "before_single_ntdb_l2",
                        format!("category={}", input.category.as_str()),
                    );
                    results.extend(self.scan_ntdb_l2_categories(
                        &[input.category],
                        &input.text,
                        &l2_execution,
                    ));
                    metrics
                        .checkpoint("after_single_ntdb_l2", format!("results={}", results.len()));
                }
            }
        }
        metrics.checkpoint("done", format!("results={}", results.len()));
        results
    }
}