lean-ctx-engine 3.12.3

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
// SPDX-License-Identifier: Apache-2.0
//! Provable security events for the value surface.
//!
//! lean-ctx's default-on protections (secret redaction, the shell allowlist,
//! the path jail, prompt-injection screening) used to act silently: nothing a
//! user could later point to. This module turns each firing into
//!
//! 1. a hash-chained, signed [`crate::core::audit_trail`] entry — the proof, and
//! 2. a session counter ([`SecurityCounts`]) — what the status line shows.
//!
//! Counting is **once per tool result**. Deep code (redaction, allowlist) calls
//! [`note`], which only lands in the collector that
//! [`collect`] opens around one MCP tool handler; the dispatch layer then
//! records the tally for that single result. `note` outside a collector (CLI,
//! hooks, config loading) is deliberately dropped, so a secret redacted twice
//! on its way through nested passes, or a re-rendered cache entry outside a
//! tool call, never inflates the count. Undercounting is acceptable; claiming
//! more than happened is not. Prompt-injection flags go further: one per
//! flagged object per process ([`record_injections`]), however often the same
//! object is delivered again.
//!
//! The audit trail's `event_type` enum is **not** extended: an older binary
//! verifying a trail that contains an unknown variant would report it as
//! tampered. The kind is committed in the (hashed) `action` field instead.

use std::cell::RefCell;
use std::sync::Mutex;

use serde::{Deserialize, Serialize};

/// What a protection did. The wording each kind renders with is part of the
/// honesty contract: injections are *flagged*, never "neutralized".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecurityKind {
    /// A secret was replaced by `[REDACTED:…]` before the model saw it.
    SecretRedacted,
    /// A shell command was refused by the allowlist / dangerous-pattern gate.
    ShellBlocked,
    /// A path outside the project jail was refused.
    PathBlocked,
    /// Tool output matched prompt-injection patterns and was flagged.
    InjectionFlagged,
    /// A checksum-validated PII value was masked by the context gateway.
    PiiRedacted,
    /// The context gateway withheld a source entirely.
    ContentWithheld,
    /// A source was delivered although a detector did not inspect all of it.
    CoverageIncomplete,
}

impl SecurityKind {
    /// Stable identifier committed into the audit trail's `action` field.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SecretRedacted => "secret_redacted",
            Self::ShellBlocked => "shell_blocked",
            Self::PathBlocked => "path_blocked",
            Self::InjectionFlagged => "injection_flagged",
            Self::PiiRedacted => "pii_redacted",
            Self::ContentWithheld => "content_withheld",
            Self::CoverageIncomplete => "coverage_incomplete",
        }
    }

    /// Existing trail event types only: an unknown variant would read as
    /// tampering to an older verifier, so the kind lives in `action`.
    fn audit_event_type(self) -> crate::core::audit_trail::AuditEventType {
        use crate::core::audit_trail::AuditEventType;
        match self {
            Self::SecretRedacted | Self::PiiRedacted => AuditEventType::SecretDetected,
            Self::ShellBlocked | Self::ContentWithheld => AuditEventType::ToolDenied,
            Self::PathBlocked => AuditEventType::PathJailViolation,
            Self::InjectionFlagged | Self::CoverageIncomplete => AuditEventType::SecurityViolation,
        }
    }

    /// Parses the `action` prefix written by [`record`] back into a kind.
    pub fn from_action(action: &str) -> Option<Self> {
        let kind = action.split(':').next()?;
        Self::ALL.into_iter().find(|k| k.as_str() == kind)
    }

    /// Kinds a signed savings-batch tally carries; server mirrors verify the
    /// tally field by field and predate the context-gateway kinds.
    #[must_use]
    pub const fn in_signed_tally(self) -> bool {
        matches!(
            self,
            Self::SecretRedacted | Self::ShellBlocked | Self::PathBlocked | Self::InjectionFlagged
        )
    }

    const ALL: [Self; 7] = [
        Self::SecretRedacted,
        Self::ShellBlocked,
        Self::PathBlocked,
        Self::InjectionFlagged,
        Self::PiiRedacted,
        Self::ContentWithheld,
        Self::CoverageIncomplete,
    ];
}

