Skip to main content

omega_cognitive_kernel/
audit.rs

1//! Append-only audit log (S3 hardening).
2//!
3//! `AuditEvent` is the kernel's public event stream. Prefer the alias
4//! [`KernelEvent`] at the crate root when wiring integrators.
5
6#[allow(unused_imports)]
7use crate::prelude::*;
8
9use crate::error::{OmegaError, Result};
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use std::fs::{self, OpenOptions};
13use std::io::{Read, Seek, SeekFrom, Write};
14use std::path::{Path, PathBuf};
15use uuid::Uuid;
16
17/// Public event stream for integrators (same shape as [`AuditEvent`]).
18pub type KernelEvent = AuditEvent;
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21#[serde(tag = "kind", rename_all = "snake_case")]
22pub enum AuditEvent {
23    Step {
24        step: u64,
25        goal: String,
26        action: String,
27        avg_err: f64,
28        damping: f64,
29    },
30    PatchAccepted {
31        step: u64,
32        patch_id: Uuid,
33        damping: f64,
34        description: String,
35    },
36    PatchRejected {
37        step: u64,
38        reason: String,
39    },
40    Checkpoint {
41        checkpoint_id: Uuid,
42        step: u64,
43        label: String,
44    },
45    Rollback {
46        checkpoint_id: Uuid,
47        step_before: u64,
48    },
49    TaskEpisode {
50        task: String,
51        reward: f64,
52        steps: u32,
53    },
54    /// Tool-call gate: proposed tool was on allow-list and recorded.
55    ToolAllowed {
56        tool: String,
57    },
58    /// Tool-call gate: proposed tool blocked (deny-list or not allowed).
59    ToolDenied {
60        tool: String,
61        reason: String,
62    },
63    /// L2 entered the fixed-point regime.
64    FixedPointEntered {
65        step: u64,
66        alignment_score: f64,
67    },
68    /// L2 exited the fixed-point regime.
69    FixedPointExited {
70        step: u64,
71        alignment_score: f64,
72        dwell_steps: u64,
73    },
74    L2ModulationProposed {
75        step: u64,
76        score: f64,
77    },
78    L2ModulationCommitted {
79        step: u64,
80        score: f64,
81        gain: f64,
82    },
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuditRecord {
87    pub ts: DateTime<Utc>,
88    pub event: AuditEvent,
89}
90
91/// Operator-facing rollup of an audit.jsonl file.
92#[derive(Debug, Clone, Default, Serialize)]
93pub struct AuditSummary {
94    pub total_events: usize,
95    pub steps: usize,
96    pub patches_accepted: usize,
97    pub patches_rejected: usize,
98    pub checkpoints: usize,
99    pub rollbacks: usize,
100    pub task_episodes: usize,
101    pub tools_allowed: usize,
102    pub tools_denied: usize,
103    pub fixed_point_enters: usize,
104    pub fixed_point_exits: usize,
105    pub l2_modulation_proposals: usize,
106    pub l2_modulation_commits: usize,
107    pub first_ts: Option<DateTime<Utc>>,
108    pub last_ts: Option<DateTime<Utc>>,
109    pub last_action: Option<String>,
110    pub last_avg_err: Option<f64>,
111    pub last_damping: Option<f64>,
112    pub action_counts: Vec<(String, usize)>,
113}
114
115impl AuditSummary {
116    pub fn from_records(rows: &[AuditRecord]) -> Self {
117        use hashbrown::HashMap;
118        let mut s = AuditSummary {
119            total_events: rows.len(),
120            ..AuditSummary::default()
121        };
122        let mut actions: HashMap<String, usize> = HashMap::new();
123        if let Some(first) = rows.first() {
124            s.first_ts = Some(first.ts);
125        }
126        if let Some(last) = rows.last() {
127            s.last_ts = Some(last.ts);
128        }
129        for r in rows {
130            match &r.event {
131                AuditEvent::Step {
132                    action,
133                    avg_err,
134                    damping,
135                    ..
136                } => {
137                    s.steps += 1;
138                    *actions.entry(action.clone()).or_insert(0) += 1;
139                    s.last_action = Some(action.clone());
140                    s.last_avg_err = Some(*avg_err);
141                    s.last_damping = Some(*damping);
142                }
143                AuditEvent::PatchAccepted { .. } => s.patches_accepted += 1,
144                AuditEvent::PatchRejected { .. } => s.patches_rejected += 1,
145                AuditEvent::Checkpoint { .. } => s.checkpoints += 1,
146                AuditEvent::Rollback { .. } => s.rollbacks += 1,
147                AuditEvent::TaskEpisode { .. } => s.task_episodes += 1,
148                AuditEvent::ToolAllowed { tool } => {
149                    s.tools_allowed += 1;
150                    *actions.entry(format!("tool:{tool}")).or_insert(0) += 1;
151                }
152                AuditEvent::ToolDenied { tool, .. } => {
153                    s.tools_denied += 1;
154                    *actions.entry(format!("deny:{tool}")).or_insert(0) += 1;
155                }
156                AuditEvent::FixedPointEntered { .. } => s.fixed_point_enters += 1,
157                AuditEvent::FixedPointExited { .. } => s.fixed_point_exits += 1,
158                AuditEvent::L2ModulationProposed { .. } => s.l2_modulation_proposals += 1,
159                AuditEvent::L2ModulationCommitted { .. } => s.l2_modulation_commits += 1,
160            }
161        }
162        let mut counts: Vec<_> = actions.into_iter().collect();
163        counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
164        s.action_counts = counts;
165        s
166    }
167}
168
169pub struct AuditLog {
170    pub path: PathBuf,
171}
172
173impl AuditLog {
174    pub fn beside_state(state_path: &Path) -> Self {
175        let path = state_path
176            .parent()
177            .unwrap_or_else(|| Path::new("."))
178            .join("audit.jsonl");
179        Self { path }
180    }
181
182    pub fn append(&self, event: AuditEvent) -> Result<()> {
183        if let Some(parent) = self.path.parent() {
184            fs::create_dir_all(parent).map_err(|e| OmegaError::Persist(e.to_string()))?;
185        }
186        let rec = AuditRecord {
187            ts: crate::now_utc(),
188            event,
189        };
190        let line = serde_json::to_string(&rec).map_err(|e| OmegaError::Persist(e.to_string()))?;
191        let mut f = OpenOptions::new()
192            .create(true)
193            .append(true)
194            .open(&self.path)
195            .map_err(|e| OmegaError::Persist(e.to_string()))?;
196        writeln!(f, "{line}").map_err(|e| OmegaError::Persist(e.to_string()))?;
197        Ok(())
198    }
199
200    pub fn tail(&self, n: usize) -> Result<Vec<AuditRecord>> {
201        let mut rows = self.read_all()?;
202        if rows.len() > n {
203            rows = rows.split_off(rows.len() - n);
204        }
205        Ok(rows)
206    }
207
208    pub fn read_all(&self) -> Result<Vec<AuditRecord>> {
209        if !self.path.exists() {
210            return Ok(vec![]);
211        }
212        let data =
213            fs::read_to_string(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
214        let rows: Vec<AuditRecord> = data
215            .lines()
216            .filter(|l| !l.trim().is_empty())
217            .filter_map(|l| serde_json::from_str(l).ok())
218            .collect();
219        Ok(rows)
220    }
221
222    /// Current file length in bytes (0 if missing). Use as the cursor for [`poll_after`].
223    pub fn byte_len(&self) -> Result<u64> {
224        if !self.path.exists() {
225            return Ok(0);
226        }
227        let meta = fs::metadata(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
228        Ok(meta.len())
229    }
230
231    /// Read complete JSONL records written after `offset` bytes.
232    ///
233    /// Returns `(new_records, new_offset)`. Incomplete trailing lines are left
234    /// for a later poll (offset does not advance past them).
235    pub fn poll_after(&self, offset: u64) -> Result<(Vec<AuditRecord>, u64)> {
236        if !self.path.exists() {
237            return Ok((vec![], 0));
238        }
239        let mut f = fs::File::open(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
240        let len = f
241            .metadata()
242            .map_err(|e| OmegaError::Persist(e.to_string()))?
243            .len();
244        if offset > len {
245            // File was truncated/rotated — resync from start.
246            return self.poll_after(0);
247        }
248        f.seek(SeekFrom::Start(offset))
249            .map_err(|e| OmegaError::Persist(e.to_string()))?;
250        let mut buf = String::new();
251        f.read_to_string(&mut buf)
252            .map_err(|e| OmegaError::Persist(e.to_string()))?;
253
254        let mut rows = Vec::new();
255        let mut consumed = 0usize;
256        for line in buf.split_inclusive('\n') {
257            let trimmed = line.trim_end_matches(['\r', '\n']);
258            if trimmed.is_empty() {
259                consumed += line.len();
260                continue;
261            }
262            // Incomplete last line (no newline yet) — wait for more bytes.
263            if !line.ends_with('\n') {
264                break;
265            }
266            if let Ok(rec) = serde_json::from_str::<AuditRecord>(trimmed) {
267                rows.push(rec);
268            }
269            consumed += line.len();
270        }
271        let new_offset = offset + consumed as u64;
272        Ok((rows, new_offset))
273    }
274
275    pub fn summarize(&self) -> Result<AuditSummary> {
276        let rows = self.read_all()?;
277        Ok(AuditSummary::from_records(&rows))
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use std::env::temp_dir;
285
286    #[test]
287    fn append_and_tail() {
288        let path = temp_dir().join(format!("omega-audit-{}.jsonl", crate::new_uuid()));
289        let log = AuditLog { path: path.clone() };
290        log.append(AuditEvent::Step {
291            step: 1,
292            goal: "g".into(),
293            action: "observe".into(),
294            avg_err: 0.5,
295            damping: 1.0,
296        })
297        .unwrap();
298        let rows = log.tail(10).unwrap();
299        assert_eq!(rows.len(), 1);
300        let sum = log.summarize().unwrap();
301        assert_eq!(sum.steps, 1);
302        assert_eq!(sum.action_counts[0].0, "observe");
303        let _ = fs::remove_file(&path);
304    }
305
306    #[test]
307    fn poll_after_reads_only_new_lines() {
308        let path = temp_dir().join(format!("omega-poll-{}.jsonl", crate::new_uuid()));
309        let log = AuditLog { path: path.clone() };
310        log.append(AuditEvent::Step {
311            step: 1,
312            goal: "g".into(),
313            action: "explore".into(),
314            avg_err: 0.4,
315            damping: 1.0,
316        })
317        .unwrap();
318        let (first, off) = log.poll_after(0).unwrap();
319        assert_eq!(first.len(), 1);
320        assert!(off > 0);
321
322        let (none, off2) = log.poll_after(off).unwrap();
323        assert!(none.is_empty());
324        assert_eq!(off2, off);
325
326        log.append(AuditEvent::PatchAccepted {
327            step: 2,
328            patch_id: Uuid::nil(),
329            damping: 0.8,
330            description: "t".into(),
331        })
332        .unwrap();
333        let (second, off3) = log.poll_after(off).unwrap();
334        assert_eq!(second.len(), 1);
335        assert!(matches!(second[0].event, AuditEvent::PatchAccepted { .. }));
336        assert!(off3 > off);
337
338        let _ = fs::remove_file(&path);
339    }
340}