vetto 0.2.15

Daemon-less sandbox + security layer for AI coding agents (Landlock/Seatbelt, TUI statusline, post-session audit reports)
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
//! Shared, backend-independent state for the statusline and full dashboards.
//!
//! The state is deliberately fed by the event bus instead of by a periodic
//! sampler. This keeps repaint work bounded and makes the state useful in
//! tests (and for the multi-agent dashboard) without requiring a terminal.

use std::collections::{BTreeMap, VecDeque};
use std::path::Path;

use chrono::{DateTime, Utc};
use serde::Serialize;
use tokio::sync::broadcast;

use crate::events::{Event, FileAccess};

pub const RING_CAP: usize = 1000;
pub const ACTIVITY_CAP: usize = 120;

/// Which event subset is currently visible in a dashboard.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum EventFilter {
    #[default]
    All,
    Blocked,
    Files,
    Network,
    Suspicious,
    Notices,
    Search(String),
}

impl EventFilter {
    pub fn label(&self) -> &str {
        match self {
            Self::All => "all",
            Self::Blocked => "blocked",
            Self::Files => "files",
            Self::Network => "network",
            Self::Suspicious => "suspicious",
            Self::Notices => "notices",
            Self::Search(_) => "search",
        }
    }

    pub fn matches(&self, event: &Event) -> bool {
        match self {
            Self::All => true,
            Self::Blocked => {
                matches!(event, Event::BlockedAttempt { .. })
                    || matches!(event, Event::NetRequest { allowed: false, .. })
            }
            Self::Files => matches!(event, Event::FileObserved { .. }),
            Self::Network => matches!(event, Event::NetRequest { .. }),
            Self::Suspicious => crate::classifier::classify_event(event).is_some(),
            Self::Notices => matches!(event, Event::Notice { .. }),
            Self::Search(query) => {
                let q = query.trim().to_ascii_lowercase();
                q.is_empty() || describe(event).to_ascii_lowercase().contains(&q)
            }
        }
    }
}

/// One bucket of the activity sparkline. Counts are observations, not
/// enforcement decisions; the event model documents that distinction.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct ActivitySample {
    pub at: DateTime<Utc>,
    pub events: u64,
    pub blocked: u64,
    pub network: u64,
    pub suspicious: u64,
}