/// Per-kind event counts. Persisted inside `SessionStats`, so every field is
/// `serde(default)` and old session files load unchanged.
///
/// The context-gateway kinds are written only when non-zero: every count
/// serialized before they existed keeps its exact bytes (signed tallies, see
/// [`Self::signed_tally_projection`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SecurityCounts {
    pub secrets_redacted: u64,
    pub shell_blocked: u64,
    pub path_blocked: u64,
    pub injection_flagged: u64,
    #[serde(skip_serializing_if = "is_zero")]
    pub pii_redacted: u64,
    #[serde(skip_serializing_if = "is_zero")]
    pub content_withheld: u64,
    #[serde(skip_serializing_if = "is_zero")]
    pub coverage_incomplete: u64,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(n: &u64) -> bool {
    *n == 0
}

impl SecurityCounts {
    /// The counts a signed savings-batch tally carries. Server mirrors verify
    /// the tally field by field and do not know the gateway kinds yet, so they
    /// are left out (zero, hence not serialized) instead of breaking the
    /// signature; the audit trail still proves them locally.
    #[must_use]
    pub fn signed_tally_projection(&self) -> Self {
        Self {
            pii_redacted: 0,
            content_withheld: 0,
            coverage_incomplete: 0,
            ..*self
        }
    }

    pub const ZERO: Self = Self {
        secrets_redacted: 0,
        shell_blocked: 0,
        path_blocked: 0,
        injection_flagged: 0,
        pii_redacted: 0,
        content_withheld: 0,
        coverage_incomplete: 0,
    };

    fn slot(&mut self, kind: SecurityKind) -> &mut u64 {
        match kind {
            SecurityKind::SecretRedacted => &mut self.secrets_redacted,
            SecurityKind::ShellBlocked => &mut self.shell_blocked,
            SecurityKind::PathBlocked => &mut self.path_blocked,
            SecurityKind::InjectionFlagged => &mut self.injection_flagged,
            SecurityKind::PiiRedacted => &mut self.pii_redacted,
            SecurityKind::ContentWithheld => &mut self.content_withheld,
            SecurityKind::CoverageIncomplete => &mut self.coverage_incomplete,
        }
    }

    fn get(&self, kind: SecurityKind) -> u64 {
        match kind {
            SecurityKind::SecretRedacted => self.secrets_redacted,
            SecurityKind::ShellBlocked => self.shell_blocked,
            SecurityKind::PathBlocked => self.path_blocked,
            SecurityKind::InjectionFlagged => self.injection_flagged,
            SecurityKind::PiiRedacted => self.pii_redacted,
            SecurityKind::ContentWithheld => self.content_withheld,
            SecurityKind::CoverageIncomplete => self.coverage_incomplete,
        }
    }

    pub fn add(&mut self, kind: SecurityKind, n: u64) {
        let slot = self.slot(kind);
        *slot = slot.saturating_add(n);
    }

    pub fn merge(&mut self, other: &Self) {
        for kind in SecurityKind::ALL {
            self.add(kind, other.get(kind));
        }
    }

    /// Events since `base` (a counter never goes below zero).
    #[must_use]
    pub fn since(&self, base: &Self) -> Self {
        let mut out = Self::ZERO;
        for kind in SecurityKind::ALL {
            *out.slot(kind) = self.get(kind).saturating_sub(base.get(kind));
        }
        out
    }

    pub fn total(&self) -> u64 {
        SecurityKind::ALL
            .into_iter()
            .fold(0u64, |sum, kind| sum.saturating_add(self.get(kind)))
    }

    pub fn is_empty(&self) -> bool {
        self.total() == 0
    }

    fn iter(&self) -> impl Iterator<Item = (SecurityKind, u64)> + '_ {
        SecurityKind::ALL
            .into_iter()
            .map(|kind| (kind, self.get(kind)))
            .filter(|(_, n)| *n > 0)
    }
}

/// Why the I/O boundary refused a path a call asked for. The trail records
/// this class only: like every other entry, never the path, a digest of it
/// or any content.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefusalClass {
    /// A secret-like path (`.env`, key material, credential files): withheld.
    SecretPath,
    /// Outside the project root, its trusted roots or the Workspace.
    OutsideRoot,
    /// lean-ctx's own runtime context, or a symlink inside the jail.
    ProtectedPath,
}

