zeph-config 0.21.2

Pure-data configuration types for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::providers::ProviderName;
use serde::{Deserialize, Serialize};

use crate::defaults::default_true;

// ---------------------------------------------------------------------------
// ContentIsolationConfig
// ---------------------------------------------------------------------------

fn default_max_content_size() -> usize {
    65_536
}

/// Configuration for the embedding anomaly guard, nested under
/// `[security.content_isolation.embedding_guard]`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct EmbeddingGuardConfig {
    /// Enable embedding-based anomaly detection (default: false — opt-in).
    #[serde(default)]
    pub enabled: bool,
    /// Cosine distance threshold above which outputs are flagged as anomalous.
    #[serde(
        default = "default_embedding_threshold",
        deserialize_with = "validate_embedding_threshold"
    )]
    pub threshold: f64,
    /// Minimum clean samples before centroid-based detection activates.
    /// Before this count, regex fallback is used instead.
    #[serde(
        default = "default_embedding_min_samples",
        deserialize_with = "validate_min_samples"
    )]
    pub min_samples: usize,
    /// EMA alpha floor for centroid updates after stabilization (n >= `min_samples`).
    ///
    /// Once the centroid has accumulated `min_samples` clean outputs, each new sample
    /// can shift it by at most this fraction. Lower values make the centroid more
    /// resistant to slow drift attacks but slower to adapt to legitimate distribution
    /// changes. Default: 0.01 (1% per sample).
    #[serde(default = "default_ema_floor")]
    pub ema_floor: f32,
}

fn validate_embedding_threshold<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <f64 as serde::Deserialize>::deserialize(deserializer)?;
    if value.is_nan() || value.is_infinite() {
        return Err(serde::de::Error::custom(
            "embedding_guard.threshold must be a finite number",
        ));
    }
    if !(value > 0.0 && value <= 1.0) {
        return Err(serde::de::Error::custom(
            "embedding_guard.threshold must be in (0.0, 1.0]",
        ));
    }
    Ok(value)
}

fn validate_min_samples<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <usize as serde::Deserialize>::deserialize(deserializer)?;
    if value == 0 {
        return Err(serde::de::Error::custom(
            "embedding_guard.min_samples must be >= 1",
        ));
    }
    Ok(value)
}

fn default_embedding_threshold() -> f64 {
    0.35
}

fn default_embedding_min_samples() -> usize {
    10
}

fn default_ema_floor() -> f32 {
    0.01
}

impl Default for EmbeddingGuardConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            threshold: default_embedding_threshold(),
            min_samples: default_embedding_min_samples(),
            ema_floor: default_ema_floor(),
        }
    }
}

/// Configuration for the content isolation pipeline, nested under
/// `[security.content_isolation]` in the agent config file.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[allow(clippy::struct_excessive_bools)] // config struct — boolean flags are idiomatic for TOML-deserialized configuration
pub struct ContentIsolationConfig {
    /// When `false`, the sanitizer is a no-op: content passes through unchanged.
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Maximum byte length of untrusted content before truncation.
    #[serde(default = "default_max_content_size")]
    pub max_content_size: usize,

    /// When `true`, injection patterns detected in content are recorded as
    /// flags and a warning is prepended to the spotlighting wrapper.
    #[serde(default = "default_true")]
    pub flag_injection_patterns: bool,

    /// When `true`, untrusted content is wrapped in spotlighting XML delimiters
    /// that instruct the LLM to treat the enclosed text as data, not instructions.
    #[serde(default = "default_true")]
    pub spotlight_untrusted: bool,

    /// Quarantine summarizer configuration.
    #[serde(default)]
    pub quarantine: QuarantineConfig,

    /// Embedding anomaly guard configuration.
    #[serde(default)]
    pub embedding_guard: EmbeddingGuardConfig,

