omega-cognitive-kernel 0.6.1

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
//! 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 chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// 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")]
pub enum AuditEvent {
    Step {
        step: u64,
        goal: String,
        action: String,
        avg_err: f64,
        damping: f64,
    },
    PatchAccepted {
        step: u64,
        patch_id: Uuid,
        damping: f64,
        description: String,
    },
    PatchRejected {
        step: u64,
        reason: String,
    },
    Checkpoint {
        checkpoint_id: Uuid,
        step: u64,
        label: String,
    },
    Rollback {
        checkpoint_id: Uuid,
        step_before: u64,
    },
    TaskEpisode {
        task: String,
        reward: f64,
        steps: u32,
    },
    /// Tool-call gate: proposed tool was on allow-list and recorded.
    ToolAllowed {
        tool: String,
    },
    /// Tool-call gate: proposed tool blocked (deny-list or not allowed).
    ToolDenied {
        tool: String,
        reason: String,
    },
    /// L2 entered the fixed-point regime.
    FixedPointEntered {
        step: u64,
        alignment_score: f64,
    },
    /// L2 exited the fixed-point regime.
    FixedPointExited {
        step: u64,
        alignment_score: f64,
        dwell_steps: u64,
    },
    L2ModulationProposed {
        step: u64,
        score: f64,
    },
    L2ModulationCommitted {
        step: u64,
        score: f64,
        gain: f64,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditRecord {
    pub ts: DateTime<Utc>,
    pub event: AuditEvent,
}

/// Operator-facing rollup of an audit.jsonl file.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AuditSummary {
    pub total_events: usize,
    pub steps: usize,
    pub patches_accepted: usize,
    pub patches_rejected: usize,
    pub checkpoints: usize,
    pub rollbacks: usize,
    pub task_episodes: usize,
    pub tools_allowed: usize,
    pub tools_denied: usize,
    pub fixed_point_enters: usize,
    pub fixed_point_exits: usize,
    pub l2_modulation_proposals: usize,
    pub l2_modulation_commits: usize,
    pub first_ts: Option<DateTime<Utc>>,
    pub last_ts: Option<DateTime<Utc>>,
    pub last_action: Option<String>,
    pub last_avg_err: Option<f64>,
    pub last_damping: Option<f64>,
    pub action_counts: Vec<(String, usize)>,
}

impl AuditSummary {
    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,
            }
        }
        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
    }
}

pub struct AuditLog {
    pub path: PathBuf,
}

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()
        ))
    }

    pub fn beside_state(state_path: &Path) -> Self {
        let path = state_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("audit.jsonl");
        Self { path }
    }

    pub fn append(&self, event: AuditEvent) -> Result<()> {
        self.append_with_privacy(event, false)
    }

    /// Append an event, optionally replacing user-provided text fields before serialization.
    pub fn append_with_privacy(
        &self,
        mut event: AuditEvent,
        redact_user_content: bool,
    ) -> 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 rec = AuditRecord {
            ts: crate::now_utc(),
            event,
        };
        let line = serde_json::to_string(&rec).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let mut f = crate::private_fs::open_options()
            .create(true)
            .append(true)
            .open(&self.path)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        writeln!(f, "{line}").map_err(|e| OmegaError::Persist(e.to_string()))?;
        Ok(())
    }

    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 data =
            fs::read_to_string(&self.path).map_err(|e| OmegaError::Persist(e.to_string()))?;
        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.trim().is_empty() {
                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 [`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 mut buf = String::new();
        f.read_to_string(&mut buf)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;

        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.is_empty() {
                consumed += line.len();
                continue;
            }
            // Incomplete last line (no newline yet) — wait for more bytes.
            if !line.ends_with('\n') {
                break;
            }
            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))
    }

    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;

    #[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");
        let _ = fs::remove_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}");
        let _ = fs::remove_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);

        let _ = fs::remove_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
        );
        let _ = fs::remove_file(path);
    }
}