impl RefusalClass {
    /// Stable identifier committed as `reason=` into the trail's `action`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SecretPath => "secret_path",
            Self::OutsideRoot => "outside_root",
            Self::ProtectedPath => "protected_path",
        }
    }

    /// The counted kind: a secret path is withheld content; every other class
    /// is the path jail's existing `path_blocked`.
    pub const fn kind(self) -> SecurityKind {
        match self {
            Self::SecretPath => SecurityKind::ContentWithheld,
            Self::OutsideRoot | Self::ProtectedPath => SecurityKind::PathBlocked,
        }
    }

    /// The class of a path-jail refusal. A path that simply does not exist
    /// (or a malformed one) is no boundary decision and has none.
    pub fn of_jail_error(error: &crate::core::error::PathJailError) -> Option<Self> {
        use crate::core::error::PathJailError;
        match error {
            PathJailError::EscapesRoot { .. }
            | PathJailError::PostCanonicalizeEscape { .. }
            | PathJailError::OutsideWorkspace { .. }
            | PathJailError::WorkspaceUnavailable { .. } => Some(Self::OutsideRoot),
            PathJailError::ProtectedContext { .. } | PathJailError::Symlink { .. } => {
                Some(Self::ProtectedPath)
            }
            PathJailError::NullByte | PathJailError::NoExistingAncestor { .. } => None,
        }
    }

    const ALL: [Self; 3] = [Self::SecretPath, Self::OutsideRoot, Self::ProtectedPath];
}

/// What one tool call noted: the per-kind counts and the boundary refusals,
/// which are recorded with their [`RefusalClass`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CallTally {
    pub counts: SecurityCounts,
    refusals: [u64; RefusalClass::ALL.len()],
}

impl CallTally {
    fn merge(&mut self, other: &Self) {
        self.counts.merge(&other.counts);
        for (mine, theirs) in self.refusals.iter_mut().zip(other.refusals) {
            *mine = mine.saturating_add(theirs);
        }
    }

    /// Refusals noted for `class`.
    #[must_use]
    pub fn refusals(&self, class: RefusalClass) -> u64 {
        self.refusals[class as usize]
    }
}

thread_local! {
    static COLLECTOR: RefCell<Option<CallTally>> = const { RefCell::new(None) };
}

/// Notes `n` firings of `kind` into the collector of the tool call running on
/// this thread. A no-op outside [`collect`] — see the module docs for why.
pub fn note(kind: SecurityKind, n: usize) {
    if n == 0 {
        return;
    }
    COLLECTOR.with(|c| {
        if let Some(tally) = c.borrow_mut().as_mut() {
            tally.counts.add(kind, n as u64);
        }
    });
}

/// Notes `n` boundary refusals of `class` into the running call's collector,
/// like [`note`] (a no-op outside one). A call that refuses several paths of
/// one class gets one trail entry carrying the count.
pub fn note_refusals(class: RefusalClass, n: usize) {
    if n == 0 {
        return;
    }
    COLLECTOR.with(|c| {
        if let Some(tally) = c.borrow_mut().as_mut() {
            let slot = &mut tally.refusals[class as usize];
            *slot = slot.saturating_add(n as u64);
        }
    });
}

/// Runs `f` (one synchronous tool handler) with a fresh collector and returns
/// what it noted. Nested calls keep the outer collector's tally intact.
pub fn collect<T>(f: impl FnOnce() -> T) -> (T, SecurityCounts) {
    let (value, tally) = collect_call(f);
    (value, tally.counts)
}

/// [`collect`], including the call's boundary refusals ([`record_call`]).
pub fn collect_call<T>(f: impl FnOnce() -> T) -> (T, CallTally) {
    let outer = COLLECTOR.with(|c| c.borrow_mut().replace(CallTally::default()));
    let value = f();
    let tally = COLLECTOR
        .with(|c| std::mem::replace(&mut *c.borrow_mut(), outer))
        .unwrap_or_default();
    if let Some(mut outer) = outer {
        outer.merge(&tally);
        COLLECTOR.with(|c| *c.borrow_mut() = Some(outer));
    }
    (value, tally)
}

/// Counts recorded since the MCP server last drained them into its session.
static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts::ZERO);

/// The session suffix of a trail `action`. The session id rides in the hashed
/// `action` field (the trail's timestamp is not hashed), so per-session
/// security claims are chain-backed.
fn session_suffix() -> String {
    crate::core::value::current_session()
        .map(|id| format!("|session={id}"))
        .unwrap_or_default()
}