    /// When `true`, MCP tool results flowing through ACP-serving sessions receive
    /// unconditional quarantine summarization and cross-boundary audit log entries.
    /// This prevents confused-deputy attacks where untrusted MCP output influences
    /// responses served to ACP clients (e.g. IDE integrations).
    #[serde(default = "default_true")]
    pub mcp_to_acp_boundary: bool,

    /// NLI entailment check stage configuration.
    #[serde(default)]
    pub nli: NliConfig,

    /// PAAC secret placeholder masking configuration.
    #[serde(default)]
    pub secret_masking: SecretMaskingConfig,
}

impl Default for ContentIsolationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_content_size: default_max_content_size(),
            flag_injection_patterns: true,
            spotlight_untrusted: true,
            quarantine: QuarantineConfig::default(),
            embedding_guard: EmbeddingGuardConfig::default(),
            mcp_to_acp_boundary: true,
            nli: NliConfig::default(),
            secret_masking: SecretMaskingConfig::default(),
        }
    }
}

/// Configuration for the SONAR NLI entailment check stage, nested under
/// `[security.content_isolation.nli]` in the agent config file.
///
/// When `enabled = false` (the default), the NLI stage is skipped entirely.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct NliConfig {
    /// Enable NLI entailment-based injection detection (default: false — opt-in).
    #[serde(default)]
    pub enabled: bool,

    /// Provider name from `[[llm.providers]]` to use for NLI inference.
    ///
    /// An empty [`ProviderName`] falls back to the default provider. Prefer a fast, cheap model.
    #[serde(default)]
    pub provider: ProviderName,

    /// Entailment score threshold above which content is flagged (default: 0.75).
    #[serde(default = "default_nli_threshold")]
    pub threshold: f32,

    /// Maximum milliseconds to wait for the NLI provider response (default: 5000).
    #[serde(default = "default_nli_timeout_ms")]
    pub timeout_ms: u64,

    /// Maximum characters of content sent to the NLI provider (default: 2048).
    #[serde(default = "default_nli_max_content_len")]
    pub max_content_len: usize,
}

fn default_nli_threshold() -> f32 {
    0.75
}

fn default_nli_timeout_ms() -> u64 {
    5000
}

fn default_nli_max_content_len() -> usize {
    2048
}

impl Default for NliConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: ProviderName::default(),
            threshold: default_nli_threshold(),
            timeout_ms: default_nli_timeout_ms(),
            max_content_len: default_nli_max_content_len(),
        }
    }
}

/// Configuration for PAAC secret placeholder masking, nested under
/// `[security.secret_masking]` in the agent config file.
///
/// When `enabled = false` (the default), vault secrets are not masked.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct SecretMaskingConfig {
    /// Enable secret placeholder masking (default: false — opt-in).
    #[serde(default)]
    pub enabled: bool,

    /// Minimum secret byte length to be eligible for masking (default: 8).
    ///
    /// Secrets shorter than this value are not substituted to avoid false matches
    /// on common short strings.
    #[serde(default = "default_min_secret_len")]
    pub min_secret_len: usize,
}

fn default_min_secret_len() -> usize {
    8
}

impl Default for SecretMaskingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            min_secret_len: default_min_secret_len(),
        }
    }
}

/// Configuration for the quarantine summarizer, nested under
/// `[security.content_isolation.quarantine]` in the agent config file.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct QuarantineConfig {
    /// When `false`, quarantine summarization is disabled entirely.
    #[serde(default)]
    pub enabled: bool,

    /// Source kinds to route through the quarantine LLM.
    #[serde(default = "default_quarantine_sources")]
    pub sources: Vec<String>,

    /// Provider name passed to `create_named_provider`.
    #[serde(default = "default_quarantine_model")]
    pub model: String,
}

fn default_quarantine_sources() -> Vec<String> {
    vec!["web_scrape".to_owned(), "a2a_message".to_owned()]
}

fn default_quarantine_model() -> String {
    "claude".to_owned()
}

impl Default for QuarantineConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            sources: default_quarantine_sources(),
            model: default_quarantine_model(),
        }
    }
}

