zeph-sanitizer 0.22.3

Content sanitization, exfiltration guard, PII filtering, and quarantine 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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Core types for the sanitization pipeline: trust model, content provenance, and results.

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Trust model
// ---------------------------------------------------------------------------

/// Trust tier assigned to content entering the agent context.
///
/// Drives spotlighting intensity: [`Trusted`](ContentTrustLevel::Trusted) content passes
/// through unchanged; [`ExternalUntrusted`](ContentTrustLevel::ExternalUntrusted) receives
/// the strongest warning header.
///
/// The tier is typically derived automatically from [`ContentSourceKind::default_trust_level`],
/// but can be overridden via [`ContentSource::with_trust_level`] when the call-site has
/// more context about the actual origin of the content.
///
/// # Examples
///
/// ```rust
/// use zeph_sanitizer::{ContentTrustLevel, ContentSource, ContentSourceKind};
///
/// // Web scrapes default to the strongest warning level.
/// let source = ContentSource::new(ContentSourceKind::WebScrape);
/// assert_eq!(source.trust_level, ContentTrustLevel::ExternalUntrusted);
///
/// // Trust level can be overridden.
/// let elevated = source.with_trust_level(ContentTrustLevel::Trusted);
/// assert_eq!(elevated.trust_level, ContentTrustLevel::Trusted);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
#[repr(u8)]
pub enum ContentTrustLevel {
    /// System prompt, hardcoded instructions, direct user input. No wrapping applied.
    Trusted = 0,
    /// Tool results from local executors (shell, file I/O). Lighter warning.
    LocalUntrusted = 1,
    /// External sources: web scrape, MCP, A2A, memory retrieval. Strongest warning.
    ExternalUntrusted = 2,
}

impl ContentTrustLevel {
    /// Returns the `snake_case` identifier string for this trust level.
    ///
    /// Used for `SQLite`/Qdrant persistence (issue #6490 write-time provenance tagging),
    /// mirroring [`ContentSourceKind::as_str`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::ContentTrustLevel;
    ///
    /// assert_eq!(ContentTrustLevel::Trusted.as_str(), "trusted");
    /// assert_eq!(ContentTrustLevel::ExternalUntrusted.as_str(), "external_untrusted");
    /// ```
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Trusted => "trusted",
            Self::LocalUntrusted => "local_untrusted",
            Self::ExternalUntrusted => "external_untrusted",
        }
    }

    /// Parse a `&str` into a [`ContentTrustLevel`].
    ///
    /// Returns `None` for unrecognized strings so callers can fall back to a conservative
    /// default and log a warning instead of failing deserialization.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::ContentTrustLevel;
    ///
    /// assert_eq!(ContentTrustLevel::from_str_opt("local_untrusted"), Some(ContentTrustLevel::LocalUntrusted));
    /// assert_eq!(ContentTrustLevel::from_str_opt("unknown"), None);
    /// ```
    #[must_use]
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "trusted" => Some(Self::Trusted),
            "local_untrusted" => Some(Self::LocalUntrusted),
            "external_untrusted" => Some(Self::ExternalUntrusted),
            _ => None,
        }
    }

    /// Reconstruct from the `u8` discriminant.
    ///
    /// Used by turn-scoped trust-tier trackers (issue #6490) that store the tier as a bare
    /// `u8` in a lock-free slot (`AtomicU8`/`RwLock<u8>`) for cheap ratcheting via
    /// `fetch_max`/`max`. Values ≥ 2 saturate to [`ExternalUntrusted`](Self::ExternalUntrusted)
    /// (the most conservative tier) rather than panicking, so a slot value from a future added
    /// variant fails safe instead of undefined behavior.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::ContentTrustLevel;
    ///
    /// assert_eq!(ContentTrustLevel::from_ordinal(0), ContentTrustLevel::Trusted);
    /// assert_eq!(ContentTrustLevel::from_ordinal(2), ContentTrustLevel::ExternalUntrusted);
    /// assert_eq!(ContentTrustLevel::from_ordinal(255), ContentTrustLevel::ExternalUntrusted);
    /// ```
    #[must_use]
    pub fn from_ordinal(ordinal: u8) -> Self {
        match ordinal {
            0 => Self::Trusted,
            1 => Self::LocalUntrusted,
            _ => Self::ExternalUntrusted,
        }
    }
}

