Skip to main content

patronus_ark/
types.rs

1// SPDX-License-Identifier: GPL-3.0-only
2use std::collections::HashMap;
3
4use serde::{Deserialize, Serialize};
5
6pub type RequestId = String;
7
8/// Lifecycle state for an accepted queued request until its terminal event is consumed.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum SecurityRequestState {
11    /// At least one planned scanner or promoted L3 job can still publish an event.
12    Running,
13    /// All planned work has reached a terminal outcome.
14    Finished(SecurityRequestCompletion),
15}
16
17/// Terminal outcome for one accepted queued request.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum SecurityRequestCompletion {
20    /// Every planned scanner completed without a failure.
21    Complete,
22    /// At least one usable result and at least one failure were produced.
23    Degraded { failures: Vec<SecurityFailure> },
24    /// No planned scanner produced a usable result.
25    Failed { failures: Vec<SecurityFailure> },
26}
27
28/// Typed failure attached to one scanner stage.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct SecurityFailure {
31    pub stage: SecurityFailureStage,
32    pub level: Option<SecurityLevel>,
33    pub detector_id: Option<String>,
34    pub kind: SecurityFailureKind,
35    pub retryable: bool,
36    pub message: String,
37}
38
39/// Runtime stage at which a security operation failed.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum SecurityFailureStage {
42    Warmup,
43    Asset,
44    Scanner,
45    Inference,
46    Queue,
47    Worker,
48}
49
50/// Stable failure classification for product logic.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SecurityFailureKind {
53    NotReady,
54    MissingAsset,
55    IntegrityFailure,
56    InitializationFailure,
57    InferenceFailure,
58    Timeout,
59    QueueFull,
60    WorkerUnavailable,
61    Internal,
62}
63
64/// Readiness of the configured scanner runtime by security level.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct SecurityRuntimeReadiness {
67    pub l1: SecurityLevelReadiness,
68    pub l2: SecurityLevelReadiness,
69    pub l3: SecurityLevelReadiness,
70}
71
72/// Readiness of model assets on disk before runtime warmup.
73///
74/// Native L1 rule scanners require no model assets, so `l1` is configured only
75/// for model-backed L1 categories such as `shell_command`. Runtime readiness
76/// remains a separate contract.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct SecurityAssetReadiness {
79    pub l1: SecurityLevelReadiness,
80    pub l2: SecurityLevelReadiness,
81    pub l3: SecurityLevelReadiness,
82}
83
84/// Progress emitted while configured model assets are downloaded.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct SecurityAssetProgress {
87    /// Pipeline category whose assets are currently being prepared.
88    pub category: SecurityCategory,
89    /// Public model identifier from the asset manifest.
90    pub model: String,
91    /// Files already present or downloaded for this model.
92    pub completed_files: usize,
93    /// Total files required by this model.
94    pub total_files: usize,
95}
96
97/// Thread-safe callback used by asset preparation workers.
98pub type SecurityAssetProgressCallback =
99    std::sync::Arc<dyn Fn(SecurityAssetProgress) + Send + Sync>;
100
101/// Readiness of one security level before request execution.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum SecurityLevelReadiness {
104    Ready,
105    NotConfigured,
106    NotReady { failures: Vec<SecurityFailure> },
107}
108
109impl std::fmt::Display for SecurityFailure {
110    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        write!(formatter, "{}", self.message)
112    }
113}
114
115impl std::error::Error for SecurityFailure {}
116
117impl SecurityFailureStage {
118    pub fn as_str(self) -> &'static str {
119        match self {
120            Self::Warmup => "warmup",
121            Self::Asset => "asset",
122            Self::Scanner => "scanner",
123            Self::Inference => "inference",
124            Self::Queue => "queue",
125            Self::Worker => "worker",
126        }
127    }
128}
129
130impl SecurityFailureKind {
131    pub fn as_str(self) -> &'static str {
132        match self {
133            Self::NotReady => "not_ready",
134            Self::MissingAsset => "missing_asset",
135            Self::IntegrityFailure => "integrity_failure",
136            Self::InitializationFailure => "initialization_failure",
137            Self::InferenceFailure => "inference_failure",
138            Self::Timeout => "timeout",
139            Self::QueueFull => "queue_full",
140            Self::WorkerUnavailable => "worker_unavailable",
141            Self::Internal => "internal",
142        }
143    }
144}
145
146/// Ordered event published by the queue.
147#[derive(Debug, Clone)]
148pub enum QueuedSecurityEvent {
149    /// One usable scanner result.
150    Result(QueuedSecurityScanResult),
151    /// Non-authoritative progress for UI status.
152    Progress(QueuedSecurityProgress),
153    /// Non-authoritative interim result for UI preview.
154    Provisional(QueuedSecurityScanResult),
155    /// The unique terminal event for an accepted request.
156    Finished {
157        request_id: RequestId,
158        completion: SecurityRequestCompletion,
159    },
160}
161
162impl QueuedSecurityEvent {
163    /// Return the request id carried by this event.
164    pub fn request_id(&self) -> &str {
165        match self {
166            Self::Result(queued) => &queued.request_id,
167            Self::Progress(progress) => &progress.request_id,
168            Self::Provisional(queued) => &queued.request_id,
169            Self::Finished { request_id, .. } => request_id,
170        }
171    }
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
175/// Progress emitted while L3 resolves a multi-chunk request.
176pub struct QueuedSecurityProgress {
177    pub request_id: RequestId,
178    pub category: String,
179    pub model: String,
180    pub stage: String,
181    pub completed_chunks: usize,
182    pub total_chunks: usize,
183    pub inferred_chunks: usize,
184    pub propagated_chunks: usize,
185    pub cache_hits: usize,
186    pub early_exit: bool,
187    pub coverage: f64,
188    pub details: HashMap<String, serde_json::Value>,
189}
190
191#[derive(Debug, Clone)]
192/// A completed queued scan result together with the request that produced it.
193pub struct QueuedSecurityScanResult {
194    /// Request id returned by `SecurityGateway::enqueue`.
195    pub request_id: RequestId,
196    /// Complete classifier result published by L1/L2 or the L3 worker.
197    pub result: SecurityScanResult,
198}
199
200#[derive(Debug, Clone)]
201/// Public scan result returned by `SecurityGateway` methods.
202pub struct SecurityScanResult {
203    /// Category that was scanned, for example `injection` or `dlp`.
204    pub category: String,
205    /// Stable class label for the final decision.
206    pub class_name: String,
207    /// Final confidence score in the inclusive range `0.0..=1.0` when available.
208    pub confidence: f64,
209    /// Highest layer that contributed the final decision.
210    pub level: String,
211    /// Model or native scanner name that produced the final decision.
212    pub model: String,
213    /// Sum of recorded layer durations, in milliseconds.
214    pub duration_ms: f64,
215    /// Ordered layer evidence that explains the final decision.
216    pub layers: Vec<LayerResult>,
217    /// Internal L2 chunk outputs reused by L3 planning. This field is cleared
218    /// before results are published outside the gateway.
219    #[doc(hidden)]
220    pub internal_l2_chunk_outputs: Vec<crate::ml::ntdb_executor::L2ChunkOutput>,
221    /// Exact entity evidence returned by span-producing pipelines.
222    pub evidence_spans: Vec<crate::dynamic_pii::EvidenceSpan>,
223    /// Per-label scores for multi-label classifier outputs.
224    pub label_scores: Vec<LabelScore>,
225    /// Structured classifier decision contract for policy consumers.
226    pub decision: Option<DecisionEnvelope>,
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
230/// Maximum scanner depth to run.
231pub enum SecurityLevel {
232    /// Native rule-based checks only.
233    L1 = 1,
234    /// Native checks plus L2 model-backed classifiers when assets are available.
235    L2 = 2,
236    /// Native, L2, and L3 model-backed classifiers when assets are available.
237    L3 = 3,
238}
239
240impl SecurityLevel {
241    /// Return the canonical uppercase level string.
242    pub fn as_str(self) -> &'static str {
243        match self {
244            SecurityLevel::L1 => "L1",
245            SecurityLevel::L2 => "L2",
246            SecurityLevel::L3 => "L3",
247        }
248    }
249}
250
251/// Serializes the canonical [`SecurityLevel::as_str`] name.
252impl Serialize for SecurityLevel {
253    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
254        serializer.serialize_str(self.as_str())
255    }
256}
257
258/// Deserializes every name [`str::parse`] accepts (`L1`, `l1`, `1`, ...).
259impl<'de> Deserialize<'de> for SecurityLevel {
260    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
261        String::deserialize(deserializer)?
262            .parse()
263            .map_err(serde::de::Error::custom)
264    }
265}
266
267impl std::str::FromStr for SecurityLevel {
268    type Err = String;
269
270    fn from_str(s: &str) -> Result<Self, Self::Err> {
271        match s.to_lowercase().as_str() {
272            "1" | "l1" => Ok(SecurityLevel::L1),
273            "2" | "l2" => Ok(SecurityLevel::L2),
274            "3" | "l3" => Ok(SecurityLevel::L3),
275            _ => Err(format!("Unknown security level: {}", s)),
276        }
277    }
278}
279
280#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
281/// How model pipelines execute ONNX L3 fallback batches.
282pub enum OnnxBatchMode {
283    /// Keep the existing lazy per-text ONNX execution path.
284    #[default]
285    LazyBatches,
286    /// Execute all L3 fallback texts as one ONNX tensor batch where possible.
287    TensorBatch,
288}
289
290impl OnnxBatchMode {
291    /// Return the canonical snake_case mode string.
292    pub fn as_str(self) -> &'static str {
293        match self {
294            OnnxBatchMode::LazyBatches => "lazy_batches",
295            OnnxBatchMode::TensorBatch => "tensor_batch",
296        }
297    }
298}
299
300impl std::str::FromStr for OnnxBatchMode {
301    type Err = String;
302
303    fn from_str(s: &str) -> Result<Self, Self::Err> {
304        match s.to_lowercase().replace('-', "_").as_str() {
305            "lazy" | "lazy_batches" | "lazybatches" => Ok(OnnxBatchMode::LazyBatches),
306            "tensor" | "tensor_batch" | "tensorbatch" => Ok(OnnxBatchMode::TensorBatch),
307            _ => Err(format!("Unknown ONNX batch mode: {}", s)),
308        }
309    }
310}
311
312#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
313/// Calibrated NTDB operating point selected from each package manifest.
314pub enum NtdbOperatingPoint {
315    BestF1,
316    #[default]
317    BestPromote,
318    /// Internal Ark API routing profile: use utility promotion only for an
319    /// Injection document with at most two normal chunks.
320    ArkApiShortInjectionUtility,
321    BestFprInF1,
322    BestFnrInF1,
323    BestLatencyInF1,
324}
325
326impl NtdbOperatingPoint {
327    /// Return the manifest key for this operating point.
328    pub fn as_str(self) -> &'static str {
329        match self {
330            Self::BestF1 => "best_f1",
331            Self::BestPromote => "best_promote",
332            Self::ArkApiShortInjectionUtility => "ark_api_short_injection_utility",
333            Self::BestFprInF1 => "best_fpr_in_f1",
334            Self::BestFnrInF1 => "best_fnr_in_f1",
335            Self::BestLatencyInF1 => "best_latency_in_f1",
336        }
337    }
338}
339
340impl std::str::FromStr for NtdbOperatingPoint {
341    type Err = String;
342
343    fn from_str(s: &str) -> Result<Self, Self::Err> {
344        match s.to_lowercase().replace('-', "_").as_str() {
345            "best_f1" => Ok(Self::BestF1),
346            "best_promote" => Ok(Self::BestPromote),
347            "ark_api_short_injection_utility" => Ok(Self::ArkApiShortInjectionUtility),
348            "best_fpr_in_f1" => Ok(Self::BestFprInF1),
349            "best_fnr_in_f1" => Ok(Self::BestFnrInF1),
350            "best_latency_in_f1" => Ok(Self::BestLatencyInF1),
351            _ => Err(format!("Unknown NTDB operating point: {s}")),
352        }
353    }
354}
355
356#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
357/// Physical L3 classifier topology.
358pub enum L3Strategy {
359    /// Each promoted pipeline executes its own L3 model.
360    #[default]
361    Dedicated,
362    /// Promoted classifier pipelines share one request-local multi-head model run.
363    Multi,
364}
365
366impl L3Strategy {
367    pub fn as_str(self) -> &'static str {
368        match self {
369            Self::Dedicated => "dedicated",
370            Self::Multi => "multi",
371        }
372    }
373}
374
375impl std::str::FromStr for L3Strategy {
376    type Err = String;
377
378    fn from_str(value: &str) -> Result<Self, Self::Err> {
379        match value.trim().to_lowercase().replace('-', "_").as_str() {
380            "dedicated" | "single" | "single_model" => Ok(Self::Dedicated),
381            "multi" | "multitask" | "multi_task" => Ok(Self::Multi),
382            _ => Err(format!("Unknown L3 strategy: {value}")),
383        }
384    }
385}
386
387#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(try_from = "GateConfig")]
389/// Caller-controlled execution gates for one scanner execution profile.
390///
391/// Unspecified rules use the shared credentials/secrets-only DLP default;
392/// other execution gates default to enabled. Diagnostic `explain` and the
393/// scored PII and DLP modes are opt-in. `max_level` is still enforced by
394/// `ScanExecution`, so a gate can only further restrict the configured scanner.
395///
396/// Deserializes from the one gate schema of every host (Python
397/// `execution_gates`, Ark API `gates`): the native keys `rules`, `models`,
398/// `pii_mode`, `dlp_mode` and `explain`, the level switches `l1`, `l2` and
399/// `l3`, `conditional` and the L3 worker policy `l3_policy`. Unknown keys and
400/// out-of-range values are refused.
401pub struct ScanGateMatrix {
402    /// Native rule, model, mode and `explain` gates, shared with Ark Core.
403    pub native: crate::NativeGates,
404    /// Optional L1 override. `None` means enabled.
405    pub l1: Option<bool>,
406    /// Optional L2 override. `None` means enabled.
407    pub l2: Option<bool>,
408    /// Optional L3 override. `None` means enabled.
409    pub l3: Option<bool>,
410    /// Request-context and prior-result conditions applied before L2 or L3.
411    pub conditional: Vec<ConditionalPipelineGate>,
412    /// L3 worker scheduling policy.
413    pub l3_policy: L3SchedulerPolicy,
414}
415
416#[derive(Debug, Clone)]
417/// Priority and timeout policy for centrally scheduled L3 work.
418pub struct L3SchedulerPolicy {
419    /// Whether model L3 work should be centrally queued by scan methods.
420    pub enabled: bool,
421    /// Ordered category/model priority list. Earlier entries run first.
422    pub priority: Vec<String>,
423    /// Per category/model timeout before an unstarted L3 job degrades.
424    pub ttl_ms: HashMap<String, u64>,
425    /// Initial execution-cost estimate per category/model. The worker replaces
426    /// this gradually with observed wall time while it is running.
427    pub estimated_cost_ms: HashMap<String, u64>,
428    /// Compute-time credit granted during one fair-scheduling round.
429    pub fairness_quantum_ms: u64,
430    /// Maximum queue wait before the oldest job bypasses priority and cost.
431    pub max_wait_ms: u64,
432    /// Multiplier applied to L2 confidence when L3 degrades.
433    pub degraded_factor: f64,
434    /// Whether L3 may stop once the final class is stable.
435    pub early_exit: L3EarlyExitMode,
436    /// Whether L3 should emit non-authoritative progress/provisional events.
437    pub progress: L3ProgressMode,
438    /// Logical chunk ordering strategy. This does not enable tensor batching.
439    pub clustering: L3ClusteringStrategy,
440    /// Number of high-priority members inferred per similarity cluster for
441    /// representative scheduling. Values below 1 are treated as 1.
442    pub representatives_per_cluster: usize,
443    /// Number of least-similar verification members inferred per cluster for
444    /// verify-representative scheduling. Values below 1 are treated as 1.
445    pub verify_representatives_per_cluster: usize,
446    /// Minimum request-local similarity required to place two chunks in the
447    /// same representative cluster.
448    pub min_cluster_similarity: f64,
449    /// Maximum number of chunks assigned to one representative cluster.
450    pub max_cluster_size: usize,
451    /// Optional execution-policy overrides keyed by pipeline category or model.
452    /// Category keys take precedence over model keys.
453    pub pipelines: HashMap<String, L3PipelinePolicy>,
454}
455
456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
457#[serde(deny_unknown_fields)]
458/// Optional per-pipeline overrides for L3 chunk execution.
459pub struct L3PipelinePolicy {
460    /// Chunk execution strategy. `None` inherits the request-wide default.
461    #[serde(default)]
462    pub clustering: Option<L3ClusteringStrategy>,
463    /// Representatives inferred from the high-priority side of each cluster.
464    #[serde(default)]
465    pub representatives_per_cluster: Option<usize>,
466    /// Least-similar members used to verify a representative cluster.
467    #[serde(default)]
468    pub verify_representatives_per_cluster: Option<usize>,
469    /// Minimum request-local similarity required for cluster membership.
470    #[serde(default)]
471    pub min_cluster_similarity: Option<f64>,
472    /// Maximum number of members allowed in one cluster.
473    #[serde(default)]
474    pub max_cluster_size: Option<usize>,
475    /// Chunk-output aggregation. `None` keeps the pipeline's built-in rule.
476    #[serde(default)]
477    pub aggregation: Option<L3AggregationStrategy>,
478    /// Early-exit scope. `None` inherits the request-wide default semantics.
479    #[serde(default)]
480    pub early_exit: Option<L3PipelineEarlyExit>,
481}
482
483#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
485/// Configurable aggregation for one L3 pipeline.
486pub enum L3AggregationStrategy {
487    AnyPositiveOrHighest {
488        positive_class: String,
489        threshold: f64,
490    },
491    HighestRiskAboveThresholdOrConfidence {
492        threshold: f64,
493    },
494    MajorityVoteOrHighest,
495}
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(rename_all = "snake_case")]
499/// Scope at which a stable per-pipeline L3 decision stops work.
500pub enum L3PipelineEarlyExit {
501    Disabled,
502    HeadStable,
503    RequestWidePositive,
504}
505
506#[derive(Debug, Clone, PartialEq)]
507/// Fully resolved execution settings for one pipeline and request.
508pub struct EffectiveL3PipelinePolicy {
509    pub clustering: L3ClusteringStrategy,
510    pub representatives_per_cluster: usize,
511    pub verify_representatives_per_cluster: usize,
512    pub min_cluster_similarity: f64,
513    pub max_cluster_size: usize,
514    pub aggregation: Option<L3AggregationStrategy>,
515    pub early_exit: L3PipelineEarlyExit,
516}
517
518#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(rename_all = "snake_case")]
520pub enum L3EarlyExitMode {
521    Disabled,
522    ClassStable,
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
526#[serde(rename_all = "snake_case")]
527pub enum L3ProgressMode {
528    Disabled,
529    Progress,
530    Provisional,
531}
532
533#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
534#[serde(rename_all = "snake_case")]
535pub enum L3ClusteringStrategy {
536    Disabled,
537    RankOnly,
538    Representative,
539    VerifyRepresentative,
540}
541
542#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
543#[serde(deny_unknown_fields)]
544/// One conditional L2/L3 pipeline gate.
545pub struct ConditionalPipelineGate {
546    /// Phase controlled by this gate. L1 is intentionally not supported.
547    pub level: SecurityLevel,
548    /// Optional category/model selector. `None` applies to every pipeline at the level.
549    #[serde(default)]
550    pub pipeline: Option<String>,
551    /// Condition that enables a normal gate or activates an `l3_policy` override.
552    pub when: GateExpression,
553    /// Optional L3 execution-policy override applied when `when` matches.
554    /// Policy gates do not suppress the pipeline when the condition is false.
555    #[serde(default)]
556    pub l3_policy: Option<L3PipelinePolicy>,
557}
558
559#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
560#[serde(rename_all = "snake_case")]
561/// Recursive expression over enqueue metadata and completed L1/L2 results.
562pub enum GateExpression {
563    All(Vec<GateExpression>),
564    Any(Vec<GateExpression>),
565    Not(Box<GateExpression>),
566    Metadata(MetadataCondition),
567    Result(ResultCondition),
568}
569
570#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
571#[serde(deny_unknown_fields)]
572/// Predicate over a dotted path in request metadata.
573pub struct MetadataCondition {
574    pub path: String,
575    #[serde(default)]
576    pub equals: Option<serde_json::Value>,
577    #[serde(default, rename = "in")]
578    pub in_values: Option<Vec<serde_json::Value>>,
579    #[serde(default)]
580    pub exists: Option<bool>,
581}
582
583#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
584#[serde(deny_unknown_fields)]
585/// Predicate over a previously completed L1/L2 pipeline result.
586pub struct ResultCondition {
587    pub pipeline: String,
588    #[serde(default)]
589    pub classes: Vec<String>,
590    #[serde(default)]
591    pub min_confidence: Option<f64>,
592}
593
594#[derive(Debug, Clone, PartialEq)]
595/// Minimal result view exposed to conditional gate evaluation.
596pub struct GateResult {
597    pub pipeline: String,
598    pub class_name: String,
599    pub confidence: f64,
600    pub level: SecurityLevel,
601}
602
603impl Default for L3SchedulerPolicy {
604    fn default() -> Self {
605        let mut ttl_ms = HashMap::new();
606        ttl_ms.insert("injection".to_string(), 15_000);
607        ttl_ms.insert("wolf-defender-small".to_string(), 15_000);
608        ttl_ms.insert("dynamic-pii".to_string(), 12_000);
609        ttl_ms.insert("gliner_small-v2.5-edge".to_string(), 12_000);
610        ttl_ms.insert("sensitive_document".to_string(), 12_000);
611        ttl_ms.insert("orca-sonar-document-classifier".to_string(), 12_000);
612        for name in [
613            "tool_class",
614            "tool_action",
615            "tool_tags",
616            "routing",
617            "threat",
618            "unified-v3-tool-class",
619            "unified-v3-tool-action",
620            "unified-v3-tool-tags",
621            "unified-v3-routing",
622            "unified-v3-threat",
623        ] {
624            ttl_ms.insert(name.to_string(), 10_500);
625        }
626        ttl_ms.insert("unified-multitask-model-augmented-v3".to_string(), 15_000);
627        let mut estimated_cost_ms = HashMap::new();
628        estimated_cost_ms.insert("injection".to_string(), 200);
629        estimated_cost_ms.insert("wolf-defender-small".to_string(), 200);
630        estimated_cost_ms.insert("dynamic-pii".to_string(), 240);
631        estimated_cost_ms.insert("gliner_small-v2.5-edge".to_string(), 240);
632        estimated_cost_ms.insert("sensitive_document".to_string(), 150);
633        estimated_cost_ms.insert("orca-sonar-document-classifier".to_string(), 150);
634        for name in [
635            "tool_class",
636            "tool_action",
637            "tool_tags",
638            "routing",
639            "threat",
640            "unified-v3-tool-class",
641            "unified-v3-tool-action",
642            "unified-v3-tool-tags",
643            "unified-v3-routing",
644            "unified-v3-threat",
645        ] {
646            estimated_cost_ms.insert(name.to_string(), 150);
647        }
648        estimated_cost_ms.insert("unified-multitask-model-augmented-v3".to_string(), 200);
649        Self {
650            enabled: true,
651            priority: vec![
652                "injection".to_string(),
653                "wolf-defender-small".to_string(),
654                "threat".to_string(),
655                "unified-v3-threat".to_string(),
656                "dynamic-pii".to_string(),
657                "gliner_small-v2.5-edge".to_string(),
658                "sensitive_document".to_string(),
659                "orca-sonar-document-classifier".to_string(),
660                "tool_class".to_string(),
661                "tool_action".to_string(),
662                "tool_tags".to_string(),
663                "routing".to_string(),
664                "unified-multitask-model-augmented-v3".to_string(),
665            ],
666            ttl_ms,
667            estimated_cost_ms,
668            fairness_quantum_ms: 50,
669            max_wait_ms: 2_000,
670            degraded_factor: 0.75,
671            early_exit: L3EarlyExitMode::ClassStable,
672            progress: L3ProgressMode::Disabled,
673            clustering: L3ClusteringStrategy::RankOnly,
674            representatives_per_cluster: 1,
675            verify_representatives_per_cluster: 1,
676            min_cluster_similarity: 0.90,
677            max_cluster_size: 8,
678            pipelines: HashMap::new(),
679        }
680    }
681}
682
683impl L3SchedulerPolicy {
684    /// Resolve request-wide defaults and a category/model override.
685    pub fn pipeline_policy(&self, category: &str, model: &str) -> EffectiveL3PipelinePolicy {
686        let pipeline = self
687            .pipelines
688            .get(category)
689            .or_else(|| self.pipelines.get(model));
690        let inherited_early_exit = match self.early_exit {
691            L3EarlyExitMode::Disabled => L3PipelineEarlyExit::Disabled,
692            L3EarlyExitMode::ClassStable
693                if category == "injection"
694                    || category == "threat"
695                    || model == "wolf-defender-small"
696                    || model == "unified-v3-threat" =>
697            {
698                L3PipelineEarlyExit::RequestWidePositive
699            }
700            L3EarlyExitMode::ClassStable => L3PipelineEarlyExit::HeadStable,
701        };
702        EffectiveL3PipelinePolicy {
703            clustering: pipeline
704                .and_then(|policy| policy.clustering)
705                .unwrap_or(self.clustering),
706            representatives_per_cluster: pipeline
707                .and_then(|policy| policy.representatives_per_cluster)
708                .unwrap_or(self.representatives_per_cluster)
709                .max(1),
710            verify_representatives_per_cluster: pipeline
711                .and_then(|policy| policy.verify_representatives_per_cluster)
712                .unwrap_or(self.verify_representatives_per_cluster)
713                .max(1),
714            min_cluster_similarity: pipeline
715                .and_then(|policy| policy.min_cluster_similarity)
716                .unwrap_or(self.min_cluster_similarity)
717                .clamp(0.0, 1.0),
718            max_cluster_size: pipeline
719                .and_then(|policy| policy.max_cluster_size)
720                .unwrap_or(self.max_cluster_size)
721                .max(1),
722            aggregation: pipeline.and_then(|policy| policy.aggregation.clone()),
723            early_exit: pipeline
724                .and_then(|policy| policy.early_exit)
725                .unwrap_or(inherited_early_exit),
726        }
727    }
728}
729
730impl ScanGateMatrix {
731    /// Explicitly enable all native rules, including opt-in DLP content families.
732    pub fn all_enabled() -> Self {
733        Self {
734            native: crate::NativeGates::all_enabled(),
735            ..Self::default()
736        }
737    }
738
739    /// Create a matrix with explicit level gates.
740    pub fn levels(l1: bool, l2: bool, l3: bool) -> Self {
741        Self {
742            l1: Some(l1),
743            l2: Some(l2),
744            l3: Some(l3),
745            ..Self::default()
746        }
747    }
748
749    /// Set one level gate.
750    pub fn set_level(&mut self, level: SecurityLevel, enabled: bool) {
751        match level {
752            SecurityLevel::L1 => self.l1 = Some(enabled),
753            SecurityLevel::L2 => self.l2 = Some(enabled),
754            SecurityLevel::L3 => self.l3 = Some(enabled),
755        }
756    }
757
758    /// Set one model/native scanner gate.
759    pub fn set_model(&mut self, model: impl Into<String>, enabled: bool) {
760        self.native.models.insert(model.into(), enabled);
761    }
762
763    /// Builder-style model/native scanner gate setter.
764    pub fn with_model(mut self, model: impl Into<String>, enabled: bool) -> Self {
765        self.set_model(model, enabled);
766        self
767    }
768
769    /// Set one stable rule-id gate.
770    pub fn set_rule(&mut self, rule_id: impl Into<String>, enabled: bool) {
771        self.native.rules.insert(rule_id.into(), enabled);
772    }
773
774    /// Builder-style stable rule-id gate setter.
775    pub fn with_rule(mut self, rule_id: impl Into<String>, enabled: bool) -> Self {
776        self.set_rule(rule_id, enabled);
777        self
778    }
779
780    /// Replace request-context and prior-result gates.
781    pub fn set_conditional(&mut self, gates: Vec<ConditionalPipelineGate>) -> Result<(), String> {
782        for gate in &gates {
783            gate.validate()?;
784        }
785        self.conditional = gates;
786        Ok(())
787    }
788
789    /// Return whether the level is allowed by this matrix before max-level
790    /// enforcement.
791    pub fn allows_level(&self, level: SecurityLevel) -> bool {
792        match level {
793            SecurityLevel::L1 => self.l1.unwrap_or(true),
794            SecurityLevel::L2 => self.l2.unwrap_or(true),
795            SecurityLevel::L3 => self.l3.unwrap_or(true),
796        }
797    }
798
799    /// Replace the L3 worker scheduling policy.
800    pub fn set_l3_policy(&mut self, policy: L3SchedulerPolicy) {
801        self.l3_policy = policy;
802    }
803}
804
805/// The serialized [`ScanGateMatrix`]; missing keys keep the defaults.
806#[derive(Default, Deserialize)]
807#[serde(default, deny_unknown_fields)]
808struct GateConfig {
809    #[serde(flatten)]
810    native: crate::NativeGates,
811    l1: Option<bool>,
812    l2: Option<bool>,
813    l3: Option<bool>,
814    conditional: Vec<ConditionalPipelineGate>,
815    l3_policy: L3PolicyConfig,
816}
817
818/// The serialized [`L3SchedulerPolicy`]: each key overrides its default;
819/// `ttl_ms` and `estimated_cost_ms` entries override the default per key.
820#[derive(Default, Deserialize)]
821#[serde(default, deny_unknown_fields)]
822struct L3PolicyConfig {
823    enabled: Option<bool>,
824    priority: Option<Vec<String>>,
825    ttl_ms: HashMap<String, u64>,
826    estimated_cost_ms: HashMap<String, u64>,
827    fairness_quantum_ms: Option<u64>,
828    max_wait_ms: Option<u64>,
829    degraded_factor: Option<f64>,
830    early_exit: Option<L3EarlyExitMode>,
831    progress: Option<L3ProgressMode>,
832    clustering: Option<L3ClusteringStrategy>,
833    representatives_per_cluster: Option<usize>,
834    verify_representatives_per_cluster: Option<usize>,
835    min_cluster_similarity: Option<f64>,
836    max_cluster_size: Option<usize>,
837    pipelines: HashMap<String, L3PipelinePolicy>,
838}
839
840impl TryFrom<GateConfig> for ScanGateMatrix {
841    type Error = String;
842
843    fn try_from(config: GateConfig) -> Result<Self, String> {
844        let raw = config.l3_policy;
845        let mut policy = L3SchedulerPolicy::default();
846        macro_rules! set {
847            ($($field:ident),*) => {$(
848                if let Some(value) = raw.$field {
849                    policy.$field = value;
850                }
851            )*};
852        }
853        set!(
854            enabled,
855            priority,
856            fairness_quantum_ms,
857            max_wait_ms,
858            degraded_factor,
859            early_exit,
860            progress,
861            clustering,
862            representatives_per_cluster,
863            verify_representatives_per_cluster,
864            min_cluster_similarity,
865            max_cluster_size
866        );
867        policy.ttl_ms.extend(raw.ttl_ms);
868        policy.estimated_cost_ms.extend(raw.estimated_cost_ms);
869        policy.pipelines = raw.pipelines;
870        policy.validate()?;
871        let mut gates = Self {
872            native: config.native,
873            l1: config.l1,
874            l2: config.l2,
875            l3: config.l3,
876            l3_policy: policy,
877            ..Self::default()
878        };
879        gates.set_conditional(config.conditional)?;
880        Ok(gates)
881    }
882}
883
884fn check_fraction(value: f64, field: &str) -> Result<(), String> {
885    if (0.0..=1.0).contains(&value) {
886        Ok(())
887    } else {
888        Err(format!("{field} must be between 0.0 and 1.0"))
889    }
890}
891
892fn check_count(value: usize, field: &str) -> Result<(), String> {
893    if value == 0 {
894        Err(format!("{field} must be >= 1"))
895    } else {
896        Ok(())
897    }
898}
899
900impl L3SchedulerPolicy {
901    /// Refuse out-of-range values: zero counts, costs and fairness quantum,
902    /// fractions outside `0..=1` and invalid pipeline overrides.
903    pub fn validate(&self) -> Result<(), String> {
904        check_count(
905            usize::try_from(self.fairness_quantum_ms).unwrap_or(usize::MAX),
906            "l3_policy.fairness_quantum_ms",
907        )?;
908        check_count(
909            self.representatives_per_cluster,
910            "l3_policy.representatives_per_cluster",
911        )?;
912        check_count(
913            self.verify_representatives_per_cluster,
914            "l3_policy.verify_representatives_per_cluster",
915        )?;
916        check_count(self.max_cluster_size, "l3_policy.max_cluster_size")?;
917        check_fraction(self.degraded_factor, "l3_policy.degraded_factor")?;
918        check_fraction(
919            self.min_cluster_similarity,
920            "l3_policy.min_cluster_similarity",
921        )?;
922        if let Some(name) = self.estimated_cost_ms.iter().find(|(_, &cost)| cost == 0) {
923            return Err(format!(
924                "l3_policy.estimated_cost_ms.{} must be >= 1",
925                name.0
926            ));
927        }
928        for (name, pipeline) in &self.pipelines {
929            if name.trim().is_empty() {
930                return Err("l3_policy.pipelines keys must not be empty".to_string());
931            }
932            pipeline
933                .validate()
934                .map_err(|error| format!("l3_policy.pipelines.{name}.{error}"))?;
935        }
936        Ok(())
937    }
938}
939
940impl L3PipelinePolicy {
941    /// Refuse zero counts, fractions outside `0..=1` and an empty positive class.
942    pub fn validate(&self) -> Result<(), String> {
943        for (field, value) in [
944            (
945                "representatives_per_cluster",
946                self.representatives_per_cluster,
947            ),
948            (
949                "verify_representatives_per_cluster",
950                self.verify_representatives_per_cluster,
951            ),
952            ("max_cluster_size", self.max_cluster_size),
953        ] {
954            value.map_or(Ok(()), |value| check_count(value, field))?;
955        }
956        if let Some(value) = self.min_cluster_similarity {
957            check_fraction(value, "min_cluster_similarity")?;
958        }
959        match &self.aggregation {
960            Some(L3AggregationStrategy::AnyPositiveOrHighest {
961                positive_class,
962                threshold,
963            }) => {
964                if positive_class.trim().is_empty() {
965                    return Err("aggregation.positive_class must not be empty".to_string());
966                }
967                check_fraction(*threshold, "aggregation.threshold")
968            }
969            Some(L3AggregationStrategy::HighestRiskAboveThresholdOrConfidence { threshold }) => {
970                check_fraction(*threshold, "aggregation.threshold")
971            }
972            Some(L3AggregationStrategy::MajorityVoteOrHighest) | None => Ok(()),
973        }
974    }
975}
976
977impl ConditionalPipelineGate {
978    pub fn validate(&self) -> Result<(), String> {
979        if self.level == SecurityLevel::L1 {
980            return Err("conditional gates may only target L2 or L3".to_string());
981        }
982        if self
983            .pipeline
984            .as_ref()
985            .is_some_and(|value| value.trim().is_empty())
986        {
987            return Err("conditional gate pipeline must not be empty".to_string());
988        }
989        if self.l3_policy.is_some() && (self.level != SecurityLevel::L3 || self.pipeline.is_none())
990        {
991            return Err(
992                "conditional l3_policy overrides require level l3 and a pipeline".to_string(),
993            );
994        }
995        if let Some(policy) = &self.l3_policy {
996            policy
997                .validate()
998                .map_err(|error| format!("conditional l3_policy.{error}"))?;
999        }
1000        self.when.validate()
1001    }
1002}
1003
1004impl L3PipelinePolicy {
1005    pub(crate) fn apply_override(&mut self, override_policy: &Self) {
1006        if override_policy.clustering.is_some() {
1007            self.clustering = override_policy.clustering;
1008        }
1009        if override_policy.representatives_per_cluster.is_some() {
1010            self.representatives_per_cluster = override_policy.representatives_per_cluster;
1011        }
1012        if override_policy.verify_representatives_per_cluster.is_some() {
1013            self.verify_representatives_per_cluster =
1014                override_policy.verify_representatives_per_cluster;
1015        }
1016        if override_policy.min_cluster_similarity.is_some() {
1017            self.min_cluster_similarity = override_policy.min_cluster_similarity;
1018        }
1019        if override_policy.max_cluster_size.is_some() {
1020            self.max_cluster_size = override_policy.max_cluster_size;
1021        }
1022        if override_policy.aggregation.is_some() {
1023            self.aggregation = override_policy.aggregation.clone();
1024        }
1025        if override_policy.early_exit.is_some() {
1026            self.early_exit = override_policy.early_exit;
1027        }
1028    }
1029}
1030
1031impl GateExpression {
1032    fn validate(&self) -> Result<(), String> {
1033        match self {
1034            Self::All(items) | Self::Any(items) => {
1035                if items.is_empty() {
1036                    return Err("conditional gate all/any must not be empty".to_string());
1037                }
1038                for item in items {
1039                    item.validate()?;
1040                }
1041                Ok(())
1042            }
1043            Self::Not(item) => item.validate(),
1044            Self::Metadata(condition) => condition.validate(),
1045            Self::Result(condition) => condition.validate(),
1046        }
1047    }
1048}
1049
1050impl MetadataCondition {
1051    fn validate(&self) -> Result<(), String> {
1052        if self.path.trim().is_empty() {
1053            return Err("metadata gate path must not be empty".to_string());
1054        }
1055        let predicates = usize::from(self.equals.is_some())
1056            + usize::from(self.in_values.is_some())
1057            + usize::from(self.exists.is_some());
1058        if predicates != 1 {
1059            return Err(
1060                "metadata gate must configure exactly one of equals, in, or exists".to_string(),
1061            );
1062        }
1063        if self.in_values.as_ref().is_some_and(Vec::is_empty) {
1064            return Err("metadata gate in list must not be empty".to_string());
1065        }
1066        Ok(())
1067    }
1068}
1069
1070impl ResultCondition {
1071    fn validate(&self) -> Result<(), String> {
1072        if self.pipeline.trim().is_empty() {
1073            return Err("result gate pipeline must not be empty".to_string());
1074        }
1075        if self
1076            .min_confidence
1077            .is_some_and(|value| !(0.0..=1.0).contains(&value))
1078        {
1079            return Err("result gate min_confidence must be between 0.0 and 1.0".to_string());
1080        }
1081        Ok(())
1082    }
1083}
1084
1085#[derive(Debug, Clone)]
1086/// Effective execution state consumed by scan methods and model pipelines.
1087pub struct ScanExecution {
1088    max_level: SecurityLevel,
1089    gates: ScanGateMatrix,
1090    backend: ExecutionBackend,
1091    onnx_runtime_options: OnnxRuntimeOptions,
1092    onnx_batch_mode: OnnxBatchMode,
1093    ntdb_operating_point: NtdbOperatingPoint,
1094    ntdb_decision_threshold_point: NtdbOperatingPoint,
1095    l3_strategy: L3Strategy,
1096    defer_l3: bool,
1097    chunk_overlap_tokens: usize,
1098    wolf_execution_options: crate::WolfExecutionOptions,
1099    wolf_selection: WolfSelection,
1100}
1101
1102/// The Wolf Defender model and ONNX export the dedicated injection L3 loads.
1103#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1104#[serde(default, deny_unknown_fields)]
1105pub struct WolfSelection {
1106    pub model: crate::WolfModel,
1107    pub precision: crate::WolfPrecision,
1108}
1109
1110impl ScanExecution {
1111    /// Create an execution with shared rule defaults up to `max_level`.
1112    pub fn new(max_level: SecurityLevel) -> Self {
1113        Self {
1114            max_level,
1115            gates: ScanGateMatrix::default(),
1116            backend: ExecutionBackend::default(),
1117            onnx_runtime_options: OnnxRuntimeOptions::default(),
1118            onnx_batch_mode: OnnxBatchMode::LazyBatches,
1119            ntdb_operating_point: NtdbOperatingPoint::default(),
1120            ntdb_decision_threshold_point: NtdbOperatingPoint::BestF1,
1121            l3_strategy: L3Strategy::default(),
1122            defer_l3: false,
1123            chunk_overlap_tokens: 0,
1124            wolf_execution_options: crate::WolfExecutionOptions::default(),
1125            wolf_selection: WolfSelection::default(),
1126        }
1127    }
1128
1129    /// Create an execution with explicit gates up to `max_level`.
1130    pub fn with_gates(max_level: SecurityLevel, gates: ScanGateMatrix) -> Self {
1131        Self {
1132            max_level,
1133            gates,
1134            backend: ExecutionBackend::default(),
1135            onnx_runtime_options: OnnxRuntimeOptions::default(),
1136            onnx_batch_mode: OnnxBatchMode::LazyBatches,
1137            ntdb_operating_point: NtdbOperatingPoint::default(),
1138            ntdb_decision_threshold_point: NtdbOperatingPoint::BestF1,
1139            l3_strategy: L3Strategy::default(),
1140            defer_l3: false,
1141            chunk_overlap_tokens: 0,
1142            wolf_execution_options: crate::WolfExecutionOptions::default(),
1143            wolf_selection: WolfSelection::default(),
1144        }
1145    }
1146
1147    /// Choose the Wolf model and export; an unknown `auto` override fails here, not on first use.
1148    pub fn set_wolf_selection(&mut self, selection: WolfSelection) -> Result<(), String> {
1149        selection.precision.resolve().map_err(|e| e.to_string())?;
1150        self.wolf_selection = selection;
1151        Ok(())
1152    }
1153
1154    pub fn wolf_selection(&self) -> WolfSelection {
1155        self.wolf_selection
1156    }
1157
1158    /// Configure dedicated Wolf execution using the shared Core validation.
1159    pub fn set_wolf_execution_options(
1160        &mut self,
1161        options: crate::WolfExecutionOptions,
1162    ) -> Result<(), String> {
1163        options.validate().map_err(|e| e.to_string())?;
1164        self.wolf_execution_options = options;
1165        Ok(())
1166    }
1167
1168    pub fn wolf_execution_options(&self) -> crate::WolfExecutionOptions {
1169        self.wolf_execution_options
1170    }
1171
1172    /// Replace the gate matrix.
1173    pub fn set_gates(&mut self, gates: ScanGateMatrix) {
1174        self.gates = gates;
1175    }
1176
1177    /// Replace the ONNX batch execution mode.
1178    pub fn set_onnx_batch_mode(&mut self, mode: OnnxBatchMode) {
1179        self.onnx_batch_mode = mode;
1180    }
1181
1182    /// Replace the execution backend and apply its default L3 batch mode.
1183    pub fn set_backend(&mut self, backend: ExecutionBackend) {
1184        self.backend = backend;
1185        self.onnx_batch_mode = match backend {
1186            ExecutionBackend::Auto | ExecutionBackend::Cpu => OnnxBatchMode::LazyBatches,
1187            ExecutionBackend::Gpu
1188            | ExecutionBackend::CoreMl
1189            | ExecutionBackend::Cuda
1190            | ExecutionBackend::DirectMl
1191            | ExecutionBackend::TensorRt => OnnxBatchMode::TensorBatch,
1192        };
1193    }
1194
1195    /// Replace ONNX Runtime session options used by L3 ONNX classifiers.
1196    pub fn set_onnx_runtime_options(&mut self, options: OnnxRuntimeOptions) {
1197        self.onnx_runtime_options = options.normalized();
1198    }
1199
1200    /// Select the calibrated NTDB operating point used by subsequent scans.
1201    pub fn set_ntdb_operating_point(&mut self, point: NtdbOperatingPoint) {
1202        self.ntdb_operating_point = point;
1203    }
1204
1205    /// Select the calibrated NTDB final-decision threshold set.
1206    pub fn set_ntdb_decision_threshold_point(&mut self, point: NtdbOperatingPoint) {
1207        self.ntdb_decision_threshold_point = point;
1208    }
1209
1210    /// Select the physical L3 classifier topology.
1211    pub fn set_l3_strategy(&mut self, strategy: L3Strategy) {
1212        self.l3_strategy = strategy;
1213    }
1214
1215    /// Set whether L3 should be marked pending instead of executed immediately.
1216    pub fn set_defer_l3(&mut self, defer_l3: bool) {
1217        self.defer_l3 = defer_l3;
1218    }
1219
1220    /// Set the request-local overlap between adjacent classifier chunks.
1221    pub fn set_chunk_overlap_tokens(&mut self, overlap: usize) -> Result<(), String> {
1222        self.set_validated_chunk_overlap_tokens(crate::ChunkOverlapTokens::try_from(overlap)?);
1223        Ok(())
1224    }
1225
1226    pub(crate) fn set_validated_chunk_overlap_tokens(
1227        &mut self,
1228        overlap: crate::ChunkOverlapTokens,
1229    ) {
1230        self.chunk_overlap_tokens = overlap.get();
1231    }
1232
1233    /// Return a copy with a different max-level cap.
1234    pub fn with_max_level(mut self, max_level: SecurityLevel) -> Self {
1235        self.max_level = max_level;
1236        self
1237    }
1238
1239    /// Return whether a level is enabled for this execution after max-level
1240    /// enforcement.
1241    pub fn allows_level(&self, level: SecurityLevel) -> bool {
1242        level <= self.max_level && self.gates.allows_level(level)
1243    }
1244
1245    /// Return the matrix backing this execution.
1246    pub fn gates(&self) -> &ScanGateMatrix {
1247        &self.gates
1248    }
1249
1250    /// Return the ONNX batch mode backing this execution.
1251    pub fn onnx_batch_mode(&self) -> OnnxBatchMode {
1252        self.onnx_batch_mode
1253    }
1254
1255    /// Return the configured execution backend.
1256    pub fn backend(&self) -> ExecutionBackend {
1257        self.backend
1258    }
1259
1260    /// Return the ONNX Runtime session options backing this execution.
1261    pub fn onnx_runtime_options(&self) -> OnnxRuntimeOptions {
1262        self.onnx_runtime_options
1263    }
1264
1265    /// Return the selected NTDB operating point.
1266    pub fn ntdb_operating_point(&self) -> NtdbOperatingPoint {
1267        self.ntdb_operating_point
1268    }
1269
1270    /// Return the selected NTDB final-decision threshold set.
1271    pub fn ntdb_decision_threshold_point(&self) -> NtdbOperatingPoint {
1272        self.ntdb_decision_threshold_point
1273    }
1274
1275    /// Return the selected physical L3 classifier topology.
1276    pub fn l3_strategy(&self) -> L3Strategy {
1277        self.l3_strategy
1278    }
1279
1280    /// Return whether L3 should be centrally scheduled.
1281    pub fn defer_l3(&self) -> bool {
1282        self.defer_l3
1283    }
1284
1285    /// Return the overlap between adjacent classifier chunks.
1286    pub fn chunk_overlap_tokens(&self) -> usize {
1287        self.chunk_overlap_tokens
1288    }
1289
1290    /// Return the L3 worker policy.
1291    pub fn l3_policy(&self) -> &L3SchedulerPolicy {
1292        &self.gates.l3_policy
1293    }
1294
1295    /// Return the max-level cap backing this execution.
1296    pub fn max_level(&self) -> SecurityLevel {
1297        self.max_level
1298    }
1299}
1300
1301impl Default for ScanExecution {
1302    fn default() -> Self {
1303        Self::new(SecurityLevel::L3)
1304    }
1305}
1306
1307pub use patronus_ark_core::{
1308    DecisionCandidate, DecisionEnvelope, DecisionProvenance, DecisionRecommendation,
1309    DecisionResult, DecisionTerminality, EvaluationResult, LabelScore, LayerResult,
1310    SecurityCategory,
1311};
1312
1313impl From<patronus_ark_core::NativeResult> for SecurityScanResult {
1314    fn from(value: patronus_ark_core::NativeResult) -> Self {
1315        Self {
1316            category: value.category,
1317            class_name: value.class_name,
1318            confidence: value.confidence,
1319            level: value.level,
1320            model: value.model,
1321            duration_ms: value.duration_ms,
1322            layers: value.layers,
1323            evidence_spans: value.evidence_spans,
1324            label_scores: value.label_scores,
1325            decision: value.decision,
1326            internal_l2_chunk_outputs: Vec::new(),
1327        }
1328    }
1329}
1330
1331impl From<SecurityScanResult> for patronus_ark_core::NativeResult {
1332    fn from(value: SecurityScanResult) -> Self {
1333        Self {
1334            category: value.category,
1335            class_name: value.class_name,
1336            confidence: value.confidence,
1337            level: value.level,
1338            model: value.model,
1339            duration_ms: value.duration_ms,
1340            layers: value.layers,
1341            evidence_spans: value.evidence_spans,
1342            label_scores: value.label_scores,
1343            decision: value.decision,
1344        }
1345    }
1346}
1347
1348pub use patronus_ark_core::{ExecutionBackend, OnnxRuntimeOptions};
1349
1350#[cfg(test)]
1351mod gate_schema_tests {
1352    use super::*;
1353
1354    fn gates(value: serde_json::Value) -> Result<ScanGateMatrix, String> {
1355        serde_json::from_value(value).map_err(|error| error.to_string())
1356    }
1357
1358    #[test]
1359    fn one_gate_schema_reads_every_key() {
1360        let gates = gates(serde_json::json!({
1361            "rules": {"pii_email": false, "cat.core.remote_to_exec": false},
1362            "models": {"native:pii": false},
1363            "pii_mode": "recall",
1364            "dlp_mode": "balanced",
1365            "explain": true,
1366            "l1": true,
1367            "l2": false,
1368            "l3": false,
1369            "conditional": [{
1370                "level": "l3",
1371                "pipeline": "injection",
1372                "when": {"metadata": {"path": "tenant", "equals": "a"}},
1373                "l3_policy": {"clustering": "representative"}
1374            }],
1375            "l3_policy": {
1376                "enabled": false,
1377                "priority": ["tool_class"],
1378                "ttl_ms": {"tool_class": 1234},
1379                "estimated_cost_ms": {"tool_class": 30},
1380                "fairness_quantum_ms": 10,
1381                "max_wait_ms": 100,
1382                "degraded_factor": 0.5,
1383                "early_exit": "disabled",
1384                "progress": "provisional",
1385                "clustering": "verify_representative",
1386                "representatives_per_cluster": 2,
1387                "verify_representatives_per_cluster": 2,
1388                "min_cluster_similarity": 0.8,
1389                "max_cluster_size": 4,
1390                "pipelines": {"injection": {
1391                    "clustering": "representative",
1392                    "aggregation": {"type": "any_positive_or_highest", "positive_class": "attack", "threshold": 0.93},
1393                    "early_exit": "request_wide_positive"
1394                }}
1395            }
1396        }))
1397        .unwrap();
1398        assert!(!gates.native.allows_rule("cat.core.remote_to_exec"));
1399        assert!(!gates.native.allows_model("native:pii"));
1400        assert_eq!(gates.native.pii_mode, crate::ScoreMode::Recall);
1401        assert!(gates.native.explain);
1402        assert_eq!(
1403            (gates.l1, gates.l2, gates.l3),
1404            (Some(true), Some(false), Some(false))
1405        );
1406        assert_eq!(gates.conditional.len(), 1);
1407        let policy = &gates.l3_policy;
1408        assert!(!policy.enabled);
1409        assert_eq!(policy.ttl_ms["tool_class"], 1234);
1410        // Map entries override the defaults per key.
1411        assert_eq!(policy.ttl_ms["injection"], 15_000);
1412        assert_eq!(
1413            policy.clustering,
1414            L3ClusteringStrategy::VerifyRepresentative
1415        );
1416        assert_eq!(policy.max_cluster_size, 4);
1417        assert_eq!(
1418            policy.pipelines["injection"].clustering,
1419            Some(L3ClusteringStrategy::Representative)
1420        );
1421        let default = self::gates(serde_json::json!({})).unwrap();
1422        assert_eq!(
1423            default.l3_policy.priority,
1424            L3SchedulerPolicy::default().priority
1425        );
1426        assert!(default.native.allows_rule("pii_email"));
1427    }
1428
1429    #[test]
1430    fn gate_schema_refuses_old_keys_and_bad_values() {
1431        for invalid in [
1432            serde_json::json!({"levels": {"l1": true}}),
1433            serde_json::json!({"model_areas": {"native:pii": false}}),
1434            serde_json::json!({"policy": {"enabled": true}}),
1435            serde_json::json!({"l3": {"enabled": true}}),
1436            serde_json::json!({"l3_policy": {"execution": "rank_only"}}),
1437            serde_json::json!({"l3_policy": {"min_similarity": 0.9}}),
1438            serde_json::json!({"l3_policy": {"pipelines": {"injection": {"execution": "representative"}}}}),
1439            serde_json::json!({"rules": {"pii_email": "no"}}),
1440            serde_json::json!({"l1": "yes"}),
1441            serde_json::json!({"pii_mode": "fast"}),
1442            serde_json::json!({"l3_policy": {"priority": "injection"}}),
1443            serde_json::json!({"l3_policy": {"ttl_ms": {"injection": "soon"}}}),
1444            serde_json::json!({"l3_policy": {"estimated_cost_ms": {"dynamic-pii": 0}}}),
1445            serde_json::json!({"l3_policy": {"fairness_quantum_ms": 0}}),
1446            serde_json::json!({"l3_policy": {"max_wait_ms": -1}}),
1447            serde_json::json!({"l3_policy": {"degraded_factor": 2.0}}),
1448            serde_json::json!({"l3_policy": {"min_cluster_similarity": 1.5}}),
1449            serde_json::json!({"l3_policy": {"early_exit": "sometimes"}}),
1450            serde_json::json!({"l3_policy": {"progress": "verbose"}}),
1451            serde_json::json!({"l3_policy": {"clustering": "aggressive"}}),
1452            serde_json::json!({"l3_policy": {"representatives_per_cluster": 0}}),
1453            serde_json::json!({"l3_policy": {"max_cluster_size": 0}}),
1454            serde_json::json!({"l3_policy": {"pipelines": {"": {}}}}),
1455            serde_json::json!({"l3_policy": {"pipelines": {"injection": {"max_cluster_size": 0}}}}),
1456            serde_json::json!({"l3_policy": {"pipelines": {"injection": {"min_cluster_similarity": 1.5}}}}),
1457            serde_json::json!({"l3_policy": {"pipelines": {"injection": {"aggregation": {"type": "any_positive_or_highest", "positive_class": " ", "threshold": 0.5}}}}}),
1458            serde_json::json!({"conditional": [{"level": "l1", "when": {"metadata": {"path": "a", "exists": true}}}]}),
1459            serde_json::json!({"conditional": [{"level": "l3", "pipeline": "injection", "when": {"metadata": {"path": "a", "exists": true}}, "l3_policy": {"max_cluster_size": 0}}]}),
1460        ] {
1461            assert!(gates(invalid.clone()).is_err(), "{invalid} must be refused");
1462        }
1463    }
1464}
1465
1466#[cfg(test)]
1467mod tests {
1468    use super::*;
1469
1470    #[test]
1471    fn l3_pipeline_policy_overrides_request_defaults_by_category() {
1472        let mut policy = L3SchedulerPolicy {
1473            clustering: L3ClusteringStrategy::RankOnly,
1474            ..L3SchedulerPolicy::default()
1475        };
1476        policy.pipelines.insert(
1477            "injection".to_string(),
1478            L3PipelinePolicy {
1479                clustering: Some(L3ClusteringStrategy::VerifyRepresentative),
1480                representatives_per_cluster: Some(2),
1481                verify_representatives_per_cluster: Some(1),
1482                min_cluster_similarity: Some(0.96),
1483                max_cluster_size: Some(4),
1484                aggregation: Some(L3AggregationStrategy::AnyPositiveOrHighest {
1485                    positive_class: "attack".to_string(),
1486                    threshold: 0.9,
1487                }),
1488                early_exit: Some(L3PipelineEarlyExit::RequestWidePositive),
1489            },
1490        );
1491
1492        let resolved = policy.pipeline_policy("injection", "wolf-defender-small");
1493
1494        assert_eq!(
1495            resolved.clustering,
1496            L3ClusteringStrategy::VerifyRepresentative
1497        );
1498        assert_eq!(resolved.representatives_per_cluster, 2);
1499        assert_eq!(resolved.min_cluster_similarity, 0.96);
1500        assert_eq!(resolved.max_cluster_size, 4);
1501        assert_eq!(
1502            resolved.early_exit,
1503            L3PipelineEarlyExit::RequestWidePositive
1504        );
1505    }
1506
1507    #[test]
1508    fn l3_pipeline_policy_uses_model_override_when_category_is_absent() {
1509        let mut policy = L3SchedulerPolicy::default();
1510        policy.pipelines.insert(
1511            "unified-v3-tool-class".to_string(),
1512            L3PipelinePolicy {
1513                clustering: Some(L3ClusteringStrategy::Representative),
1514                ..L3PipelinePolicy::default()
1515            },
1516        );
1517
1518        assert_eq!(
1519            policy
1520                .pipeline_policy("tool_class", "unified-v3-tool-class")
1521                .clustering,
1522            L3ClusteringStrategy::Representative
1523        );
1524    }
1525
1526    #[test]
1527    fn l3_default_early_exit_scope_matches_pipeline_semantics() {
1528        let policy = L3SchedulerPolicy::default();
1529
1530        assert_eq!(
1531            policy
1532                .pipeline_policy("threat", "unified-v3-threat")
1533                .early_exit,
1534            L3PipelineEarlyExit::RequestWidePositive
1535        );
1536        assert_eq!(
1537            policy
1538                .pipeline_policy("tool_class", "unified-v3-tool-class")
1539                .early_exit,
1540            L3PipelineEarlyExit::HeadStable
1541        );
1542    }
1543
1544    #[test]
1545    fn security_level_serde_accepts_from_str_names_and_writes_canonical_names() {
1546        for (name, level) in [
1547            ("L1", SecurityLevel::L1),
1548            ("l2", SecurityLevel::L2),
1549            ("3", SecurityLevel::L3),
1550        ] {
1551            let parsed: SecurityLevel = serde_json::from_value(serde_json::json!(name)).unwrap();
1552            assert_eq!(parsed, level);
1553            assert_eq!(serde_json::to_value(level).unwrap(), level.as_str());
1554        }
1555        assert!(serde_json::from_value::<SecurityLevel>(serde_json::json!("L4")).is_err());
1556    }
1557}