// ---------------------------------------------------------------------------
// ExfiltrationGuardConfig
// ---------------------------------------------------------------------------

/// Configuration for exfiltration guards, nested under
/// `[security.exfiltration_guard]` in the agent config file.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ExfiltrationGuardConfig {
    /// Strip external markdown images from LLM output to prevent pixel-tracking exfiltration.
    #[serde(default = "default_true")]
    pub block_markdown_images: bool,

    /// Cross-reference tool call arguments against URLs seen in flagged untrusted content.
    #[serde(default = "default_true")]
    pub validate_tool_urls: bool,

    /// Skip Qdrant embedding for messages that contained injection-flagged content.
    #[serde(default = "default_true")]
    pub guard_memory_writes: bool,
}

impl Default for ExfiltrationGuardConfig {
    fn default() -> Self {
        Self {
            block_markdown_images: true,
            validate_tool_urls: true,
            guard_memory_writes: true,
        }
    }
}

// ---------------------------------------------------------------------------
// MemoryWriteValidationConfig
// ---------------------------------------------------------------------------

fn default_max_content_bytes() -> usize {
    4096
}

fn default_max_entity_name_bytes() -> usize {
    256
}

fn default_min_entity_name_bytes() -> usize {
    3
}

fn default_max_fact_bytes() -> usize {
    1024
}

fn default_max_entities() -> usize {
    50
}

fn default_max_edges() -> usize {
    100
}

/// Configuration for memory write validation, nested under `[security.memory_validation]`.
///
/// Enabled by default with conservative limits.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct MemoryWriteValidationConfig {
    /// Master switch. When `false`, validation is a no-op.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Maximum byte length of content passed to `memory_save`.
    #[serde(default = "default_max_content_bytes")]
    pub max_content_bytes: usize,
    /// Minimum byte length of an entity name in graph extraction.
    #[serde(default = "default_min_entity_name_bytes")]
    pub min_entity_name_bytes: usize,
    /// Maximum byte length of a single entity name in graph extraction.
    #[serde(default = "default_max_entity_name_bytes")]
    pub max_entity_name_bytes: usize,
    /// Maximum byte length of an edge fact string in graph extraction.
    #[serde(default = "default_max_fact_bytes")]
    pub max_fact_bytes: usize,
    /// Maximum number of entities allowed per graph extraction result.
    #[serde(default = "default_max_entities")]
    pub max_entities_per_extraction: usize,
    /// Maximum number of edges allowed per graph extraction result.
    #[serde(default = "default_max_edges")]
    pub max_edges_per_extraction: usize,
    /// Forbidden substring patterns.
    #[serde(default)]
    pub forbidden_content_patterns: Vec<String>,
}

impl Default for MemoryWriteValidationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_content_bytes: default_max_content_bytes(),
            min_entity_name_bytes: default_min_entity_name_bytes(),
            max_entity_name_bytes: default_max_entity_name_bytes(),
            max_fact_bytes: default_max_fact_bytes(),
            max_entities_per_extraction: default_max_entities(),
            max_edges_per_extraction: default_max_edges(),
            forbidden_content_patterns: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// PiiFilterConfig
// ---------------------------------------------------------------------------

/// A single user-defined PII pattern.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct CustomPiiPattern {
    /// Human-readable name used in the replacement label.
    pub name: String,
    /// Regular expression pattern.
    pub pattern: String,
    /// Replacement text. Defaults to `[PII:custom]`.
    #[serde(default = "default_custom_replacement")]
    pub replacement: String,
}

fn default_custom_replacement() -> String {
    "[PII:custom]".to_owned()
}