/// All known content source categories.
///
/// Used for spotlighting annotation and future per-source config overrides.
/// Each variant maps to a fixed [`ContentTrustLevel`] via [`default_trust_level`](Self::default_trust_level).
///
/// # Examples
///
/// ```rust
/// use zeph_sanitizer::{ContentSourceKind, ContentTrustLevel};
///
/// assert_eq!(
///     ContentSourceKind::ToolResult.default_trust_level(),
///     ContentTrustLevel::LocalUntrusted
/// );
/// assert_eq!(
///     ContentSourceKind::WebScrape.default_trust_level(),
///     ContentTrustLevel::ExternalUntrusted
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ContentSourceKind {
    /// Output from a locally-executed tool (shell, file I/O).
    ToolResult,
    /// Content fetched from a remote URL by the web-scrape tool.
    WebScrape,
    /// Response from an MCP (Model Context Protocol) server.
    McpResponse,
    /// Message received from another agent via the A2A protocol.
    A2aMessage,
    /// Content retrieved from Qdrant/SQLite semantic memory.
    ///
    /// Memory poisoning is a documented attack vector: an adversary can plant injection
    /// payloads in web content that gets stored, then recalled in future sessions.
    MemoryRetrieval,
    /// Project-level instruction files (`.zeph/zeph.md`, CLAUDE.md, etc.).
    ///
    /// Treated as `LocalUntrusted` by default. Path-based trust inference (e.g. treating
    /// user-authored files as `Trusted`) is a Phase 2 concern.
    InstructionFile,
    /// Primary message ingested from an external channel adapter (gateway webhook,
    /// and potentially Telegram/Discord in the future).
    ///
    /// The sender only proves possession of a bearer token or channel credential, not
    /// that the message content is safe — treated as `ExternalUntrusted` like any other
    /// network-supplied text.
    ChannelMessage,
}

impl ContentSourceKind {
    /// Returns the default [`ContentTrustLevel`] for this source kind.
    ///
    /// Tool results and instruction files are `LocalUntrusted`; all network-sourced
    /// content (web scrape, MCP, A2A, memory retrieval) is `ExternalUntrusted`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::{ContentSourceKind, ContentTrustLevel};
    ///
    /// assert_eq!(ContentSourceKind::McpResponse.default_trust_level(), ContentTrustLevel::ExternalUntrusted);
    /// assert_eq!(ContentSourceKind::InstructionFile.default_trust_level(), ContentTrustLevel::LocalUntrusted);
    /// ```
    #[must_use]
    pub fn default_trust_level(self) -> ContentTrustLevel {
        match self {
            Self::ToolResult | Self::InstructionFile => ContentTrustLevel::LocalUntrusted,
            Self::WebScrape
            | Self::McpResponse
            | Self::A2aMessage
            | Self::MemoryRetrieval
            | Self::ChannelMessage => ContentTrustLevel::ExternalUntrusted,
        }
    }

    /// Returns the `snake_case` identifier string for this source kind.
    ///
    /// Used for `SQLite`/Qdrant persistence (issue #6490 write-time provenance tagging).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::ContentSourceKind;
    ///
    /// assert_eq!(ContentSourceKind::WebScrape.as_str(), "web_scrape");
    /// ```
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ToolResult => "tool_result",
            Self::WebScrape => "web_scrape",
            Self::McpResponse => "mcp_response",
            Self::A2aMessage => "a2a_message",
            Self::MemoryRetrieval => "memory_retrieval",
            Self::InstructionFile => "instruction_file",
            Self::ChannelMessage => "channel_message",
        }
    }

    /// Parse a `&str` into a [`ContentSourceKind`].
    ///
    /// Returns `None` for unrecognized strings so callers can log a warning and
    /// skip unknown values without breaking deserialization.
    ///
    /// The comparison is case-sensitive and uses the canonical `snake_case` form
    /// (e.g. `"web_scrape"`, not `"WebScrape"`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::ContentSourceKind;
    ///
    /// assert_eq!(ContentSourceKind::from_str_opt("web_scrape"), Some(ContentSourceKind::WebScrape));
    /// assert_eq!(ContentSourceKind::from_str_opt("WebScrape"), None); // case-sensitive
    /// assert_eq!(ContentSourceKind::from_str_opt("unknown"), None);
    /// ```
    #[must_use]
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "tool_result" => Some(Self::ToolResult),
            "web_scrape" => Some(Self::WebScrape),
            "mcp_response" => Some(Self::McpResponse),
            "a2a_message" => Some(Self::A2aMessage),
            "memory_retrieval" => Some(Self::MemoryRetrieval),
            "instruction_file" => Some(Self::InstructionFile),
            "channel_message" => Some(Self::ChannelMessage),
            _ => None,
        }
    }
}