/// The audit `action` of `n` refusals: the count first (older readers parse
/// `<kind>:<n>` up to the session), then the reason class, then the session.
fn refusal_action(class: RefusalClass, n: u64, session: &str) -> String {
    format!(
        "{}:{n}|reason={}{session}",
        class.kind().as_str(),
        class.as_str()
    )
}

/// Records `n` boundary refusals of `class` for one tool call: one trail
/// entry with the reason class (never the path) plus the session counter.
pub fn record_refusals(tool: &str, agent_id: &str, class: RefusalClass, n: u64) {
    if n == 0 {
        return;
    }
    let kind = class.kind();
    crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
        agent_id: agent_id.to_string(),
        tool: tool.to_string(),
        action: Some(refusal_action(class, n, &session_suffix())),
        input_hash: String::new(),
        output_tokens: 0,
        role: crate::core::roles::active_role_name(),
        event_type: kind.audit_event_type(),
    });
    if let Ok(mut pending) = PENDING.lock() {
        pending.add(kind, n);
    }
}

/// Records one tool call's [`CallTally`]: the counted kinds ([`record`]) and
/// one entry per refusal class.
pub fn record_call(tool: &str, agent_id: &str, tally: &CallTally) {
    record(tool, agent_id, &tally.counts);
    for class in RefusalClass::ALL {
        record_refusals(tool, agent_id, class, tally.refusals(class));
    }
}

/// Records one tool result's security tally: one audit-trail entry per kind
/// (the proof) plus the pending session counters (the display).
pub fn record(tool: &str, agent_id: &str, counts: &SecurityCounts) {
    if counts.is_empty() {
        return;
    }
    let role = crate::core::roles::active_role_name();
    let session = session_suffix();
    for (kind, n) in counts.iter() {
        crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
            agent_id: agent_id.to_string(),
            tool: tool.to_string(),
            action: Some(format!("{}:{n}{session}", kind.as_str())),
            input_hash: String::new(),
            output_tokens: 0,
            role: role.clone(),
            event_type: kind.audit_event_type(),
        });
    }
    if let Ok(mut pending) = PENDING.lock() {
        pending.merge(counts);
    }
}

/// One object the prompt-injection heuristic flagged: which pattern families
/// matched and the object's SHA-256 — never its content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InjectionFlag {
    /// Lowercase hex SHA-256 of the flagged object.
    pub object_sha256: String,
    /// [`crate::core::output_sanitizer::InjectionCategory`] bits.
    pub patterns: u8,
}

/// Flagged objects remembered per process (a few hundred KiB at most).
const SEEN_INJECTIONS_CAPACITY: usize = 4096;

/// Digests of flagged objects recorded by this process, bounded LRU.
static SEEN_INJECTIONS: Mutex<Option<lru::LruCache<String, ()>>> = Mutex::new(None);

/// Whether this process records `object_sha256` for the first time. The
/// proxy re-admits the unchanged history of every turn and agents re-read the
/// same files: the object is one finding, not one per delivery. Receipts
/// still carry the per-delivery signal.
fn first_sighting(object_sha256: &str) -> bool {
    let Ok(mut seen) = SEEN_INJECTIONS.lock() else {
        // Undercounting is acceptable; claiming more than happened is not.
        return false;
    };
    let seen = seen.get_or_insert_with(|| {
        lru::LruCache::new(
            std::num::NonZeroUsize::new(SEEN_INJECTIONS_CAPACITY).expect("non-zero capacity"),
        )
    });
    seen.put(object_sha256.to_owned(), ()).is_none()
}

/// The audit `action` of one flagged object: the count first (older readers
/// parse `<kind>:<n>` up to the session), then what matched and a short
/// object digest prefix, then the session.
fn injection_action(flag: &InjectionFlag, session: &str) -> String {
    let prefix: String = flag.object_sha256.chars().take(12).collect();
    format!(
        "{}:1|pattern={}|object={prefix}{session}",
        SecurityKind::InjectionFlagged.as_str(),
        crate::core::output_sanitizer::InjectionCategory::describe(flag.patterns),
    )
}