/// Configuration for the PII filter, nested under `[security.pii_filter]` in the config file.
///
/// Disabled by default — opt-in to avoid unexpected data loss.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[allow(clippy::struct_excessive_bools)] // config struct — boolean flags are idiomatic for TOML-deserialized configuration
pub struct PiiFilterConfig {
    /// Master switch. When `false`, the filter is a no-op.
    #[serde(default)]
    pub enabled: bool,
    /// Scrub email addresses.
    #[serde(default = "default_true")]
    pub filter_email: bool,
    /// Scrub US phone numbers.
    #[serde(default = "default_true")]
    pub filter_phone: bool,
    /// Scrub US Social Security Numbers.
    #[serde(default = "default_true")]
    pub filter_ssn: bool,
    /// Scrub credit card numbers (16-digit patterns).
    #[serde(default = "default_true")]
    pub filter_credit_card: bool,
    /// Custom regex patterns to add on top of the built-ins.
    #[serde(default)]
    pub custom_patterns: Vec<CustomPiiPattern>,
}

impl Default for PiiFilterConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            filter_email: true,
            filter_phone: true,
            filter_ssn: true,
            filter_credit_card: true,
            custom_patterns: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// GuardrailConfig
// ---------------------------------------------------------------------------

/// What happens when the guardrail flags input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum GuardrailAction {
    /// Block the input and return an error message to the user.
    #[default]
    Block,
    /// Allow the input but emit a warning message.
    Warn,
}

/// Behavior on timeout or LLM error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum GuardrailFailStrategy {
    /// Block input on timeout/error (safe default for security-sensitive deployments).
    #[default]
    Closed,
    /// Allow input on timeout/error (for availability-sensitive deployments).
    Open,
}

/// Configuration for the LLM-based guardrail, nested under `[security.guardrail]`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct GuardrailConfig {
    /// Enable the guardrail (default: false).
    #[serde(default)]
    pub enabled: bool,
    /// Provider to use for guardrail classification (e.g. `"ollama"`, `"claude"`).
    #[serde(default)]
    pub provider: Option<String>,
    /// Model to use (e.g. `"llama-guard-3:1b"`).
    #[serde(default)]
    pub model: Option<String>,
    /// Timeout for each guardrail LLM call in milliseconds (default: 500).
    #[serde(default = "default_guardrail_timeout_ms")]
    pub timeout_ms: u64,
    /// Action to take when a message is flagged (default: block).
    #[serde(default)]
    pub action: GuardrailAction,
    /// What to do on timeout or LLM error (default: closed — block).
    #[serde(default = "default_fail_strategy")]
    pub fail_strategy: GuardrailFailStrategy,
    /// When `true`, also scan tool outputs before they enter message history (default: false).
    #[serde(default)]
    pub scan_tool_output: bool,
    /// Maximum number of characters to send to the guard model (default: 4096).
    #[serde(default = "default_max_input_chars")]
    pub max_input_chars: usize,
}
fn default_guardrail_timeout_ms() -> u64 {
    500
}
fn default_max_input_chars() -> usize {
    4096
}
fn default_fail_strategy() -> GuardrailFailStrategy {
    GuardrailFailStrategy::Closed
}
impl Default for GuardrailConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: None,
            model: None,
            timeout_ms: default_guardrail_timeout_ms(),
            action: GuardrailAction::default(),
            fail_strategy: default_fail_strategy(),
            scan_tool_output: false,
            max_input_chars: default_max_input_chars(),
        }
    }
}

// ---------------------------------------------------------------------------
// ResponseVerificationConfig
// ---------------------------------------------------------------------------

/// Configuration for post-LLM response verification, nested under
/// `[security.response_verification]` in the agent config file.
///
/// Scans LLM responses for injected instruction patterns before tool dispatch.
/// This is defense-in-depth layer 3 (after input sanitization and pre-execution verification).
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ResponseVerificationConfig {
    /// Enable post-LLM response verification (default: true).
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Block tool dispatch when injection patterns are detected (default: false).
    ///
    /// When `false`, flagged responses are logged and shown in the TUI SEC panel
    /// but still delivered. When `true`, the response is suppressed and the user
    /// is notified.
    #[serde(default)]
    pub block_on_detection: bool,
    /// Optional LLM provider for async deep verification of flagged responses.
    ///
    /// When set: suspicious responses are delivered immediately with a `[FLAGGED]`
    /// annotation, and background LLM verification runs asynchronously. The verifier
    /// receives a sanitized summary (via `QuarantinedSummarizer`) to prevent recursive
    /// injection. Empty string = disabled (regex-only verification).
    #[serde(default)]
    pub verifier_provider: ProviderName,
}