/// Hint about the origin of memory-retrieved content.
///
/// Used to modulate injection detection sensitivity within `ContentSanitizer::sanitize`].
/// The hint is set at call-site (compile-time) based on which retrieval path produced the
/// content — it cannot be influenced by the content itself and thus cannot be spoofed.
///
/// # Defense-in-depth invariant
///
/// Setting a hint to [`ConversationHistory`](MemorySourceHint::ConversationHistory) or
/// [`LlmSummary`](MemorySourceHint::LlmSummary) **only** skips injection pattern detection
/// (step 3). Truncation, control-character stripping, delimiter escaping, and spotlighting
/// remain active for all sources regardless of this hint.
///
/// # Known limitation: indirect memory poisoning
///
/// Conversation history is treated as first-party (user-typed) content. However, the LLM
/// may call `memory_save` with content derived from a prior injection in external sources
/// (web scrape → spotlighted → LLM stores payload → recalled as `[assistant]` turn).
/// Mitigate by configuring `forbidden_content_patterns` in `[memory.validation]` to block
/// known injection strings on the write path. This risk is pre-existing and is not worsened
/// by the hint mechanism.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MemorySourceHint {
    /// Prior user/assistant conversation turns (semantic recall, corrections).
    ///
    /// Injection patterns in recalled user text are expected false positives — the user
    /// legitimately discussed topics like "system prompt" or "show your instructions".
    ConversationHistory,
    /// LLM-generated summaries (session summaries, cross-session context).
    ///
    /// Low risk: generated by the agent's own model from already-sanitized content.
    LlmSummary,
    /// External document chunks or graph entity facts.
    ///
    /// Full detection applies — may contain adversarial content from web scrapes,
    /// MCP responses, or other untrusted sources that were stored in the corpus.
    ExternalContent,
}

/// Provenance metadata attached to a piece of untrusted content.
///
/// Created at the call-site (tool executor, MCP adapter, A2A handler, etc.) to describe
/// where content came from. Passed into `ContentSanitizer::sanitize`] alongside the raw
/// content so the pipeline can choose the appropriate spotlight wrapper and injection
/// detection sensitivity.
///
/// # Examples
///
/// ```rust
/// use zeph_sanitizer::{ContentSource, ContentSourceKind, ContentTrustLevel, MemorySourceHint};
///
/// // Basic source for a shell tool result.
/// let source = ContentSource::new(ContentSourceKind::ToolResult)
///     .with_identifier("shell");
/// assert_eq!(source.trust_level, ContentTrustLevel::LocalUntrusted);
/// assert_eq!(source.identifier.as_deref(), Some("shell"));
///
/// // Memory retrieval with a hint to skip injection detection for conversation turns.
/// let mem_source = ContentSource::new(ContentSourceKind::MemoryRetrieval)
///     .with_memory_hint(MemorySourceHint::ConversationHistory);
/// assert!(mem_source.memory_hint.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct ContentSource {
    /// The category of this content source.
    pub kind: ContentSourceKind,
    /// Trust tier that drives the spotlight wrapper choice.
    pub trust_level: ContentTrustLevel,
    /// Optional identifier: tool name, URL, agent ID, etc. Used in spotlight attributes.
    pub identifier: Option<String>,
    /// Optional hint for memory retrieval sub-sources. When `Some`, modulates injection
    /// detection sensitivity in `ContentSanitizer::sanitize`]. Non-memory sources leave
    /// this as `None` — full detection applies.
    pub memory_hint: Option<MemorySourceHint>,
}