impl Default for ActivitySample {
    fn default() -> Self {
        Self {
            at: Utc::now(),
            events: 0,
            blocked: 0,
            network: 0,
            suspicious: 0,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
pub struct NetworkSummary {
    pub total: u64,
    pub allowed: u64,
    pub blocked: u64,
}

/// Real-time event counts aggregated across observation & security categories (Feature 37).
#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
pub struct EventCategoryCounters {
    pub file_reads: u64,
    pub file_writes: u64,
    pub files_total: u64,
    pub net_allowed: u64,
    pub net_blocked: u64,
    pub net_total: u64,
    pub blocked_files: u64,
    pub blocked_net: u64,
    pub blocked_total: u64,
    pub procs_exec: u64,
    pub notices: u64,
    pub suspicious: u64,
}

/// Dedicated real-time event aggregator decoupled from TUI rendering for independent testing.
#[derive(Debug, Clone)]
pub struct LiveEventAggregator {
    pub counters: EventCategoryCounters,
    pub recent_events: VecDeque<Event>,
    pub capacity: usize,
}

impl LiveEventAggregator {
    pub fn new(capacity: usize) -> Self {
        Self {
            counters: EventCategoryCounters::default(),
            recent_events: VecDeque::with_capacity(capacity.min(RING_CAP)),
            capacity,
        }
    }

    pub fn ingest(&mut self, event: &Event) {
        if crate::classifier::classify_event(event).is_some() {
            self.counters.suspicious = self.counters.suspicious.saturating_add(1);
        }

        match event {
            Event::FileObserved { access, .. } => {
                self.counters.files_total = self.counters.files_total.saturating_add(1);
                match access {
                    FileAccess::Read => {
                        self.counters.file_reads = self.counters.file_reads.saturating_add(1)
                    }
                    FileAccess::Write => {
                        self.counters.file_writes = self.counters.file_writes.saturating_add(1)
                    }
                    FileAccess::Unknown => {}
                }
            }
            Event::ExecObserved { .. } => {
                self.counters.procs_exec = self.counters.procs_exec.saturating_add(1);
            }
            Event::BlockedAttempt { .. } => {
                self.counters.blocked_files = self.counters.blocked_files.saturating_add(1);
                self.counters.blocked_total = self.counters.blocked_total.saturating_add(1);
            }
            Event::NetRequest { allowed, .. } => {
                self.counters.net_total = self.counters.net_total.saturating_add(1);
                if *allowed {
                    self.counters.net_allowed = self.counters.net_allowed.saturating_add(1);
                } else {
                    self.counters.net_blocked = self.counters.net_blocked.saturating_add(1);
                    self.counters.blocked_net = self.counters.blocked_net.saturating_add(1);
                    self.counters.blocked_total = self.counters.blocked_total.saturating_add(1);
                }
            }
            Event::Notice { .. } => {
                self.counters.notices = self.counters.notices.saturating_add(1);
            }
            Event::DnsResolved { .. } | Event::NetEgress { .. } => {}
            Event::NetQuotaExceeded { .. } => {
                self.counters.blocked_net = self.counters.blocked_net.saturating_add(1);
                self.counters.blocked_total = self.counters.blocked_total.saturating_add(1);
            }
            Event::SecretMasked { .. } => {
                self.counters.files_total = self.counters.files_total.saturating_add(1);
            }
            Event::SessionStarted { .. }
            | Event::SessionTimeout { .. }
            | Event::SessionEnded { .. } => {}
        }

        self.recent_events.push_back(event.clone());
        while self.recent_events.len() > self.capacity {
            self.recent_events.pop_front();
        }
    }

    pub fn recent(&self, limit: usize) -> Vec<&Event> {
        let skip = self.recent_events.len().saturating_sub(limit);
        self.recent_events.iter().skip(skip).collect()
    }
}

pub struct AppState {
    pub tier: String,
    pub net: String,
    pub profile: String,
    pub events: VecDeque<Event>,
    pub aggregator: LiveEventAggregator,
    pub events_total: u64,
    pub blocked: u64,
    pub files: u64,
    pub file_reads: u64,
    pub file_writes: u64,
    pub execs: u64,
    pub net_requests: u64,
    pub notices: u64,
    pub suspicious: u64,
    pub last_line: String,
    pub filter: EventFilter,
    pub selected: usize,
    pub scroll: usize,
    pub paused: bool,
    pub help: bool,
    pub generation: u64,
    pub started_at: Option<DateTime<Utc>>,
    pub ended_at: Option<DateTime<Utc>>,
    pub exit_code: Option<i32>,
    pub file_tree: BTreeMap<String, u64>,
    pub network: NetworkSummary,
    pub network_hosts: BTreeMap<(String, u16, bool), u64>,
    pub activity: VecDeque<ActivitySample>,
}

impl AppState {
    pub fn new(tier: &str, net: &str, profile: &str) -> Self {
        Self {
            tier: tier.to_string(),
            net: net.to_string(),
            profile: profile.to_string(),
            events: VecDeque::with_capacity(64),
            aggregator: LiveEventAggregator::new(RING_CAP),
            events_total: 0,
            blocked: 0,
            files: 0,
            file_reads: 0,
            file_writes: 0,
            execs: 0,
            net_requests: 0,
            notices: 0,
            suspicious: 0,
            last_line: String::new(),
            filter: EventFilter::All,
            selected: 0,
            scroll: 0,
            paused: false,
            help: false,
            generation: 0,
            started_at: None,
            ended_at: None,
            exit_code: None,
            file_tree: BTreeMap::new(),
            network: NetworkSummary::default(),
            network_hosts: BTreeMap::new(),
            activity: VecDeque::with_capacity(ACTIVITY_CAP),
        }
    }

    pub fn ingest(&mut self, ev: Event) {
        self.aggregator.ingest(&ev);
        self.events_total = self.events_total.saturating_add(1);
        let mut sample = ActivitySample {
            at: ev.ts(),
            ..ActivitySample::default()
        };
        if crate::classifier::classify_event(&ev).is_some() {
            self.suspicious = self.suspicious.saturating_add(1);
            sample.suspicious = 1;
        }
        match &ev {
            Event::SessionStarted { ts, .. } => self.started_at = Some(*ts),
            Event::SessionEnded { ts, exit_code, .. } => {
                self.ended_at = Some(*ts);
                self.exit_code = Some(*exit_code);
            }
            Event::FileObserved { path, access, .. } => {
                self.files += 1;
                sample.events = 1;
                let key = file_tree_key(path);
                *self.file_tree.entry(key).or_insert(0) += 1;
                match access {
                    FileAccess::Read => self.file_reads += 1,
                    FileAccess::Write => self.file_writes += 1,
                    FileAccess::Unknown => {}
                }
            }
            Event::ExecObserved { .. } => {
                self.execs += 1;
                sample.events = 1;
            }
            Event::BlockedAttempt { path, .. } => {
                self.blocked += 1;
                sample.events = 1;
                sample.blocked = 1;
                *self.file_tree.entry(file_tree_key(path)).or_insert(0) += 1;
            }
            Event::NetRequest {
                host,
                port,
                allowed,
                ..
            } => {
                self.net_requests += 1;
                self.network.total += 1;
                *self
                    .network_hosts
                    .entry((host.clone(), *port, *allowed))
                    .or_insert(0) += 1;
                if *allowed {
                    self.network.allowed += 1;
                } else {
                    self.network.blocked += 1;
                }
                sample.events = 1;
                sample.network = 1;
            }
            Event::Notice { .. } => {
                self.notices += 1;
                sample.events = 1;
            }
            Event::SecretMasked { path, .. } => {
                *self.file_tree.entry(file_tree_key(path)).or_insert(0) += 1;
                sample.events = 1;
            }
            // Session-level marker like start/end: it lands in the event ring
            // via describe() below but drives no counters or samples.
            Event::SessionTimeout { .. } => {}
            Event::DnsResolved { .. } => {}
            Event::NetEgress { .. } => {}
            Event::NetQuotaExceeded { .. } => {}
        }
        self.last_line = describe(&ev);
        self.events.push_back(ev);
        while self.events.len() > RING_CAP {
            self.events.pop_front();
        }
        if sample.events > 0 {
            push_activity(&mut self.activity, sample);
        }
        self.selected = self.selected.min(self.filtered_len().saturating_sub(1));
        self.generation = self.generation.wrapping_add(1);
    }

    /// Pull everything currently queued on the bus into the ring.
    pub fn drain(&mut self, rx: &mut broadcast::Receiver<Event>) {
        loop {
            match rx.try_recv() {
                Ok(ev) => self.ingest(ev),
                Err(broadcast::error::TryRecvError::Empty)
                | Err(broadcast::error::TryRecvError::Closed) => break,
                Err(broadcast::error::TryRecvError::Lagged(_)) => {
                    self.generation = self.generation.wrapping_add(1);
                    continue;
                }
            }
        }
    }

    pub fn set_filter(&mut self, filter: EventFilter) {
        self.filter = filter;
        self.selected = 0;
        self.scroll = 0;
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn toggle_pause(&mut self) {
        self.paused = !self.paused;
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn toggle_help(&mut self) {
        self.help = !self.help;
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn filtered_events(&self) -> Vec<&Event> {
        self.events
            .iter()
            .filter(|event| self.filter.matches(event))
            .collect()
    }

    pub fn filtered_len(&self) -> usize {
        self.events
            .iter()
            .filter(|event| self.filter.matches(event))
            .count()
    }

    pub fn move_selection(&mut self, delta: isize) {
        let len = self.filtered_len();
        if len == 0 {
            self.selected = 0;
            return;
        }
        let next = if delta.is_negative() {
            self.selected.saturating_sub(delta.unsigned_abs())
        } else {
            self.selected.saturating_add(delta as usize)
        };
        self.selected = next.min(len - 1);
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn scroll_by(&mut self, delta: isize) {
        if delta.is_negative() {
            self.scroll = self.scroll.saturating_sub(delta.unsigned_abs());
        } else {
            self.scroll = self.scroll.saturating_add(delta as usize);
        }
        self.generation = self.generation.wrapping_add(1);
    }

    /// Export the bounded event ring as JSONL. The operation is explicit and
    /// synchronous so a failed write is shown to the user instead of being
    /// silently lost in a background task.
    pub fn export_events(&self, path: &Path) -> std::io::Result<usize> {
        let mut text = String::new();
        for event in &self.events {
            let mut value = serde_json::to_value(event).map_err(std::io::Error::other)?;
            crate::report::sanitize_json_strings(&mut value);
            let line = serde_json::to_string(&value).map_err(std::io::Error::other)?;
            text.push_str(&line);
            text.push('\n');
        }
        crate::report::write_new_report(path, &text)?;
        Ok(self.events.len())
    }

    /// One compact statusline cell: badges + counters + last event.
    pub fn status_text(&self, cols: u16) -> String {
        let state = if self.paused { "paused" } else { "live" };
        let head = format!(
            " vetto [{state}] [tier={}] [net={}] blocked={} suspicious={} files={} exec={} ",
            self.tier, self.net, self.blocked, self.suspicious, self.files, self.execs
        );
        let budget = cols as usize;
        if budget == 0 {
            return String::new();
        }
        if head.len() >= budget.saturating_sub(1) {
            truncate_chars(&head, budget)
        } else {
            let tail_budget = budget - head.len() - 1;
            format!("{head}| {}", truncate_chars(&self.last_line, tail_budget))
        }
    }
}

fn push_activity(activity: &mut VecDeque<ActivitySample>, sample: ActivitySample) {
    // Events arriving in the same second share one bucket. This makes the
    // graph stable at the 4–5fps repaint cap and avoids a timer-driven UI.
    if let Some(last) = activity.back_mut() {
        if last.at.timestamp() == sample.at.timestamp() {
            last.events += sample.events;
            last.blocked += sample.blocked;
            last.network += sample.network;
            last.suspicious += sample.suspicious;
            return;
        }
    }
    activity.push_back(sample);
    while activity.len() > ACTIVITY_CAP {
        activity.pop_front();
    }
}

fn file_tree_key(path: &str) -> String {
    let path = Path::new(path);
    let mut parts = path.components();
    let Some(first) = parts.next() else {
        return "/".to_string();
    };
    let mut key = first.as_os_str().to_string_lossy().into_owned();
    if let Some(second) = parts.next() {
        key.push(std::path::MAIN_SEPARATOR);
        key.push_str(&second.as_os_str().to_string_lossy());
    }
    key
}

pub fn truncate_chars(s: &str, max_chars: usize) -> String {
    if max_chars == 0 {
        return String::new();
    }
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let mut out: String = s.chars().take(max_chars.saturating_sub(1)).collect();
    out.push('…');
    out
}

/// Short one-line rendering of an event for statusline/overlay.
pub fn describe(ev: &Event) -> String {
    let t = ev.ts().format("%H:%M:%S");
    match ev {
        Event::SessionStarted { pid, .. } => {
            format!("[{t}] session started (agent subtree root {pid})")
        }
        Event::SessionEnded { exit_code, .. } => format!("[{t}] session ended (exit {exit_code})"),
        Event::FileObserved {
            comm, path, access, ..
        } => {
            let a = match access {
                FileAccess::Read => "read",
                FileAccess::Write => "write",
                FileAccess::Unknown => "open",
            };
            format!("[{t}] {comm} {a} {path}")
        }
        Event::ExecObserved { argv, .. } => {
            format!(
                "[{t}] exec {}",
                argv.first().map(String::as_str).unwrap_or("?")
            )
        }
        Event::BlockedAttempt {
            comm, path, source, ..
        } => format!(
            "[{t}] BLOCKED [{source}] {comm} -> {path} (to allow: add `read = \"{path}\"` (or net domain) to policy.toml)"
        ),
        Event::NetRequest {
            host,
            port,
            allowed,
            ..
        } => {
            if *allowed {
                format!("[{t}] net allow {host}:{port}")
            } else {
                format!(
                    "[{t}] net DENY {host}:{port} (to allow: add `allow = [\"{host}\"]` (or net domain) to policy.toml)"
                )
            }
        }
        Event::SecretMasked { path, .. } => format!("[{t}] secret masked: {path}"),
        Event::Notice { message, .. } => format!("[{t}] {message}"),
        Event::SessionTimeout { .. } => format!("[{t}] session timeout: sandbox torn down"),
        Event::DnsResolved { host, ips, .. } => {
            format!("[{t}] dns {host} -> {}", ips.join(","))
        }
        Event::NetEgress {
            host,
            bytes_tx,
            bytes_rx,
            ..
        } => {
            format!("[{t}] net {host} (tx: {bytes_tx}B, rx: {bytes_rx}B)")
        }
        Event::NetQuotaExceeded {
            host, limit_bytes, ..
        } => {
            format!("[{t}] quota exceeded: {host} (limit {limit_bytes}B)")
        }
    }
}

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

    fn blocked(path: &str) -> Event {
        Event::BlockedAttempt {
            ts: Utc::now(),
            pid: 1,
            comm: "agent".into(),
            path: path.into(),
            source: "test".into(),
        }
    }

    #[test]
    fn filtering_and_navigation_are_deterministic() {
        let mut state = AppState::new("full", "off", "default");
        state.ingest(blocked("/tmp/a"));
        state.ingest(Event::Notice {
            ts: Utc::now(),
            message: "hello".into(),
        });
        state.set_filter(EventFilter::Blocked);
        assert_eq!(state.filtered_len(), 1);
        state.move_selection(1);
        assert_eq!(state.selected, 0);
    }

    #[test]
    fn export_contains_only_the_bounded_ring() {
        let mut state = AppState::new("full", "off", "default");
        state.ingest(blocked("/tmp/a"));
        let temp =
            std::fs::canonicalize(std::env::temp_dir()).expect("canonical temporary directory");
        let path = temp.join(format!("vetto-tui-{}.jsonl", std::process::id()));
        let count = state.export_events(&path).expect("export");
        assert_eq!(count, 1);
        let text = std::fs::read_to_string(&path).expect("read export");
        assert!(text.contains("blocked_attempt"));
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn export_redacts_user_strings_and_keeps_json_lines_valid() {
        let secret = "ghp_0123456789abcdefghijklmnopqrstuvwxyz";
        let mut state = AppState::new("full", "off", "default");
        state.ingest(Event::Notice {
            ts: Utc::now(),
            message: format!("token={secret}"),
        });
        let temp =
            std::fs::canonicalize(std::env::temp_dir()).expect("canonical temporary directory");
        let path = temp.join(format!(
            "vetto-tui-secret-{}-{}.jsonl",
            std::process::id(),
            Utc::now().timestamp_nanos_opt().unwrap_or_default()
        ));
        state.export_events(&path).expect("export");
        let text = std::fs::read_to_string(&path).expect("read export");
        assert!(!text.contains(secret), "secret leaked: {text}");
        assert!(text
            .lines()
            .all(|line| serde_json::from_str::<serde_json::Value>(line).is_ok()));
        let _ = std::fs::remove_file(path);
    }

    #[cfg(unix)]
    #[test]
    fn export_refuses_symlinked_parent() {
        use std::os::unix::fs::symlink;

        let suffix = format!(
            "{}-{}",
            std::process::id(),
            Utc::now().timestamp_nanos_opt().unwrap_or_default()
        );
        let temp =
            std::fs::canonicalize(std::env::temp_dir()).expect("canonical temporary directory");
        let real = temp.join(format!("vetto-tui-real-{suffix}"));
        let link = temp.join(format!("vetto-tui-link-{suffix}"));
        std::fs::create_dir(&real).expect("create real export directory");
        symlink(&real, &link).expect("create export symlink");

        let mut state = AppState::new("full", "off", "default");
        state.ingest(blocked("/tmp/a"));
        let path = link.join("events.jsonl");
        assert!(state.export_events(&path).is_err());
        assert!(!real.join("events.jsonl").exists());

        std::fs::remove_file(&link).expect("remove export symlink");
        std::fs::remove_dir(&real).expect("remove real export directory");
    }

    #[test]
    fn live_aggregator_tracks_typed_counters_and_bounds_recent_events() {
        let mut agg = LiveEventAggregator::new(5);
        assert_eq!(agg.counters.files_total, 0);

        agg.ingest(&Event::FileObserved {
            ts: Utc::now(),
            pid: 10,
            comm: "cargo".into(),
            path: "/tmp/src/lib.rs".into(),
            access: FileAccess::Read,
        });
        agg.ingest(&Event::FileObserved {
            ts: Utc::now(),
            pid: 10,
            comm: "cargo".into(),
            path: "/tmp/src/main.rs".into(),
            access: FileAccess::Write,
        });
        agg.ingest(&Event::NetRequest {
            ts: Utc::now(),
            host: "crates.io".into(),
            port: 443,
            allowed: true,
        });
        agg.ingest(&Event::NetRequest {
            ts: Utc::now(),
            host: "evil.com".into(),
            port: 443,
            allowed: false,
        });
        agg.ingest(&blocked("/etc/shadow"));
        agg.ingest(&Event::ExecObserved {
            ts: Utc::now(),
            pid: 11,
            argv: vec!["rustc".into(), "main.rs".into()],
        });

        let counters = agg.counters;
        assert_eq!(counters.file_reads, 1);
        assert_eq!(counters.file_writes, 1);
        assert_eq!(counters.files_total, 2);
        assert_eq!(counters.net_allowed, 1);
        assert_eq!(counters.net_blocked, 1);
        assert_eq!(counters.net_total, 2);
        assert_eq!(counters.blocked_files, 1);
        assert_eq!(counters.blocked_net, 1);
        assert_eq!(counters.blocked_total, 2);
        assert_eq!(counters.procs_exec, 1);

        // Ring buffer bounds to capacity 5
        assert_eq!(agg.recent_events.len(), 5);
        assert_eq!(agg.recent(3).len(), 3);
    }
}