impl Default for ResponseVerificationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            block_on_detection: false,
            verifier_provider: ProviderName::default(),
        }
    }
}

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

    #[test]
    fn content_isolation_default_mcp_to_acp_boundary_true() {
        let cfg = ContentIsolationConfig::default();
        assert!(cfg.mcp_to_acp_boundary);
    }

    #[test]
    fn content_isolation_deserialize_mcp_to_acp_boundary_false() {
        let toml = r"
            mcp_to_acp_boundary = false
        ";
        let cfg: ContentIsolationConfig = toml::from_str(toml).unwrap();
        assert!(!cfg.mcp_to_acp_boundary);
    }

    #[test]
    fn content_isolation_deserialize_absent_defaults_true() {
        let cfg: ContentIsolationConfig = toml::from_str("").unwrap();
        assert!(cfg.mcp_to_acp_boundary);
    }

    fn de_guard(toml: &str) -> Result<EmbeddingGuardConfig, toml::de::Error> {
        toml::from_str(toml)
    }

    #[test]
    fn threshold_valid() {
        let cfg = de_guard("threshold = 0.35\nmin_samples = 5").unwrap();
        assert!((cfg.threshold - 0.35).abs() < f64::EPSILON);
    }

    #[test]
    fn threshold_one_valid() {
        let cfg = de_guard("threshold = 1.0\nmin_samples = 1").unwrap();
        assert!((cfg.threshold - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn threshold_zero_rejected() {
        assert!(de_guard("threshold = 0.0\nmin_samples = 1").is_err());
    }

    #[test]
    fn threshold_above_one_rejected() {
        assert!(de_guard("threshold = 1.5\nmin_samples = 1").is_err());
    }

    #[test]
    fn threshold_negative_rejected() {
        assert!(de_guard("threshold = -0.1\nmin_samples = 1").is_err());
    }

    #[test]
    fn min_samples_zero_rejected() {
        assert!(de_guard("threshold = 0.35\nmin_samples = 0").is_err());
    }

    #[test]
    fn min_samples_one_valid() {
        let cfg = de_guard("threshold = 0.35\nmin_samples = 1").unwrap();
        assert_eq!(cfg.min_samples, 1);
    }
}

// ---------------------------------------------------------------------------
// CausalIpiConfig
// ---------------------------------------------------------------------------

fn default_causal_threshold() -> f32 {
    0.7
}

fn validate_causal_threshold<'de, D>(deserializer: D) -> Result<f32, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <f32 as serde::Deserialize>::deserialize(deserializer)?;
    if value.is_nan() || value.is_infinite() {
        return Err(serde::de::Error::custom(
            "causal_ipi.threshold must be a finite number",
        ));
    }
    if !(value > 0.0 && value <= 1.0) {
        return Err(serde::de::Error::custom(
            "causal_ipi.threshold must be in (0.0, 1.0]",
        ));
    }
    Ok(value)
}

fn default_probe_max_tokens() -> u32 {
    100
}

fn default_probe_timeout_ms() -> u64 {
    3000
}

/// Temporal causal IPI analysis at tool-return boundaries.
///
/// When enabled, the agent generates behavioral probes before and after tool batch dispatch
/// and compares them to detect behavioral deviation caused by injected instructions in
/// tool outputs. Probes are per-batch (2 LLM calls total), not per individual tool.
///
/// Config section: `[security.causal_ipi]`
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct CausalIpiConfig {
    /// Master switch. Default: false (opt-in).
    #[serde(default)]
    pub enabled: bool,

    /// Causal attribution score threshold for flagging. Range: (0.0, 1.0]. Default 0.7.
    ///
    /// Scores above this value trigger a WARN log, metric increment, and `SecurityEvent`.
    /// Content is never blocked — this is an observation layer only.
    #[serde(
        default = "default_causal_threshold",
        deserialize_with = "validate_causal_threshold"
    )]
    pub threshold: f32,

    /// LLM provider name from `[[llm.providers]]` for probe calls.
    ///
    /// Should reference a fast/cheap provider — probes run on every tool batch return.
    /// When `None`, falls back to the agent's default provider.
    #[serde(default)]
    pub provider: Option<String>,

    /// Maximum tokens for each probe response. Limits cost per probe call. Default: 100.
    ///
    /// Two probes per batch = max `2 * probe_max_tokens` output tokens per tool batch.
    #[serde(default = "default_probe_max_tokens")]
    pub probe_max_tokens: u32,

    /// Timeout in milliseconds for each individual probe LLM call. Default: 3000.
    ///
    /// On timeout: WARN log, skip causal analysis for the batch (never block).
    #[serde(default = "default_probe_timeout_ms")]
    pub probe_timeout_ms: u64,

    /// Shadow memory configuration for cross-turn trajectory analysis.
    #[serde(default)]
    pub shadow_memory: ShadowMemoryConfig,
}