impl ContentSource {
    /// Create a new source with the default trust level for the given kind.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::{ContentSource, ContentSourceKind, ContentTrustLevel};
    ///
    /// let source = ContentSource::new(ContentSourceKind::WebScrape);
    /// assert_eq!(source.trust_level, ContentTrustLevel::ExternalUntrusted);
    /// assert!(source.identifier.is_none());
    /// ```
    #[must_use]
    pub fn new(kind: ContentSourceKind) -> Self {
        Self {
            trust_level: kind.default_trust_level(),
            kind,
            identifier: None,
            memory_hint: None,
        }
    }

    /// Set the identifier for this source (tool name, URL, agent ID, etc.).
    ///
    /// The identifier appears in the spotlight wrapper's XML attributes so the LLM can
    /// see where the content came from (e.g. `name="shell"`, `ref="https://example.com"`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::{ContentSource, ContentSourceKind};
    ///
    /// let source = ContentSource::new(ContentSourceKind::ToolResult)
    ///     .with_identifier("shell");
    /// assert_eq!(source.identifier.as_deref(), Some("shell"));
    /// ```
    #[must_use]
    pub fn with_identifier(mut self, id: impl Into<String>) -> Self {
        self.identifier = Some(id.into());
        self
    }

    /// Override the trust level for this source.
    ///
    /// Use when the call-site has more context about the actual origin of the content
    /// than the default derived from the source kind.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zeph_sanitizer::{ContentSource, ContentSourceKind, ContentTrustLevel};
    ///
    /// // Elevate trust for a verified internal source.
    /// let source = ContentSource::new(ContentSourceKind::McpResponse)
    ///     .with_trust_level(ContentTrustLevel::LocalUntrusted);
    /// assert_eq!(source.trust_level, ContentTrustLevel::LocalUntrusted);
    /// ```
    #[must_use]
    pub fn with_trust_level(mut self, level: ContentTrustLevel) -> Self {
        self.trust_level = level;
        self
    }

    /// Attach a memory source hint to modulate injection detection sensitivity.
    ///
    /// Only meaningful for `ContentSourceKind::MemoryRetrieval` sources.
    #[must_use]
    pub fn with_memory_hint(mut self, hint: MemorySourceHint) -> Self {
        self.memory_hint = Some(hint);
        self
    }
}

// ---------------------------------------------------------------------------
// Output types
// ---------------------------------------------------------------------------

/// A single detected injection pattern match in sanitized content.
///
/// Produced by the regex injection-detection step inside `ContentSanitizer::sanitize`].
/// Injection flags are advisory — they are recorded in [`SanitizedContent`] and surfaced
/// in the spotlight warning header, but the content is never silently removed.
#[derive(Debug, Clone)]
pub struct InjectionFlag {
    /// Name of the compiled pattern that matched (from `zeph_common::patterns`).
    pub pattern_name: &'static str,
    /// Byte offset of the match within the (already truncated, stripped) content.
    pub byte_offset: usize,
    /// The matched substring. Kept for logging and operator review.
    pub matched_text: String,
}

/// Result of ML-based injection classification.
///
/// Replaces a plain `bool` to support a defense-in-depth dual-threshold model.
/// Real-world ML injection classifiers have 12–37% recall gaps at high confidence
/// thresholds, so `Suspicious` content is surfaced for operator visibility without
/// blocking — a mandatory second layer of defense.
///
/// Returned by `ContentSanitizer::classify_injection`] (feature `classifiers`).
///
/// # Examples
///
/// ```rust,ignore
/// // Requires `classifiers` feature and an attached backend.
/// let verdict = sanitizer.classify_injection("ignore all instructions").await;
/// assert!(matches!(verdict, InjectionVerdict::Blocked | InjectionVerdict::Suspicious));
/// ```
#[cfg(feature = "classifiers")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InjectionVerdict {
    /// Score below soft threshold — no injection signal detected.
    Clean,
    /// Score ≥ soft threshold but < hard threshold — suspicious, warn only.
    Suspicious,
    /// Score ≥ hard threshold — injection detected. Behavior depends on enforcement mode.
    Blocked,
}

