omega-cognitive-kernel 1.1.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Append-only audit log (S3 hardening).
//!
//! `AuditEvent` is the kernel's public event stream. Prefer the alias
//! [`KernelEvent`] at the crate root when wiring integrators.

#[allow(unused_imports)]
use crate::prelude::*;

use crate::error::{OmegaError, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// Maximum bytes retained while reading one audit log.
pub const MAX_AUDIT_READ_BYTES: u64 = 64 * 1024 * 1024;
/// Maximum serialized JSONL record size (excluding its newline).
pub const MAX_AUDIT_LINE_BYTES: usize = 1024 * 1024;
/// Maximum records returned by a single audit read.
pub const MAX_AUDIT_EVENTS: usize = 1_000_000;

/// Public event stream for integrators (same shape as [`AuditEvent`]).
pub type KernelEvent = AuditEvent;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
/// Typed event emitted by the kernel and persisted in its append-only audit log.
pub enum AuditEvent {
    /// A kernel step completed.
    Step {
        /// Kernel step number associated with the event.
        step: u64,
        /// Goal submitted for the step.
        goal: String,
        /// Action selected or produced by the kernel.
        action: String,
        /// Average prediction error reported for the step.
        avg_err: f64,
        /// Prediction-error damping factor used for the step.
        damping: f64,
    },
    /// A proposed patch passed validation and was accepted.
    PatchAccepted {
        /// Kernel step number associated with the patch.
        step: u64,
        /// Unique identifier assigned to the accepted patch.
        patch_id: Uuid,
        /// Prediction-error damping factor used for the step.
        damping: f64,
        /// Human-readable summary of the accepted change.
        description: String,
    },
    /// A proposed patch was rejected and not applied.
    PatchRejected {
        /// Kernel step number associated with the proposal.
        step: u64,
        /// Explanation for rejecting the patch.
        reason: String,
    },
    /// A kernel snapshot was saved as a checkpoint.
    Checkpoint {
        /// Identifier for the checkpoint.
        checkpoint_id: Uuid,
        /// Kernel step captured by the checkpoint.
        step: u64,
        /// Human-readable label for the checkpoint.
        label: String,
    },
    /// Kernel state was restored from a checkpoint.
    Rollback {
        /// Identifier for the checkpoint.
        checkpoint_id: Uuid,
        /// Kernel step number before the restore.
        step_before: u64,
    },
    /// A task episode completed and its reward was recorded.
    TaskEpisode {
        /// Name or description of the completed task.
        task: String,
        /// Reward observed for the episode.
        reward: f64,
        /// Number of steps used by the episode.
        steps: u32,
    },
    /// Tool-call gate: proposed tool was on allow-list and recorded.
    ToolAllowed {
        /// Name of the tool admitted by the gate.
        tool: String,
    },
    /// Tool-call gate: proposed tool blocked (deny-list or not allowed).
    ToolDenied {
        /// Name of the tool rejected by the gate.
        tool: String,
        /// Explanation for denying the tool call.
        reason: String,
    },
    /// L2 entered the fixed-point regime.
    FixedPointEntered {
        /// Kernel step at which L2 entered the regime.
        step: u64,
        /// Alignment score measured at entry.
        alignment_score: f64,
    },
    /// L2 exited the fixed-point regime.
    FixedPointExited {
        /// Kernel step at which L2 exited the regime.
        step: u64,
        /// Alignment score measured at exit.
        alignment_score: f64,
        /// Number of steps spent in the current regime or arm.
        dwell_steps: u64,
    },
    /// L2 proposed a policy modulation.
    L2ModulationProposed {
        /// Kernel step associated with the proposal.
        step: u64,
        /// Score assigned to the proposal.
        score: f64,
    },
    /// L2 committed a proposed policy modulation.
    L2ModulationCommitted {
        /// Kernel step at which the modulation was committed.
        step: u64,
        /// Score assigned to the committed modulation.
        score: f64,
        /// Gain applied when committing the modulation.
        gain: f64,
    },
    /// Telemetry for a step executed by an external host was processed.
    ExternalStep {
        /// Identifier of the step represented by this value.
        step_id: u64,
        /// Prediction error measured for this step.
        prediction_error: f64,
        /// Risk observed while executing this step.
        observed_risk: f64,
        /// L1 gate decision returned to the host.
        l1_gate: String,
        /// Whether the host was instructed to keep its current policy.
        keep_steady: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// Identifier of the patch proposed for this step, if any.
        patch_id: Option<String>,
    },
    /// The host was instructed to restore a checkpoint after a degraded step.
    ExternalRollback {
        /// Identifier of the step represented by this value.
        step_id: u64,
        /// Identifier for the checkpoint.
        checkpoint_id: String,
        /// Number of consecutive rollbacks at this point.
        consecutive_rollbacks: u32,
        /// Remaining cooldown steps before another patch may be considered.
        next_cooldown: u64,
    },
    /// A duplicate or out-of-order external step identifier was ignored.
    ExternalStepDuplicate {
        /// Identifier of the step represented by this value.
        step_id: u64,
        /// Most recent external step identifier already processed.
        last_step_id: u64,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Timestamped event stored in the append-only audit log.
pub struct AuditRecord {
    /// UTC timestamp when the event was recorded.
    pub ts: crate::UtcTimestamp,
    /// Audit event recorded at this timestamp.
    pub event: AuditEvent,
}

/// Operator-facing rollup of an audit.jsonl file.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AuditSummary {
    /// Total number of audit records summarized.
    pub total_events: usize,
    /// Number of steps completed by the run.
    pub steps: usize,
    /// Number of patches accepted during the run.
    pub patches_accepted: usize,
    /// Number of rejected patches.
    pub patches_rejected: usize,
    /// Number of checkpoint events.
    pub checkpoints: usize,
    /// Number of rollback events.
    pub rollbacks: usize,
    /// Number of completed task episodes.
    pub task_episodes: usize,
    /// Number of tool calls allowed by the gate.
    pub tools_allowed: usize,
    /// Number of tool calls denied by the gate.
    pub tools_denied: usize,
    /// Number of entries into the L2 fixed-point regime.
    pub fixed_point_enters: usize,
    /// Number of exits from the L2 fixed-point regime.
    pub fixed_point_exits: usize,
    /// Number of L2 modulation proposals.
    pub l2_modulation_proposals: usize,
    /// Number of L2 modulation commits.
    pub l2_modulation_commits: usize,
    /// Timestamp of the first record, if the input was non-empty.
    pub first_ts: Option<crate::UtcTimestamp>,
    /// Timestamp of the last record, if the input was non-empty.
    pub last_ts: Option<crate::UtcTimestamp>,
    /// Most recent action.
    pub last_action: Option<String>,
    /// Most recent average error.
    pub last_avg_err: Option<f64>,
    /// Most recent damping.
    pub last_damping: Option<f64>,
    /// Action names paired with their occurrence counts.
    pub action_counts: Vec<(String, usize)>,
}

impl AuditSummary {
    /// Builds an operator-facing summary from audit records in input order.
    pub fn from_records(rows: &[AuditRecord]) -> Self {
        use hashbrown::HashMap;
        let mut s = AuditSummary {
            total_events: rows.len(),
            ..AuditSummary::default()
        };
        let mut actions: HashMap<String, usize> = HashMap::new();
        if let Some(first) = rows.first() {
            s.first_ts = Some(first.ts);
        }
        if let Some(last) = rows.last() {
            s.last_ts = Some(last.ts);
        }
        for r in rows {
            match &r.event {
                AuditEvent::Step {
                    action,
                    avg_err,
                    damping,
                    ..
                } => {
                    s.steps += 1;
                    *actions.entry(action.clone()).or_insert(0) += 1;
                    s.last_action = Some(action.clone());
                    s.last_avg_err = Some(*avg_err);
                    s.last_damping = Some(*damping);
                }
                AuditEvent::PatchAccepted { .. } => s.patches_accepted += 1,
                AuditEvent::PatchRejected { .. } => s.patches_rejected += 1,
                AuditEvent::Checkpoint { .. } => s.checkpoints += 1,
                AuditEvent::Rollback { .. } => s.rollbacks += 1,
                AuditEvent::TaskEpisode { .. } => s.task_episodes += 1,
                AuditEvent::ToolAllowed { tool } => {
                    s.tools_allowed += 1;
                    *actions.entry(format!("tool:{tool}")).or_insert(0) += 1;
                }
                AuditEvent::ToolDenied { tool, .. } => {
                    s.tools_denied += 1;
                    *actions.entry(format!("deny:{tool}")).or_insert(0) += 1;
                }
                AuditEvent::FixedPointEntered { .. } => s.fixed_point_enters += 1,
                AuditEvent::FixedPointExited { .. } => s.fixed_point_exits += 1,
                AuditEvent::L2ModulationProposed { .. } => s.l2_modulation_proposals += 1,
                AuditEvent::L2ModulationCommitted { .. } => s.l2_modulation_commits += 1,
                AuditEvent::ExternalStep { .. } => s.steps += 1,
                AuditEvent::ExternalRollback { .. } => s.rollbacks += 1,
                AuditEvent::ExternalStepDuplicate { .. } => {}
            }
        }
        let mut counts: Vec<_> = actions.into_iter().collect();
        counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        s.action_counts = counts;
        s
    }
}

/// Data structure representing audit log.
pub struct AuditLog {
    /// Path for this value.
    pub path: PathBuf,
}

/// Default maximum size for an audit JSONL file (64 MiB).
///
/// Existing files larger than this remain readable; only new appends are
/// limited. Integrators can choose a different ceiling per append.
pub const DEFAULT_MAX_AUDIT_BYTES: u64 = 64 * 1024 * 1024;

struct AuditAppendLock {
    #[cfg(any(unix, windows))]
    _file: fs::File,
}

impl AuditAppendLock {
    fn acquire(path: &Path) -> Result<Self> {
        #[cfg(any(unix, windows))]
        {
            use fs2::FileExt;

            let file = crate::private_fs::open_options()
                .read(true)
                .write(true)
                .create(true)
                .open(path)
                .map_err(|error| {
                    OmegaError::Persist(format!("audit lock open {}: {error}", path.display()))
                })?;
            file.lock_exclusive().map_err(|error| {
                OmegaError::Persist(format!("audit lock acquire {}: {error}", path.display()))
            })?;
            Ok(Self { _file: file })
        }
        #[cfg(not(any(unix, windows)))]
        {
            // These targets do not support the crate's advisory file locks;
            // single-writer audit usage remains supported there.
            let _ = path;
            Ok(Self {})
        }
    }
}

fn audit_lock_path(path: &Path) -> PathBuf {
    let mut lock_path = path.as_os_str().to_os_string();
    lock_path.push(".lock");
    PathBuf::from(lock_path)
}

impl AuditLog {
    fn malformed_record(&self, line: usize, offset: u64, error: serde_json::Error) -> OmegaError {
        OmegaError::Persist(format!(
            "malformed audit record in {} at line {line}, byte offset {offset}: {error}",
            self.path.display()
        ))
    }

    /// Performs beside state for this type.
    pub fn beside_state(state_path: &Path) -> Self {
        let path = state_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("audit.jsonl");
        Self { path }
    }

    /// Performs append for this type.
    pub fn append(&self, event: AuditEvent) -> Result<()> {
        self.append_with_max_bytes(event, DEFAULT_MAX_AUDIT_BYTES)
    }

    /// Append an event with an explicit maximum audit-file size in bytes.
    ///
    /// The check and append are serialized across cooperating local writers.
    /// A zero limit rejects every record; use `u64::MAX` for an effectively
    /// unlimited file. Existing bytes are never truncated or rotated.
    pub fn append_with_max_bytes(&self, event: AuditEvent, max_bytes: u64) -> Result<()> {
        self.append_with_privacy_and_max_bytes(event, false, max_bytes)
    }

    /// Append an event, optionally replacing user-provided text fields before serialization.
    pub fn append_with_privacy(&self, event: AuditEvent, redact_user_content: bool) -> Result<()> {
        self.append_with_privacy_and_max_bytes(event, redact_user_content, DEFAULT_MAX_AUDIT_BYTES)
    }

    /// Append an event with privacy redaction and an explicit maximum file size.
    pub fn append_with_privacy_and_max_bytes(
        &self,
        mut event: AuditEvent,
        redact_user_content: bool,
        max_bytes: u64,
    ) -> Result<()> {
        if redact_user_content {
            match &mut event {
                AuditEvent::Step { goal, .. } => *goal = "[REDACTED]".into(),
                AuditEvent::Checkpoint { label, .. } => *label = "[REDACTED]".into(),
                AuditEvent::TaskEpisode { task, .. } => *task = "[REDACTED]".into(),
                _ => {}
            }
        }
        if let Some(parent) = self.path.parent() {
            crate::private_fs::create_dir_all(parent)
                .map_err(|e| OmegaError::Persist(e.to_string()))?;
        }
        let _lock = AuditAppendLock::acquire(&audit_lock_path(&self.path))?;

        let rec = AuditRecord {
            ts: crate::now_utc(),
            event,
        };
        let mut line =
            serde_json::to_string(&rec).map_err(|e| OmegaError::Persist(e.to_string()))?;
        line.push('\n');

        let current_len = match fs::metadata(&self.path) {
            Ok(metadata) => metadata.len(),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
            Err(error) => return Err(OmegaError::Persist(error.to_string())),
        };
        let record_len = u64::try_from(line.len())
            .map_err(|error| OmegaError::Persist(format!("audit record size: {error}")))?;
        let resulting_len = current_len.checked_add(record_len);
        if !matches!(resulting_len, Some(size) if size <= max_bytes) {
            return Err(OmegaError::Persist(format!(
                "audit log size limit exceeded for {}: current {current_len} bytes, record {record_len} bytes, maximum {max_bytes} bytes",
                self.path.display()
            )));
        }

        let mut f = crate::private_fs::open_options()
            .create(true)
            .append(true)
            .open(&self.path)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        if let Err(error) = f.write_all(line.as_bytes()) {
            return match f.set_len(current_len) {
                Ok(()) => Err(OmegaError::Persist(error.to_string())),
                Err(rollback_error) => Err(OmegaError::Persist(format!(
                    "audit write failed: {error}; partial-record cleanup failed: {rollback_error}"
                ))),
            };
        }
        Ok(())
    }

    /// Performs tail for this type.
    pub fn tail(&self, n: usize) -> Result<Vec<AuditRecord>> {
        let mut rows = self.read_all()?;
        if rows.len() > n {
            rows = rows.split_off(rows.len() - n);
        }
        Ok(rows)
    }

    /// Read and validate every complete JSONL record.
    ///
    /// A malformed trailing line is an error here; use `poll_after` to retain
    /// an incomplete trailing record while a writer is still appending.
    pub fn read_all(&self) -> Result<Vec<AuditRecord>> {
        if !self.path.exists() {
            return Ok(vec![]);
        }
        let mut file =
            fs::File::open(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let mut data = String::new();
        Read::by_ref(&mut file)
            .take(MAX_AUDIT_READ_BYTES + 1)
            .read_to_string(&mut data)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        if data.len() as u64 > MAX_AUDIT_READ_BYTES {
            return Err(OmegaError::Persist(format!(
                "audit log read limit exceeded: maximum {MAX_AUDIT_READ_BYTES} bytes"
            )));
        }
        let mut rows = Vec::new();
        let mut offset = 0u64;
        for (index, line) in data.split_inclusive('\n').enumerate() {
            let line_number = index + 1;
            let trimmed = line.trim_end_matches(['\r', '\n']);
            if trimmed.len() > MAX_AUDIT_LINE_BYTES {
                return Err(OmegaError::Persist(format!(
                    "audit line {line_number} exceeds {MAX_AUDIT_LINE_BYTES} byte limit"
                )));
            }
            if !trimmed.trim().is_empty() {
                if rows.len() >= MAX_AUDIT_EVENTS {
                    return Err(OmegaError::Persist(format!(
                        "audit event count exceeds {MAX_AUDIT_EVENTS} limit"
                    )));
                }
                let record = serde_json::from_str(trimmed)
                    .map_err(|error| self.malformed_record(line_number, offset, error))?;
                rows.push(record);
            }
            offset += line.len() as u64;
        }
        Ok(rows)
    }

    /// Current file length in bytes (0 if missing). Use as the cursor for [`AuditLog::poll_after`].
    pub fn byte_len(&self) -> Result<u64> {
        if !self.path.exists() {
            return Ok(0);
        }
        let meta = fs::metadata(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
        Ok(meta.len())
    }

    /// Read complete JSONL records written after `offset` bytes.
    ///
    /// Returns `(new_records, new_offset)`. Incomplete trailing lines are left
    /// for a later poll (offset does not advance past them).
    pub fn poll_after(&self, offset: u64) -> Result<(Vec<AuditRecord>, u64)> {
        if !self.path.exists() {
            return Ok((vec![], 0));
        }
        let mut f = fs::File::open(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let len = f
            .metadata()
            .map_err(|e| OmegaError::Persist(e.to_string()))?
            .len();
        if offset > len {
            // File was truncated/rotated — resync from start.
            return self.poll_after(0);
        }
        f.seek(SeekFrom::Start(offset))
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        let remaining = MAX_AUDIT_READ_BYTES.saturating_add(1);
        let mut buf = String::new();
        Read::by_ref(&mut f)
            .take(remaining)
            .read_to_string(&mut buf)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        if buf.len() as u64 > MAX_AUDIT_READ_BYTES {
            return Err(OmegaError::Persist(format!(
                "audit poll read limit exceeded: maximum {MAX_AUDIT_READ_BYTES} bytes"
            )));
        }

        let mut rows = Vec::new();
        let mut consumed = 0usize;
        for (index, line) in buf.split_inclusive('\n').enumerate() {
            let trimmed = line.trim_end_matches(['\r', '\n']);
            if trimmed.len() > MAX_AUDIT_LINE_BYTES {
                return Err(OmegaError::Persist(format!(
                    "audit line {} exceeds {MAX_AUDIT_LINE_BYTES} byte limit",
                    index + 1
                )));
            }
            if trimmed.is_empty() {
                consumed += line.len();
                continue;
            }
            // Incomplete last line (no newline yet) — wait for more bytes.
            if !line.ends_with('\n') {
                break;
            }
            if rows.len() >= MAX_AUDIT_EVENTS {
                return Err(OmegaError::Persist(format!(
                    "audit event count exceeds {MAX_AUDIT_EVENTS} limit"
                )));
            }
            let record = serde_json::from_str::<AuditRecord>(trimmed).map_err(|error| {
                self.malformed_record(index + 1, offset + consumed as u64, error)
            })?;
            rows.push(record);
            consumed += line.len();
        }
        let new_offset = offset + consumed as u64;
        Ok((rows, new_offset))
    }

    /// Performs summarize for this type.
    pub fn summarize(&self) -> Result<AuditSummary> {
        let rows = self.read_all()?;
        Ok(AuditSummary::from_records(&rows))
    }
}

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

    fn remove_audit_file(path: &Path) {
        let _ = fs::remove_file(path);
        let _ = fs::remove_file(audit_lock_path(path));
    }

    #[test]
    fn append_and_tail() {
        let path = temp_dir().join(format!("omega-audit-{}.jsonl", crate::new_uuid()));
        let log = AuditLog { path: path.clone() };
        log.append(AuditEvent::Step {
            step: 1,
            goal: "g".into(),
            action: "observe".into(),
            avg_err: 0.5,
            damping: 1.0,
        })
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
                0o600
            );
        }
        let rows = log.tail(10).unwrap();
        assert_eq!(rows.len(), 1);
        let sum = log.summarize().unwrap();
        assert_eq!(sum.steps, 1);
        assert_eq!(sum.action_counts[0].0, "observe");
        remove_audit_file(&path);
    }

    #[test]
    fn append_limit_accepts_exact_boundary_and_preserves_file_when_full() {
        let event = AuditEvent::ToolAllowed {
            tool: "read".into(),
        };
        let record_len = serde_json::to_vec(&AuditRecord {
            ts: crate::now_utc(),
            event: event.clone(),
        })
        .unwrap()
        .len() as u64
            + 1;
        let path = temp_dir().join(format!("omega-audit-limit-{}.jsonl", crate::new_uuid()));
        let log = AuditLog { path: path.clone() };

        log.append_with_max_bytes(event.clone(), record_len)
            .unwrap();
        assert_eq!(log.byte_len().unwrap(), record_len);
        let before = fs::read(&path).unwrap();

        let error = log
            .append_with_max_bytes(event, record_len)
            .unwrap_err()
            .to_string();
        assert!(error.contains("audit log size limit exceeded"), "{error}");
        assert_eq!(fs::read(&path).unwrap(), before);
        assert_eq!(log.read_all().unwrap().len(), 1);
        remove_audit_file(&path);
    }

    #[test]
    fn concurrent_appends_cannot_exceed_size_limit() {
        let event = AuditEvent::ToolAllowed {
            tool: "read".into(),
        };
        let record_len = serde_json::to_vec(&AuditRecord {
            ts: crate::now_utc(),
            event: event.clone(),
        })
        .unwrap()
        .len() as u64
            + 1;
        let path = temp_dir().join(format!("omega-audit-race-{}.jsonl", crate::new_uuid()));
        let log = AuditLog { path: path.clone() };

        let writers: Vec<_> = (0..2)
            .map(|_| {
                let path = path.clone();
                let event = event.clone();
                std::thread::spawn(move || {
                    AuditLog { path }.append_with_max_bytes(event, record_len)
                })
            })
            .collect();
        let outcomes: Vec<_> = writers
            .into_iter()
            .map(|writer| writer.join().unwrap())
            .collect();

        assert_eq!(outcomes.iter().filter(|result| result.is_ok()).count(), 1);
        assert_eq!(log.read_all().unwrap().len(), 1);
        assert!(log.byte_len().unwrap() <= record_len);
        remove_audit_file(&path);
    }

    #[test]
    fn existing_oversized_audit_files_remain_readable_but_reject_appends() {
        let path = temp_dir().join(format!(
            "omega-audit-legacy-limit-{}.jsonl",
            crate::new_uuid()
        ));
        let log = AuditLog { path: path.clone() };
        let event = AuditEvent::ToolAllowed {
            tool: "read".into(),
        };
        log.append_with_max_bytes(event.clone(), u64::MAX).unwrap();
        log.append_with_max_bytes(event.clone(), u64::MAX).unwrap();
        let existing_len = log.byte_len().unwrap();
        let before = fs::read(&path).unwrap();

        let error = log
            .append_with_max_bytes(event, existing_len - 1)
            .unwrap_err()
            .to_string();
        assert!(error.contains("audit log size limit exceeded"), "{error}");
        assert_eq!(fs::read(&path).unwrap(), before);
        assert_eq!(log.read_all().unwrap().len(), 2);
        let (rows, offset) = log.poll_after(0).unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(offset, existing_len);
        remove_audit_file(&path);
    }

    #[test]
    fn read_all_rejects_oversized_line() {
        let path = temp_dir().join(format!("omega-audit-long-{}.jsonl", crate::new_uuid()));
        fs::write(&path, vec![b'x'; MAX_AUDIT_LINE_BYTES + 1]).unwrap();
        let err = AuditLog { path: path.clone() }
            .read_all()
            .unwrap_err()
            .to_string();
        assert!(err.contains("audit line 1 exceeds"), "{err}");
        remove_audit_file(&path);
    }
    #[test]
    fn malformed_records_are_not_silently_dropped() {
        let path = temp_dir().join(format!("omega-corrupt-{}.jsonl", crate::new_uuid()));
        fs::write(&path, b"{not-json}\n").unwrap();
        let log = AuditLog { path: path.clone() };

        let error = log.read_all().unwrap_err().to_string();
        assert!(error.contains("line 1"), "{error}");
        assert!(error.contains("byte offset 0"), "{error}");
        let error = log.poll_after(0).unwrap_err().to_string();
        assert!(error.contains("line 1"), "{error}");
        assert!(log.summarize().is_err());
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn poll_after_reports_corruption_with_absolute_offset() {
        let path = temp_dir().join(format!(
            "omega-tail-{}-{}.jsonl",
            std::process::id(),
            crate::new_uuid()
        ));
        let log = AuditLog { path: path.clone() };
        log.append(AuditEvent::Step {
            step: 1,
            goal: "g".into(),
            action: "observe".into(),
            avg_err: 0.5,
            damping: 1.0,
        })
        .unwrap();
        let offset = log.byte_len().unwrap();
        fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap()
            .write_all(b"{not-json}\n")
            .unwrap();
        let error = log.poll_after(0).unwrap_err().to_string();
        assert!(error.contains("line 2"), "{error}");
        assert!(error.contains(&format!("byte offset {offset}")), "{error}");

        log.append(AuditEvent::Step {
            step: 2,
            goal: "g".into(),
            action: "explore".into(),
            avg_err: 0.4,
            damping: 1.0,
        })
        .unwrap();
        let complete = fs::read_to_string(&path).unwrap();
        let partial = complete.trim_end().to_string();
        fs::write(&path, partial).unwrap();
        let error = log.poll_after(0).unwrap_err().to_string();
        assert!(error.contains("line 2"), "{error}");
        remove_audit_file(&path);
    }

    #[test]
    fn poll_after_keeps_an_incomplete_trailing_record() {
        let path = temp_dir().join(format!("omega-partial-{}.jsonl", crate::new_uuid()));
        fs::write(&path, b"{\"ts\":").unwrap();
        let log = AuditLog { path: path.clone() };
        let (rows, offset) = log.poll_after(0).unwrap();
        assert!(rows.is_empty());
        assert_eq!(offset, 0);
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn poll_after_reads_only_new_lines() {
        let path = temp_dir().join(format!("omega-poll-{}.jsonl", crate::new_uuid()));
        let log = AuditLog { path: path.clone() };
        log.append(AuditEvent::Step {
            step: 1,
            goal: "g".into(),
            action: "explore".into(),
            avg_err: 0.4,
            damping: 1.0,
        })
        .unwrap();
        let (first, off) = log.poll_after(0).unwrap();
        assert_eq!(first.len(), 1);
        assert!(off > 0);

        let (none, off2) = log.poll_after(off).unwrap();
        assert!(none.is_empty());
        assert_eq!(off2, off);

        log.append(AuditEvent::PatchAccepted {
            step: 2,
            patch_id: Uuid::nil(),
            damping: 0.8,
            description: "t".into(),
        })
        .unwrap();
        let (second, off3) = log.poll_after(off).unwrap();
        assert_eq!(second.len(), 1);
        assert!(matches!(second[0].event, AuditEvent::PatchAccepted { .. }));
        assert!(off3 > off);

        remove_audit_file(&path);
    }

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

        let path = temp_dir().join(format!("omega-audit-existing-{}.jsonl", crate::new_uuid()));
        fs::write(&path, b"").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
        AuditLog { path: path.clone() }
            .append(AuditEvent::TaskEpisode {
                task: "existing".into(),
                reward: 0.5,
                steps: 1,
            })
            .unwrap();
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o640
        );
        remove_audit_file(&path);
    }
}