impl Default for CausalIpiConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            threshold: default_causal_threshold(),
            provider: None,
            probe_max_tokens: default_probe_max_tokens(),
            probe_timeout_ms: default_probe_timeout_ms(),
            shadow_memory: ShadowMemoryConfig::default(),
        }
    }
}

// ---------------------------------------------------------------------------
// ShadowMemoryConfig
// ---------------------------------------------------------------------------

fn default_shadow_window() -> usize {
    8
}

fn default_shadow_max_events() -> usize {
    64
}

fn default_shadow_drift_threshold() -> f32 {
    0.6
}

fn validate_shadow_window<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <usize as serde::Deserialize>::deserialize(deserializer)?;
    if value == 0 {
        return Err(serde::de::Error::custom(
            "shadow_memory.window_size must be >= 1",
        ));
    }
    Ok(value)
}

fn validate_shadow_max_events<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <usize as serde::Deserialize>::deserialize(deserializer)?;
    if value == 0 {
        return Err(serde::de::Error::custom(
            "shadow_memory.max_events must be >= 1",
        ));
    }
    Ok(value)
}

fn validate_shadow_drift_threshold<'de, D>(deserializer: D) -> Result<f32, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = <f32 as serde::Deserialize>::deserialize(deserializer)?;
    if value.is_nan() || value.is_infinite() {
        return Err(serde::de::Error::custom(
            "shadow_memory.drift_threshold must be a finite number",
        ));
    }
    if !(value > 0.0 && value <= 1.0) {
        return Err(serde::de::Error::custom(
            "shadow_memory.drift_threshold must be in (0.0, 1.0]",
        ));
    }
    Ok(value)
}

/// Per-session append-only event store for cross-turn trajectory analysis.
///
/// Detects multi-turn attacks that distribute payload across several turns —
/// invisible to the stateless [`CausalIpiConfig`] single-batch analysis.
///
/// Config section: `[security.causal_ipi.shadow_memory]`
///
/// # Examples
///
/// ```toml
/// [security.causal_ipi.shadow_memory]
/// enabled = true
/// window_size = 8
/// max_events = 64
/// drift_threshold = 0.6
/// ```
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ShadowMemoryConfig {
    /// Enable shadow memory trajectory tracking. Default: false.
    #[serde(default)]
    pub enabled: bool,

    /// Sliding window size for drift computation. Must be >= 1. Default: 8.
    #[serde(
        default = "default_shadow_window",
        deserialize_with = "validate_shadow_window"
    )]
    pub window_size: usize,

    /// Maximum events retained before oldest are evicted. Must be >= 1. Default: 64.
    #[serde(
        default = "default_shadow_max_events",
        deserialize_with = "validate_shadow_max_events"
    )]
    pub max_events: usize,

    /// Goal drift score threshold for flagging. Range: (0.0, 1.0]. Default: 0.6.
    #[serde(
        default = "default_shadow_drift_threshold",
        deserialize_with = "validate_shadow_drift_threshold"
    )]
    pub drift_threshold: f32,
}