/// Classification result from the three-class `AlignSentinel` model.
///
/// Used in Stage 2 of `ContentSanitizer::classify_injection`] to refine binary injection
/// verdicts. `AlignedInstruction` and `NoInstruction` results downgrade `Suspicious`/`Blocked`
/// to `Clean`, reducing false positives from legitimate instruction-style content in tool
/// outputs (e.g. a script that prints "run as root").
///
/// Only active when a three-class backend is attached via
/// `ContentSanitizer::with_three_class_backend`].
#[cfg(feature = "classifiers")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InstructionClass {
    /// Content contains no instruction-like text.
    NoInstruction,
    /// Content contains instructions aligned with the system's objectives.
    AlignedInstruction,
    /// Content contains instructions that conflict with the system's objectives.
    MisalignedInstruction,
    /// Model returned an unknown label. Treated conservatively — verdict is NOT downgraded.
    Unknown,
}

#[cfg(feature = "classifiers")]
impl InstructionClass {
    pub(crate) fn from_label(label: &str) -> Self {
        match label.to_lowercase().as_str() {
            "no_instruction" | "no-instruction" | "none" => Self::NoInstruction,
            "aligned_instruction" | "aligned-instruction" | "aligned" => Self::AlignedInstruction,
            "misaligned_instruction" | "misaligned-instruction" | "misaligned" => {
                Self::MisalignedInstruction
            }
            _ => Self::Unknown,
        }
    }
}