/// Records flagged objects: one audit-trail entry per object this process has
/// not recorded yet (with the pattern kinds and a digest prefix, never
/// content) plus the pending session counter. Returns how many were recorded.
pub fn record_injections(tool: &str, agent_id: &str, flags: &[InjectionFlag]) -> u64 {
    let fresh: Vec<&InjectionFlag> = flags
        .iter()
        .filter(|flag| first_sighting(&flag.object_sha256))
        .collect();
    if fresh.is_empty() {
        return 0;
    }
    let role = crate::core::roles::active_role_name();
    let session = crate::core::value::current_session()
        .map(|id| format!("|session={id}"))
        .unwrap_or_default();
    for flag in &fresh {
        crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
            agent_id: agent_id.to_string(),
            tool: tool.to_string(),
            action: Some(injection_action(flag, &session)),
            input_hash: String::new(),
            output_tokens: 0,
            role: role.clone(),
            event_type: SecurityKind::InjectionFlagged.audit_event_type(),
        });
    }
    let recorded = fresh.len() as u64;
    if let Ok(mut pending) = PENDING.lock() {
        pending.add(SecurityKind::InjectionFlagged, recorded);
    }
    recorded
}

/// Anchors a Context Gateway receipt in the signed, hash-chained audit trail:
/// the digest in the hashed `action` binds the stored receipt to the chain.
/// Not a counted kind (`parse_action` ignores it), so nothing is counted twice.
pub fn anchor_receipt(tool: &str, agent_id: &str, receipt_sha256_hex: &str) {
    let session = crate::core::value::current_session()
        .map(|id| format!("|session={id}"))
        .unwrap_or_default();
    crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
        agent_id: agent_id.to_string(),
        tool: tool.to_string(),
        action: Some(format!("gateway_receipt:{receipt_sha256_hex}{session}")),
        input_hash: String::new(),
        output_tokens: 0,
        role: crate::core::roles::active_role_name(),
        event_type: crate::core::audit_trail::AuditEventType::ToolCall,
    });
}

/// Convenience for a single event recorded outside a handler (dispatch layer).
pub fn record_one(tool: &str, agent_id: &str, kind: SecurityKind) {
    let mut counts = SecurityCounts::default();
    counts.add(kind, 1);
    record(tool, agent_id, &counts);
}

/// Takes the counts recorded since the last drain (the MCP server folds them
/// into the current session's stats).
pub fn drain_pending() -> SecurityCounts {
    PENDING
        .lock()
        .map(|mut pending| std::mem::take(&mut *pending))
        .unwrap_or_default()
}