impl Default for ShadowMemoryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            window_size: default_shadow_window(),
            max_events: default_shadow_max_events(),
            drift_threshold: default_shadow_drift_threshold(),
        }
    }
}

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

    #[test]
    fn causal_ipi_defaults() {
        let cfg = CausalIpiConfig::default();
        assert!(!cfg.enabled);
        assert!((cfg.threshold - 0.7).abs() < 1e-6);
        assert!(cfg.provider.is_none());
        assert_eq!(cfg.probe_max_tokens, 100);
        assert_eq!(cfg.probe_timeout_ms, 3000);
    }

    #[test]
    fn causal_ipi_deserialize_enabled() {
        let toml = r#"
            enabled = true
            threshold = 0.8
            provider = "fast"
            probe_max_tokens = 150
            probe_timeout_ms = 5000
        "#;
        let cfg: CausalIpiConfig = toml::from_str(toml).unwrap();
        assert!(cfg.enabled);
        assert!((cfg.threshold - 0.8).abs() < 1e-6);
        assert_eq!(cfg.provider.as_deref(), Some("fast"));
        assert_eq!(cfg.probe_max_tokens, 150);
        assert_eq!(cfg.probe_timeout_ms, 5000);
    }

    #[test]
    fn causal_ipi_threshold_zero_rejected() {
        let result: Result<CausalIpiConfig, _> = toml::from_str("threshold = 0.0");
        assert!(result.is_err());
    }

    #[test]
    fn causal_ipi_threshold_above_one_rejected() {
        let result: Result<CausalIpiConfig, _> = toml::from_str("threshold = 1.1");
        assert!(result.is_err());
    }

    #[test]
    fn causal_ipi_threshold_exactly_one_accepted() {
        let cfg: CausalIpiConfig = toml::from_str("threshold = 1.0").unwrap();
        assert!((cfg.threshold - 1.0).abs() < 1e-6);
    }
}

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

    #[test]
    fn shadow_memory_defaults() {
        let cfg = ShadowMemoryConfig::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.window_size, 8);
        assert_eq!(cfg.max_events, 64);
        assert!((cfg.drift_threshold - 0.6).abs() < 1e-6);
    }

    #[test]
    fn shadow_memory_window_zero_rejected() {
        let result: Result<ShadowMemoryConfig, _> = toml::from_str("window_size = 0");
        assert!(result.is_err());
    }

    #[test]
    fn shadow_memory_max_events_zero_rejected() {
        let result: Result<ShadowMemoryConfig, _> = toml::from_str("max_events = 0");
        assert!(result.is_err());
    }

    #[test]
    fn shadow_memory_drift_threshold_zero_rejected() {
        let result: Result<ShadowMemoryConfig, _> = toml::from_str("drift_threshold = 0.0");
        assert!(result.is_err());
    }

    #[test]
    fn shadow_memory_drift_threshold_above_one_rejected() {
        let result: Result<ShadowMemoryConfig, _> = toml::from_str("drift_threshold = 1.1");
        assert!(result.is_err());
    }

    #[test]
    fn shadow_memory_drift_threshold_exactly_one_accepted() {
        let cfg: ShadowMemoryConfig = toml::from_str("drift_threshold = 1.0").unwrap();
        assert!((cfg.drift_threshold - 1.0).abs() < 1e-6);
    }

    #[test]
    fn shadow_memory_full_deserialization() {
        let toml = r"
            enabled = true
            window_size = 4
            max_events = 32
            drift_threshold = 0.8
        ";
        let cfg: ShadowMemoryConfig = toml::from_str(toml).unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.window_size, 4);
        assert_eq!(cfg.max_events, 32);
        assert!((cfg.drift_threshold - 0.8).abs() < 1e-6);
    }
}