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 serde::{Deserialize, Serialize};
11use std::fs;
12use std::io::{Read, Seek, SeekFrom, Write};
13use std::path::{Path, PathBuf};
14use uuid::Uuid;
15
16/// Maximum bytes retained while reading one audit log.
17pub const MAX_AUDIT_READ_BYTES: u64 = 64 * 1024 * 1024;
18/// Maximum serialized JSONL record size (excluding its newline).
19pub const MAX_AUDIT_LINE_BYTES: usize = 1024 * 1024;
20/// Maximum records returned by a single audit read.
21pub const MAX_AUDIT_EVENTS: usize = 1_000_000;
22
23/// Public event stream for integrators (same shape as [`AuditEvent`]).
24pub type KernelEvent = AuditEvent;
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27#[serde(tag = "kind", rename_all = "snake_case")]
28#[non_exhaustive]
29/// Typed event emitted by the kernel and persisted in its append-only audit log.
30pub enum AuditEvent {
31    /// A kernel step completed.
32    Step {
33        /// Kernel step number associated with the event.
34        step: u64,
35        /// Goal submitted for the step.
36        goal: String,
37        /// Action selected or produced by the kernel.
38        action: String,
39        /// Average prediction error reported for the step.
40        avg_err: f64,
41        /// Prediction-error damping factor used for the step.
42        damping: f64,
43    },
44    /// A proposed patch passed validation and was accepted.
45    PatchAccepted {
46        /// Kernel step number associated with the patch.
47        step: u64,
48        /// Unique identifier assigned to the accepted patch.
49        patch_id: Uuid,
50        /// Prediction-error damping factor used for the step.
51        damping: f64,
52        /// Human-readable summary of the accepted change.
53        description: String,
54    },
55    /// A proposed patch was rejected and not applied.
56    PatchRejected {
57        /// Kernel step number associated with the proposal.
58        step: u64,
59        /// Explanation for rejecting the patch.
60        reason: String,
61    },
62    /// A kernel snapshot was saved as a checkpoint.
63    Checkpoint {
64        /// Identifier for the checkpoint.
65        checkpoint_id: Uuid,
66        /// Kernel step captured by the checkpoint.
67        step: u64,
68        /// Human-readable label for the checkpoint.
69        label: String,
70    },
71    /// Kernel state was restored from a checkpoint.
72    Rollback {
73        /// Identifier for the checkpoint.
74        checkpoint_id: Uuid,
75        /// Kernel step number before the restore.
76        step_before: u64,
77    },
78    /// A task episode completed and its reward was recorded.
79    TaskEpisode {
80        /// Name or description of the completed task.
81        task: String,
82        /// Reward observed for the episode.
83        reward: f64,
84        /// Number of steps used by the episode.
85        steps: u32,
86    },
87    /// Tool-call gate: proposed tool was on allow-list and recorded.
88    ToolAllowed {
89        /// Name of the tool admitted by the gate.
90        tool: String,
91    },
92    /// Tool-call gate: proposed tool blocked (deny-list or not allowed).
93    ToolDenied {
94        /// Name of the tool rejected by the gate.
95        tool: String,
96        /// Explanation for denying the tool call.
97        reason: String,
98    },
99    /// L2 entered the fixed-point regime.
100    FixedPointEntered {
101        /// Kernel step at which L2 entered the regime.
102        step: u64,
103        /// Alignment score measured at entry.
104        alignment_score: f64,
105    },
106    /// L2 exited the fixed-point regime.
107    FixedPointExited {
108        /// Kernel step at which L2 exited the regime.
109        step: u64,
110        /// Alignment score measured at exit.
111        alignment_score: f64,
112        /// Number of steps spent in the current regime or arm.
113        dwell_steps: u64,
114    },
115    /// L2 proposed a policy modulation.
116    L2ModulationProposed {
117        /// Kernel step associated with the proposal.
118        step: u64,
119        /// Score assigned to the proposal.
120        score: f64,
121    },
122    /// L2 committed a proposed policy modulation.
123    L2ModulationCommitted {
124        /// Kernel step at which the modulation was committed.
125        step: u64,
126        /// Score assigned to the committed modulation.
127        score: f64,
128        /// Gain applied when committing the modulation.
129        gain: f64,
130    },
131    /// Telemetry for a step executed by an external host was processed.
132    ExternalStep {
133        /// Identifier of the step represented by this value.
134        step_id: u64,
135        /// Prediction error measured for this step.
136        prediction_error: f64,
137        /// Risk observed while executing this step.
138        observed_risk: f64,
139        /// L1 gate decision returned to the host.
140        l1_gate: String,
141        /// Whether the host was instructed to keep its current policy.
142        keep_steady: bool,
143        #[serde(default, skip_serializing_if = "Option::is_none")]
144        /// Identifier of the patch proposed for this step, if any.
145        patch_id: Option<String>,
146    },
147    /// The host was instructed to restore a checkpoint after a degraded step.
148    ExternalRollback {
149        /// Identifier of the step represented by this value.
150        step_id: u64,
151        /// Identifier for the checkpoint.
152        checkpoint_id: String,
153        /// Number of consecutive rollbacks at this point.
154        consecutive_rollbacks: u32,
155        /// Remaining cooldown steps before another patch may be considered.
156        next_cooldown: u64,
157    },
158    /// A duplicate or out-of-order external step identifier was ignored.
159    ExternalStepDuplicate {
160        /// Identifier of the step represented by this value.
161        step_id: u64,
162        /// Most recent external step identifier already processed.
163        last_step_id: u64,
164    },
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
168/// Timestamped event stored in the append-only audit log.
169pub struct AuditRecord {
170    /// UTC timestamp when the event was recorded.
171    pub ts: crate::UtcTimestamp,
172    /// Audit event recorded at this timestamp.
173    pub event: AuditEvent,
174}
175
176/// Operator-facing rollup of an audit.jsonl file.
177#[derive(Debug, Clone, Default, Serialize)]
178pub struct AuditSummary {
179    /// Total number of audit records summarized.
180    pub total_events: usize,
181    /// Number of steps completed by the run.
182    pub steps: usize,
183    /// Number of patches accepted during the run.
184    pub patches_accepted: usize,
185    /// Number of rejected patches.
186    pub patches_rejected: usize,
187    /// Number of checkpoint events.
188    pub checkpoints: usize,
189    /// Number of rollback events.
190    pub rollbacks: usize,
191    /// Number of completed task episodes.
192    pub task_episodes: usize,
193    /// Number of tool calls allowed by the gate.
194    pub tools_allowed: usize,
195    /// Number of tool calls denied by the gate.
196    pub tools_denied: usize,
197    /// Number of entries into the L2 fixed-point regime.
198    pub fixed_point_enters: usize,
199    /// Number of exits from the L2 fixed-point regime.
200    pub fixed_point_exits: usize,
201    /// Number of L2 modulation proposals.
202    pub l2_modulation_proposals: usize,
203    /// Number of L2 modulation commits.
204    pub l2_modulation_commits: usize,
205    /// Timestamp of the first record, if the input was non-empty.
206    pub first_ts: Option<crate::UtcTimestamp>,
207    /// Timestamp of the last record, if the input was non-empty.
208    pub last_ts: Option<crate::UtcTimestamp>,
209    /// Most recent action.
210    pub last_action: Option<String>,
211    /// Most recent average error.
212    pub last_avg_err: Option<f64>,
213    /// Most recent damping.
214    pub last_damping: Option<f64>,
215    /// Action names paired with their occurrence counts.
216    pub action_counts: Vec<(String, usize)>,
217}
218
219impl AuditSummary {
220    /// Builds an operator-facing summary from audit records in input order.
221    pub fn from_records(rows: &[AuditRecord]) -> Self {
222        use hashbrown::HashMap;
223        let mut s = AuditSummary {
224            total_events: rows.len(),
225            ..AuditSummary::default()
226        };
227        let mut actions: HashMap<String, usize> = HashMap::new();
228        if let Some(first) = rows.first() {
229            s.first_ts = Some(first.ts);
230        }
231        if let Some(last) = rows.last() {
232            s.last_ts = Some(last.ts);
233        }
234        for r in rows {
235            match &r.event {
236                AuditEvent::Step {
237                    action,
238                    avg_err,
239                    damping,
240                    ..
241                } => {
242                    s.steps += 1;
243                    *actions.entry(action.clone()).or_insert(0) += 1;
244                    s.last_action = Some(action.clone());
245                    s.last_avg_err = Some(*avg_err);
246                    s.last_damping = Some(*damping);
247                }
248                AuditEvent::PatchAccepted { .. } => s.patches_accepted += 1,
249                AuditEvent::PatchRejected { .. } => s.patches_rejected += 1,
250                AuditEvent::Checkpoint { .. } => s.checkpoints += 1,
251                AuditEvent::Rollback { .. } => s.rollbacks += 1,
252                AuditEvent::TaskEpisode { .. } => s.task_episodes += 1,
253                AuditEvent::ToolAllowed { tool } => {
254                    s.tools_allowed += 1;
255                    *actions.entry(format!("tool:{tool}")).or_insert(0) += 1;
256                }
257                AuditEvent::ToolDenied { tool, .. } => {
258                    s.tools_denied += 1;
259                    *actions.entry(format!("deny:{tool}")).or_insert(0) += 1;
260                }
261                AuditEvent::FixedPointEntered { .. } => s.fixed_point_enters += 1,
262                AuditEvent::FixedPointExited { .. } => s.fixed_point_exits += 1,
263                AuditEvent::L2ModulationProposed { .. } => s.l2_modulation_proposals += 1,
264                AuditEvent::L2ModulationCommitted { .. } => s.l2_modulation_commits += 1,
265                AuditEvent::ExternalStep { .. } => s.steps += 1,
266                AuditEvent::ExternalRollback { .. } => s.rollbacks += 1,
267                AuditEvent::ExternalStepDuplicate { .. } => {}
268            }
269        }
270        let mut counts: Vec<_> = actions.into_iter().collect();
271        counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
272        s.action_counts = counts;
273        s
274    }
275}
276
277/// Data structure representing audit log.
278pub struct AuditLog {
279    /// Path for this value.
280    pub path: PathBuf,
281}
282
283/// Default maximum size for an audit JSONL file (64 MiB).
284///
285/// Existing files larger than this remain readable; only new appends are
286/// limited. Integrators can choose a different ceiling per append.
287pub const DEFAULT_MAX_AUDIT_BYTES: u64 = 64 * 1024 * 1024;
288
289struct AuditAppendLock {
290    #[cfg(any(unix, windows))]
291    _file: fs::File,
292}
293
294impl AuditAppendLock {
295    fn acquire(path: &Path) -> Result<Self> {
296        #[cfg(any(unix, windows))]
297        {
298            use fs2::FileExt;
299
300            let file = crate::private_fs::open_options()
301                .read(true)
302                .write(true)
303                .create(true)
304                .open(path)
305                .map_err(|error| {
306                    OmegaError::Persist(format!("audit lock open {}: {error}", path.display()))
307                })?;
308            file.lock_exclusive().map_err(|error| {
309                OmegaError::Persist(format!("audit lock acquire {}: {error}", path.display()))
310            })?;
311            Ok(Self { _file: file })
312        }
313        #[cfg(not(any(unix, windows)))]
314        {
315            // These targets do not support the crate's advisory file locks;
316            // single-writer audit usage remains supported there.
317            let _ = path;
318            Ok(Self {})
319        }
320    }
321}
322
323fn audit_lock_path(path: &Path) -> PathBuf {
324    let mut lock_path = path.as_os_str().to_os_string();
325    lock_path.push(".lock");
326    PathBuf::from(lock_path)
327}
328
329impl AuditLog {
330    fn malformed_record(&self, line: usize, offset: u64, error: serde_json::Error) -> OmegaError {
331        OmegaError::Persist(format!(
332            "malformed audit record in {} at line {line}, byte offset {offset}: {error}",
333            self.path.display()
334        ))
335    }
336
337    /// Performs beside state for this type.
338    pub fn beside_state(state_path: &Path) -> Self {
339        let path = state_path
340            .parent()
341            .unwrap_or_else(|| Path::new("."))
342            .join("audit.jsonl");
343        Self { path }
344    }
345
346    /// Performs append for this type.
347    pub fn append(&self, event: AuditEvent) -> Result<()> {
348        self.append_with_max_bytes(event, DEFAULT_MAX_AUDIT_BYTES)
349    }
350
351    /// Append an event with an explicit maximum audit-file size in bytes.
352    ///
353    /// The check and append are serialized across cooperating local writers.
354    /// A zero limit rejects every record; use `u64::MAX` for an effectively
355    /// unlimited file. Existing bytes are never truncated or rotated.
356    pub fn append_with_max_bytes(&self, event: AuditEvent, max_bytes: u64) -> Result<()> {
357        self.append_with_privacy_and_max_bytes(event, false, max_bytes)
358    }
359
360    /// Append an event, optionally replacing user-provided text fields before serialization.
361    pub fn append_with_privacy(&self, event: AuditEvent, redact_user_content: bool) -> Result<()> {
362        self.append_with_privacy_and_max_bytes(event, redact_user_content, DEFAULT_MAX_AUDIT_BYTES)
363    }
364
365    /// Append an event with privacy redaction and an explicit maximum file size.
366    pub fn append_with_privacy_and_max_bytes(
367        &self,
368        mut event: AuditEvent,
369        redact_user_content: bool,
370        max_bytes: u64,
371    ) -> Result<()> {
372        if redact_user_content {
373            match &mut event {
374                AuditEvent::Step { goal, .. } => *goal = "[REDACTED]".into(),
375                AuditEvent::Checkpoint { label, .. } => *label = "[REDACTED]".into(),
376                AuditEvent::TaskEpisode { task, .. } => *task = "[REDACTED]".into(),
377                _ => {}
378            }
379        }
380        if let Some(parent) = self.path.parent() {
381            crate::private_fs::create_dir_all(parent)
382                .map_err(|e| OmegaError::Persist(e.to_string()))?;
383        }
384        let _lock = AuditAppendLock::acquire(&audit_lock_path(&self.path))?;
385
386        let rec = AuditRecord {
387            ts: crate::now_utc(),
388            event,
389        };
390        let mut line =
391            serde_json::to_string(&rec).map_err(|e| OmegaError::Persist(e.to_string()))?;
392        line.push('\n');
393
394        let current_len = match fs::metadata(&self.path) {
395            Ok(metadata) => metadata.len(),
396            Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
397            Err(error) => return Err(OmegaError::Persist(error.to_string())),
398        };
399        let record_len = u64::try_from(line.len())
400            .map_err(|error| OmegaError::Persist(format!("audit record size: {error}")))?;
401        let resulting_len = current_len.checked_add(record_len);
402        if !matches!(resulting_len, Some(size) if size <= max_bytes) {
403            return Err(OmegaError::Persist(format!(
404                "audit log size limit exceeded for {}: current {current_len} bytes, record {record_len} bytes, maximum {max_bytes} bytes",
405                self.path.display()
406            )));
407        }
408
409        let mut f = crate::private_fs::open_options()
410            .create(true)
411            .append(true)
412            .open(&self.path)
413            .map_err(|e| OmegaError::Persist(e.to_string()))?;
414        if let Err(error) = f.write_all(line.as_bytes()) {
415            return match f.set_len(current_len) {
416                Ok(()) => Err(OmegaError::Persist(error.to_string())),
417                Err(rollback_error) => Err(OmegaError::Persist(format!(
418                    "audit write failed: {error}; partial-record cleanup failed: {rollback_error}"
419                ))),
420            };
421        }
422        Ok(())
423    }
424
425    /// Performs tail for this type.
426    pub fn tail(&self, n: usize) -> Result<Vec<AuditRecord>> {
427        let mut rows = self.read_all()?;
428        if rows.len() > n {
429            rows = rows.split_off(rows.len() - n);
430        }
431        Ok(rows)
432    }
433
434    /// Read and validate every complete JSONL record.
435    ///
436    /// A malformed trailing line is an error here; use `poll_after` to retain
437    /// an incomplete trailing record while a writer is still appending.
438    pub fn read_all(&self) -> Result<Vec<AuditRecord>> {
439        if !self.path.exists() {
440            return Ok(vec![]);
441        }
442        let mut file =
443            fs::File::open(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
444        let mut data = String::new();
445        Read::by_ref(&mut file)
446            .take(MAX_AUDIT_READ_BYTES + 1)
447            .read_to_string(&mut data)
448            .map_err(|e| OmegaError::Persist(e.to_string()))?;
449        if data.len() as u64 > MAX_AUDIT_READ_BYTES {
450            return Err(OmegaError::Persist(format!(
451                "audit log read limit exceeded: maximum {MAX_AUDIT_READ_BYTES} bytes"
452            )));
453        }
454        let mut rows = Vec::new();
455        let mut offset = 0u64;
456        for (index, line) in data.split_inclusive('\n').enumerate() {
457            let line_number = index + 1;
458            let trimmed = line.trim_end_matches(['\r', '\n']);
459            if trimmed.len() > MAX_AUDIT_LINE_BYTES {
460                return Err(OmegaError::Persist(format!(
461                    "audit line {line_number} exceeds {MAX_AUDIT_LINE_BYTES} byte limit"
462                )));
463            }
464            if !trimmed.trim().is_empty() {
465                if rows.len() >= MAX_AUDIT_EVENTS {
466                    return Err(OmegaError::Persist(format!(
467                        "audit event count exceeds {MAX_AUDIT_EVENTS} limit"
468                    )));
469                }
470                let record = serde_json::from_str(trimmed)
471                    .map_err(|error| self.malformed_record(line_number, offset, error))?;
472                rows.push(record);
473            }
474            offset += line.len() as u64;
475        }
476        Ok(rows)
477    }
478
479    /// Current file length in bytes (0 if missing). Use as the cursor for [`AuditLog::poll_after`].
480    pub fn byte_len(&self) -> Result<u64> {
481        if !self.path.exists() {
482            return Ok(0);
483        }
484        let meta = fs::metadata(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
485        Ok(meta.len())
486    }
487
488    /// Read complete JSONL records written after `offset` bytes.
489    ///
490    /// Returns `(new_records, new_offset)`. Incomplete trailing lines are left
491    /// for a later poll (offset does not advance past them).
492    pub fn poll_after(&self, offset: u64) -> Result<(Vec<AuditRecord>, u64)> {
493        if !self.path.exists() {
494            return Ok((vec![], 0));
495        }
496        let mut f = fs::File::open(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
497        let len = f
498            .metadata()
499            .map_err(|e| OmegaError::Persist(e.to_string()))?
500            .len();
501        if offset > len {
502            // File was truncated/rotated — resync from start.
503            return self.poll_after(0);
504        }
505        f.seek(SeekFrom::Start(offset))
506            .map_err(|e| OmegaError::Persist(e.to_string()))?;
507        let remaining = MAX_AUDIT_READ_BYTES.saturating_add(1);
508        let mut buf = String::new();
509        Read::by_ref(&mut f)
510            .take(remaining)
511            .read_to_string(&mut buf)
512            .map_err(|e| OmegaError::Persist(e.to_string()))?;
513        if buf.len() as u64 > MAX_AUDIT_READ_BYTES {
514            return Err(OmegaError::Persist(format!(
515                "audit poll read limit exceeded: maximum {MAX_AUDIT_READ_BYTES} bytes"
516            )));
517        }
518
519        let mut rows = Vec::new();
520        let mut consumed = 0usize;
521        for (index, line) in buf.split_inclusive('\n').enumerate() {
522            let trimmed = line.trim_end_matches(['\r', '\n']);
523            if trimmed.len() > MAX_AUDIT_LINE_BYTES {
524                return Err(OmegaError::Persist(format!(
525                    "audit line {} exceeds {MAX_AUDIT_LINE_BYTES} byte limit",
526                    index + 1
527                )));
528            }
529            if trimmed.is_empty() {
530                consumed += line.len();
531                continue;
532            }
533            // Incomplete last line (no newline yet) — wait for more bytes.
534            if !line.ends_with('\n') {
535                break;
536            }
537            if rows.len() >= MAX_AUDIT_EVENTS {
538                return Err(OmegaError::Persist(format!(
539                    "audit event count exceeds {MAX_AUDIT_EVENTS} limit"
540                )));
541            }
542            let record = serde_json::from_str::<AuditRecord>(trimmed).map_err(|error| {
543                self.malformed_record(index + 1, offset + consumed as u64, error)
544            })?;
545            rows.push(record);
546            consumed += line.len();
547        }
548        let new_offset = offset + consumed as u64;
549        Ok((rows, new_offset))
550    }
551
552    /// Performs summarize for this type.
553    pub fn summarize(&self) -> Result<AuditSummary> {
554        let rows = self.read_all()?;
555        Ok(AuditSummary::from_records(&rows))
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use std::env::temp_dir;
563
564    fn remove_audit_file(path: &Path) {
565        let _ = fs::remove_file(path);
566        let _ = fs::remove_file(audit_lock_path(path));
567    }
568
569    #[test]
570    fn append_and_tail() {
571        let path = temp_dir().join(format!("omega-audit-{}.jsonl", crate::new_uuid()));
572        let log = AuditLog { path: path.clone() };
573        log.append(AuditEvent::Step {
574            step: 1,
575            goal: "g".into(),
576            action: "observe".into(),
577            avg_err: 0.5,
578            damping: 1.0,
579        })
580        .unwrap();
581        #[cfg(unix)]
582        {
583            use std::os::unix::fs::PermissionsExt;
584            assert_eq!(
585                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
586                0o600
587            );
588        }
589        let rows = log.tail(10).unwrap();
590        assert_eq!(rows.len(), 1);
591        let sum = log.summarize().unwrap();
592        assert_eq!(sum.steps, 1);
593        assert_eq!(sum.action_counts[0].0, "observe");
594        remove_audit_file(&path);
595    }
596
597    #[test]
598    fn append_limit_accepts_exact_boundary_and_preserves_file_when_full() {
599        let event = AuditEvent::ToolAllowed {
600            tool: "read".into(),
601        };
602        let record_len = serde_json::to_vec(&AuditRecord {
603            ts: crate::now_utc(),
604            event: event.clone(),
605        })
606        .unwrap()
607        .len() as u64
608            + 1;
609        let path = temp_dir().join(format!("omega-audit-limit-{}.jsonl", crate::new_uuid()));
610        let log = AuditLog { path: path.clone() };
611
612        log.append_with_max_bytes(event.clone(), record_len)
613            .unwrap();
614        assert_eq!(log.byte_len().unwrap(), record_len);
615        let before = fs::read(&path).unwrap();
616
617        let error = log
618            .append_with_max_bytes(event, record_len)
619            .unwrap_err()
620            .to_string();
621        assert!(error.contains("audit log size limit exceeded"), "{error}");
622        assert_eq!(fs::read(&path).unwrap(), before);
623        assert_eq!(log.read_all().unwrap().len(), 1);
624        remove_audit_file(&path);
625    }
626
627    #[test]
628    fn concurrent_appends_cannot_exceed_size_limit() {
629        let event = AuditEvent::ToolAllowed {
630            tool: "read".into(),
631        };
632        let record_len = serde_json::to_vec(&AuditRecord {
633            ts: crate::now_utc(),
634            event: event.clone(),
635        })
636        .unwrap()
637        .len() as u64
638            + 1;
639        let path = temp_dir().join(format!("omega-audit-race-{}.jsonl", crate::new_uuid()));
640        let log = AuditLog { path: path.clone() };
641
642        let writers: Vec<_> = (0..2)
643            .map(|_| {
644                let path = path.clone();
645                let event = event.clone();
646                std::thread::spawn(move || {
647                    AuditLog { path }.append_with_max_bytes(event, record_len)
648                })
649            })
650            .collect();
651        let outcomes: Vec<_> = writers
652            .into_iter()
653            .map(|writer| writer.join().unwrap())
654            .collect();
655
656        assert_eq!(outcomes.iter().filter(|result| result.is_ok()).count(), 1);
657        assert_eq!(log.read_all().unwrap().len(), 1);
658        assert!(log.byte_len().unwrap() <= record_len);
659        remove_audit_file(&path);
660    }
661
662    #[test]
663    fn existing_oversized_audit_files_remain_readable_but_reject_appends() {
664        let path = temp_dir().join(format!(
665            "omega-audit-legacy-limit-{}.jsonl",
666            crate::new_uuid()
667        ));
668        let log = AuditLog { path: path.clone() };
669        let event = AuditEvent::ToolAllowed {
670            tool: "read".into(),
671        };
672        log.append_with_max_bytes(event.clone(), u64::MAX).unwrap();
673        log.append_with_max_bytes(event.clone(), u64::MAX).unwrap();
674        let existing_len = log.byte_len().unwrap();
675        let before = fs::read(&path).unwrap();
676
677        let error = log
678            .append_with_max_bytes(event, existing_len - 1)
679            .unwrap_err()
680            .to_string();
681        assert!(error.contains("audit log size limit exceeded"), "{error}");
682        assert_eq!(fs::read(&path).unwrap(), before);
683        assert_eq!(log.read_all().unwrap().len(), 2);
684        let (rows, offset) = log.poll_after(0).unwrap();
685        assert_eq!(rows.len(), 2);
686        assert_eq!(offset, existing_len);
687        remove_audit_file(&path);
688    }
689
690    #[test]
691    fn read_all_rejects_oversized_line() {
692        let path = temp_dir().join(format!("omega-audit-long-{}.jsonl", crate::new_uuid()));
693        fs::write(&path, vec![b'x'; MAX_AUDIT_LINE_BYTES + 1]).unwrap();
694        let err = AuditLog { path: path.clone() }
695            .read_all()
696            .unwrap_err()
697            .to_string();
698        assert!(err.contains("audit line 1 exceeds"), "{err}");
699        remove_audit_file(&path);
700    }
701    #[test]
702    fn malformed_records_are_not_silently_dropped() {
703        let path = temp_dir().join(format!("omega-corrupt-{}.jsonl", crate::new_uuid()));
704        fs::write(&path, b"{not-json}\n").unwrap();
705        let log = AuditLog { path: path.clone() };
706
707        let error = log.read_all().unwrap_err().to_string();
708        assert!(error.contains("line 1"), "{error}");
709        assert!(error.contains("byte offset 0"), "{error}");
710        let error = log.poll_after(0).unwrap_err().to_string();
711        assert!(error.contains("line 1"), "{error}");
712        assert!(log.summarize().is_err());
713        let _ = fs::remove_file(&path);
714    }
715
716    #[test]
717    fn poll_after_reports_corruption_with_absolute_offset() {
718        let path = temp_dir().join(format!(
719            "omega-tail-{}-{}.jsonl",
720            std::process::id(),
721            crate::new_uuid()
722        ));
723        let log = AuditLog { path: path.clone() };
724        log.append(AuditEvent::Step {
725            step: 1,
726            goal: "g".into(),
727            action: "observe".into(),
728            avg_err: 0.5,
729            damping: 1.0,
730        })
731        .unwrap();
732        let offset = log.byte_len().unwrap();
733        fs::OpenOptions::new()
734            .append(true)
735            .open(&path)
736            .unwrap()
737            .write_all(b"{not-json}\n")
738            .unwrap();
739        let error = log.poll_after(0).unwrap_err().to_string();
740        assert!(error.contains("line 2"), "{error}");
741        assert!(error.contains(&format!("byte offset {offset}")), "{error}");
742
743        log.append(AuditEvent::Step {
744            step: 2,
745            goal: "g".into(),
746            action: "explore".into(),
747            avg_err: 0.4,
748            damping: 1.0,
749        })
750        .unwrap();
751        let complete = fs::read_to_string(&path).unwrap();
752        let partial = complete.trim_end().to_string();
753        fs::write(&path, partial).unwrap();
754        let error = log.poll_after(0).unwrap_err().to_string();
755        assert!(error.contains("line 2"), "{error}");
756        remove_audit_file(&path);
757    }
758
759    #[test]
760    fn poll_after_keeps_an_incomplete_trailing_record() {
761        let path = temp_dir().join(format!("omega-partial-{}.jsonl", crate::new_uuid()));
762        fs::write(&path, b"{\"ts\":").unwrap();
763        let log = AuditLog { path: path.clone() };
764        let (rows, offset) = log.poll_after(0).unwrap();
765        assert!(rows.is_empty());
766        assert_eq!(offset, 0);
767        let _ = fs::remove_file(&path);
768    }
769
770    #[test]
771    fn poll_after_reads_only_new_lines() {
772        let path = temp_dir().join(format!("omega-poll-{}.jsonl", crate::new_uuid()));
773        let log = AuditLog { path: path.clone() };
774        log.append(AuditEvent::Step {
775            step: 1,
776            goal: "g".into(),
777            action: "explore".into(),
778            avg_err: 0.4,
779            damping: 1.0,
780        })
781        .unwrap();
782        let (first, off) = log.poll_after(0).unwrap();
783        assert_eq!(first.len(), 1);
784        assert!(off > 0);
785
786        let (none, off2) = log.poll_after(off).unwrap();
787        assert!(none.is_empty());
788        assert_eq!(off2, off);
789
790        log.append(AuditEvent::PatchAccepted {
791            step: 2,
792            patch_id: Uuid::nil(),
793            damping: 0.8,
794            description: "t".into(),
795        })
796        .unwrap();
797        let (second, off3) = log.poll_after(off).unwrap();
798        assert_eq!(second.len(), 1);
799        assert!(matches!(second[0].event, AuditEvent::PatchAccepted { .. }));
800        assert!(off3 > off);
801
802        remove_audit_file(&path);
803    }
804
805    #[test]
806    #[cfg(unix)]
807    fn appending_does_not_change_permissions_of_an_existing_file() {
808        use std::os::unix::fs::PermissionsExt;
809
810        let path = temp_dir().join(format!("omega-audit-existing-{}.jsonl", crate::new_uuid()));
811        fs::write(&path, b"").unwrap();
812        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
813        AuditLog { path: path.clone() }
814            .append(AuditEvent::TaskEpisode {
815                task: "existing".into(),
816                reward: 0.5,
817                steps: 1,
818            })
819            .unwrap();
820        assert_eq!(
821            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
822            0o640
823        );
824        remove_audit_file(&path);
825    }
826}