/// Splits a recorded `action` (`<kind>:<n>[|<detail>…][|session=<id>]`) into
/// its parts; details (an injection flag's pattern kinds) are skipped.
pub fn parse_action(action: &str) -> Option<(SecurityKind, u64, Option<&str>)> {
    let kind = SecurityKind::from_action(action)?;
    let rest = action.split_once(':').map_or("", |(_, rest)| rest);
    let (head, session) = match rest.split_once("|session=") {
        Some((head, session)) => (head, Some(session)),
        None => (rest, None),
    };
    let n = head.split('|').next().unwrap_or(head);
    Some((kind, n.parse().unwrap_or(1), session))
}

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

    #[test]
    fn note_outside_collector_is_dropped() {
        note(SecurityKind::SecretRedacted, 3);
        let ((), tally) = collect(|| {});
        assert!(tally.is_empty());
    }

    #[test]
    fn collect_counts_only_its_own_handler() {
        let ((), tally) = collect(|| {
            note(SecurityKind::SecretRedacted, 2);
            note(SecurityKind::ShellBlocked, 1);
        });
        assert_eq!(tally.secrets_redacted, 2);
        assert_eq!(tally.shell_blocked, 1);
        assert_eq!(tally.total(), 3);

        let ((), next) = collect(|| {});
        assert!(
            next.is_empty(),
            "a collector never leaks into the next call"
        );
    }

    #[test]
    fn nested_collect_keeps_outer_total() {
        let ((), outer) = collect(|| {
            note(SecurityKind::PathBlocked, 1);
            let ((), inner) = collect(|| note(SecurityKind::PathBlocked, 1));
            assert_eq!(inner.path_blocked, 1);
        });
        assert_eq!(outer.path_blocked, 2);
    }

    #[test]
    fn action_roundtrips_kind() {
        for kind in [
            SecurityKind::SecretRedacted,
            SecurityKind::ShellBlocked,
            SecurityKind::PathBlocked,
            SecurityKind::InjectionFlagged,
        ] {
            let action = format!("{}:4", kind.as_str());
            assert_eq!(SecurityKind::from_action(&action), Some(kind));
        }
        assert_eq!(SecurityKind::from_action("tool_call"), None);
    }

    #[test]
    fn parse_action_reads_count_and_session() {
        assert_eq!(
            parse_action("secret_redacted:3|session=abc"),
            Some((SecurityKind::SecretRedacted, 3, Some("abc")))
        );
        assert_eq!(
            parse_action("shell_blocked:1"),
            Some((SecurityKind::ShellBlocked, 1, None))
        );
    }

    #[test]
    fn a_flagged_object_is_recorded_once_per_process() {
        let object = "f".repeat(63) + "1";
        assert!(first_sighting(&object), "first delivery is recorded");
        assert!(!first_sighting(&object), "a re-read is not a new finding");
        assert!(first_sighting(&("f".repeat(63) + "2")));
    }

    #[test]
    fn injection_action_explains_without_content_and_parses() {
        let flag = InjectionFlag {
            object_sha256: "0123456789abcdef".repeat(4),
            patterns: crate::core::output_sanitizer::InjectionCategory::RoleMarker.bit(),
        };
        let action = injection_action(&flag, "|session=s1");
        assert_eq!(
            action,
            "injection_flagged:1|pattern=role_marker|object=0123456789ab|session=s1"
        );
        assert_eq!(
            parse_action(&action),
            Some((SecurityKind::InjectionFlagged, 1, Some("s1")))
        );
        assert_eq!(
            parse_action(&injection_action(&flag, "")),
            Some((SecurityKind::InjectionFlagged, 1, None))
        );
    }

    #[test]
    fn refusal_action_carries_the_class_only_and_parses() {
        let action = refusal_action(RefusalClass::SecretPath, 1, "|session=s1");
        assert_eq!(action, "content_withheld:1|reason=secret_path|session=s1");
        assert_eq!(
            parse_action(&action),
            Some((SecurityKind::ContentWithheld, 1, Some("s1")))
        );
        let action = refusal_action(RefusalClass::OutsideRoot, 2, "");
        assert_eq!(action, "path_blocked:2|reason=outside_root");
        assert_eq!(
            parse_action(&action),
            Some((SecurityKind::PathBlocked, 2, None))
        );
    }

    #[test]
    fn refusals_are_collected_per_class_and_kept_apart_from_counts() {
        let ((), tally) = collect_call(|| {
            note_refusals(RefusalClass::SecretPath, 2);
            let ((), inner) = collect_call(|| note_refusals(RefusalClass::OutsideRoot, 1));
            assert_eq!(inner.refusals(RefusalClass::OutsideRoot), 1);
            note(SecurityKind::SecretRedacted, 1);
        });
        assert_eq!(tally.refusals(RefusalClass::SecretPath), 2);
        assert_eq!(tally.refusals(RefusalClass::OutsideRoot), 1);
        assert_eq!(tally.refusals(RefusalClass::ProtectedPath), 0);
        assert_eq!(
            tally.counts.total(),
            1,
            "a refusal is recorded once, not as a count too"
        );

        note_refusals(RefusalClass::SecretPath, 1);
        let ((), next) = collect_call(|| {});
        assert_eq!(
            next,
            CallTally::default(),
            "outside a collector it is dropped"
        );
    }

    #[test]
    fn a_missing_path_is_no_boundary_refusal() {
        use crate::core::error::PathJailError;
        let escape = PathJailError::EscapesRoot {
            path: "/etc/passwd".into(),
            root: "/p".into(),
            hint: String::new(),
        };
        assert_eq!(
            RefusalClass::of_jail_error(&escape),
            Some(RefusalClass::OutsideRoot)
        );
        let symlink = PathJailError::Symlink {
            path: "/p/l".into(),
        };
        assert_eq!(
            RefusalClass::of_jail_error(&symlink),
            Some(RefusalClass::ProtectedPath)
        );
        let missing = PathJailError::NoExistingAncestor { path: "/x".into() };
        assert_eq!(RefusalClass::of_jail_error(&missing), None);
    }

    #[test]
    fn old_session_json_loads_with_zero_counts() {
        let counts: SecurityCounts = serde_json::from_str("{}").unwrap();
        assert!(counts.is_empty());
    }
}