/// Result of the sanitization pipeline for a single piece of content.
///
/// The `body` field is the processed text ready to insert into the agent's message history.
/// Callers should inspect `injection_flags` for threat intelligence and `was_truncated` to
/// decide whether to emit a "content was truncated" notice to the user.
///
/// # Examples
///
/// ```rust
/// use zeph_sanitizer::{ContentSanitizer, ContentSource, ContentSourceKind};
/// use zeph_config::ContentIsolationConfig;
///
/// let sanitizer = ContentSanitizer::new(&ContentIsolationConfig::default());
/// let result = sanitizer.sanitize(
///     "normal tool output",
///     ContentSource::new(ContentSourceKind::ToolResult),
/// );
/// assert!(!result.was_truncated);
/// assert!(result.injection_flags.is_empty());
/// assert!(result.body.contains("normal tool output"));
/// ```
#[derive(Debug, Clone)]
pub struct SanitizedContent {
    /// The processed, possibly spotlighted body ready to insert into message history.
    pub body: String,
    /// Provenance metadata for this content.
    pub source: ContentSource,
    /// Injection patterns matched during detection (advisory — content is never removed).
    pub injection_flags: Vec<InjectionFlag>,
    /// `true` when content was truncated to `max_content_size`.
    pub was_truncated: bool,
}

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

    // --- ContentSourceKind::from_str_opt roundtrip ---

    #[test]
    fn from_str_opt_known_variants_roundtrip() {
        let variants = [
            (ContentSourceKind::ToolResult, "tool_result"),
            (ContentSourceKind::WebScrape, "web_scrape"),
            (ContentSourceKind::McpResponse, "mcp_response"),
            (ContentSourceKind::A2aMessage, "a2a_message"),
            (ContentSourceKind::MemoryRetrieval, "memory_retrieval"),
            (ContentSourceKind::InstructionFile, "instruction_file"),
            (ContentSourceKind::ChannelMessage, "channel_message"),
        ];
        for (kind, s) in &variants {
            assert_eq!(ContentSourceKind::from_str_opt(s), Some(*kind));
            assert_eq!(kind.as_str(), *s);
        }
    }

    #[test]
    fn from_str_opt_unknown_returns_none() {
        assert_eq!(ContentSourceKind::from_str_opt("unknown"), None);
        assert_eq!(ContentSourceKind::from_str_opt(""), None);
    }

    #[test]
    fn from_str_opt_case_sensitive() {
        assert_eq!(ContentSourceKind::from_str_opt("WebScrape"), None);
        assert_eq!(ContentSourceKind::from_str_opt("TOOL_RESULT"), None);
    }

    // --- ContentSource builder methods ---

    #[test]
    fn content_source_new_has_default_trust_and_no_identifier() {
        let source = ContentSource::new(ContentSourceKind::WebScrape);
        assert_eq!(source.trust_level, ContentTrustLevel::ExternalUntrusted);
        assert!(source.identifier.is_none());
        assert!(source.memory_hint.is_none());
    }

    #[test]
    fn content_source_with_identifier() {
        let source = ContentSource::new(ContentSourceKind::ToolResult).with_identifier("shell");
        assert_eq!(source.identifier.as_deref(), Some("shell"));
    }

    #[test]
    fn content_source_with_trust_level_override() {
        let source = ContentSource::new(ContentSourceKind::McpResponse)
            .with_trust_level(ContentTrustLevel::LocalUntrusted);
        assert_eq!(source.trust_level, ContentTrustLevel::LocalUntrusted);
    }

    #[test]
    fn content_source_with_memory_hint() {
        let source = ContentSource::new(ContentSourceKind::MemoryRetrieval)
            .with_memory_hint(MemorySourceHint::ConversationHistory);
        assert_eq!(
            source.memory_hint,
            Some(MemorySourceHint::ConversationHistory)
        );
    }

    // --- ContentTrustLevel ---

    #[test]
    fn content_trust_level_equality() {
        assert_eq!(ContentTrustLevel::Trusted, ContentTrustLevel::Trusted);
        assert_ne!(
            ContentTrustLevel::Trusted,
            ContentTrustLevel::LocalUntrusted
        );
        assert_ne!(
            ContentTrustLevel::LocalUntrusted,
            ContentTrustLevel::ExternalUntrusted
        );
    }

    // --- ContentTrustLevel::as_str / from_str_opt roundtrip (issue #6490) ---

    #[test]
    fn trust_level_from_str_opt_known_variants_roundtrip() {
        let variants = [
            (ContentTrustLevel::Trusted, "trusted"),
            (ContentTrustLevel::LocalUntrusted, "local_untrusted"),
            (ContentTrustLevel::ExternalUntrusted, "external_untrusted"),
        ];
        for (level, s) in &variants {
            assert_eq!(ContentTrustLevel::from_str_opt(s), Some(*level));
            assert_eq!(level.as_str(), *s);
        }
    }

    #[test]
    fn trust_level_from_str_opt_unknown_returns_none() {
        assert_eq!(ContentTrustLevel::from_str_opt("unknown"), None);
        assert_eq!(ContentTrustLevel::from_str_opt(""), None);
    }

    #[test]
    fn trust_level_ord_matches_severity() {
        assert!(ContentTrustLevel::Trusted < ContentTrustLevel::LocalUntrusted);
        assert!(ContentTrustLevel::LocalUntrusted < ContentTrustLevel::ExternalUntrusted);
        assert_eq!(
            ContentTrustLevel::Trusted.max(ContentTrustLevel::ExternalUntrusted),
            ContentTrustLevel::ExternalUntrusted
        );
    }

    // --- default_trust_level mapping ---

    #[test]
    fn default_trust_level_local_kinds() {
        assert_eq!(
            ContentSourceKind::ToolResult.default_trust_level(),
            ContentTrustLevel::LocalUntrusted
        );
        assert_eq!(
            ContentSourceKind::InstructionFile.default_trust_level(),
            ContentTrustLevel::LocalUntrusted
        );
    }

    #[test]
    fn default_trust_level_external_kinds() {
        for kind in [
            ContentSourceKind::WebScrape,
            ContentSourceKind::McpResponse,
            ContentSourceKind::A2aMessage,
            ContentSourceKind::MemoryRetrieval,
            ContentSourceKind::ChannelMessage,
        ] {
            assert_eq!(
                kind.default_trust_level(),
                ContentTrustLevel::ExternalUntrusted
            );
        }
    }
}