omega-cognitive-kernel 1.3.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
//! Append-only trajectory JSONL writer with file locking and offline replay.

use crate::error::{OmegaError, Result};
use alloc::collections::BTreeMap;
use serde::Serialize;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Default maximum size for a trajectory JSONL file (64 MiB).
///
/// Existing files larger than this remain readable; only new appends are limited.
pub const DEFAULT_MAX_TRAJECTORY_BYTES: u64 = 64 * 1024 * 1024;

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

impl TrajectoryAppendLock {
    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!("trajectory lock open {}: {error}", path.display()))
                })?;
            file.lock_exclusive().map_err(|error| {
                OmegaError::Persist(format!(
                    "trajectory 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 trajectory usage remains supported there.
            let _ = path;
            Ok(Self {})
        }
    }
}

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

pub(super) fn append_trajectory_record(
    path: &Path,
    record: &serde_json::Value,
    max_bytes: u64,
) -> Result<()> {
    let mut line = serde_json::to_vec(record)
        .map_err(|error| OmegaError::Persist(format!("trajectory serialize: {error}")))?;
    line.push(b'\n');

    if let Some(parent) = path.parent() {
        crate::private_fs::create_dir_all(parent)
            .map_err(|error| OmegaError::Persist(format!("trajectory directory: {error}")))?;
    }
    let _lock = TrajectoryAppendLock::acquire(&trajectory_lock_path(path))?;

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

    let mut file = crate::private_fs::open_options()
        .create(true)
        .append(true)
        .open(path)
        .map_err(|error| {
            OmegaError::Persist(format!("trajectory open {}: {error}", path.display()))
        })?;
    file.write_all(&line).map_err(|error| {
        OmegaError::Persist(format!("trajectory write {}: {error}", path.display()))
    })
}

/// Offline summary of a `trajectory.jsonl` file (no world re-execution).
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct TrajectoryReplaySummary {
    /// Path of the trajectory file that was read.
    pub path: String,
    /// Number of valid trajectory rows parsed.
    pub rows: usize,
    /// Number of rows that record an accepted patch.
    pub patches: usize,
    /// First average error.
    pub first_avg_err: Option<f64>,
    /// Most recent average error.
    pub last_avg_err: Option<f64>,
    /// Action names paired with their occurrence counts.
    pub action_counts: Vec<(String, usize)>,
    /// Last N step lines (step, action, patched, avg_err) for operator view.
    pub tail: Vec<TrajectoryReplayRow>,
}

#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
/// One parsed trajectory row with the fields shown in replay summaries.
pub struct TrajectoryReplayRow {
    /// Kernel step number recorded in the row.
    pub step: u64,
    /// Action recorded for the step.
    pub action: String,
    /// Whether the step recorded an accepted patch.
    pub patched: bool,
    /// Average prediction error reported for the step.
    pub avg_err: Option<f64>,
    /// Goal associated with the step, when present in the file.
    pub goal: Option<String>,
    /// L2 arm-selection record, when present in the file.
    pub l2_decision: Option<crate::types::L2DecisionRecord>,
    /// Current L2 gate state.
    pub l2_gate_state: crate::l2::control::L2GateState,
    /// L2 policy learning-rate parameter.
    pub l2_alpha: f64,
    /// Current weights assigned to L2 experts.
    pub l2_expert_weights: BTreeMap<String, f64>,
    /// L2 policy regularization parameter.
    pub l2_beta: f64,
    /// Current Lyapunov stability potential.
    pub l2_lyapunov_potential: f64,
    /// Whether the stability monitor vetoed an L2 change.
    pub l2_lyapunov_veto: bool,
    /// Whether the most recent L2 lookup hit the meta-cache.
    pub l2_meta_cache_hit: bool,
    /// Residual used by the L2 Dayan stability calculation.
    pub l2_dayan_residual: f64,
    /// L2 policy currently applied at the control boundary.
    pub l2_applied_policy: crate::types::L2Policy,
    /// L2 policy proposed but not yet applied.
    pub l2_pending_policy: crate::types::L2Policy,
}

/// Read and summarize a trajectory.jsonl without running the kernel loop.
pub fn replay_trajectory_file(path: &Path, tail_n: usize) -> Result<TrajectoryReplaySummary> {
    use std::fs;
    if !path.exists() {
        return Err(OmegaError::Persist(format!(
            "trajectory not found: {}",
            path.display()
        )));
    }
    const MAX_TRACE_BYTES: u64 = 64 * 1024 * 1024;
    const MAX_TRACE_LINE_BYTES: usize = 1024 * 1024;
    const MAX_TRACE_ROWS: usize = 1_000_000;
    let mut file = fs::File::open(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
    let mut data = String::new();
    std::io::Read::read_to_string(
        &mut std::io::Read::take(std::io::Read::by_ref(&mut file), MAX_TRACE_BYTES + 1),
        &mut data,
    )
    .map_err(|e| OmegaError::Persist(e.to_string()))?;
    if data.len() as u64 > MAX_TRACE_BYTES {
        return Err(OmegaError::Persist(format!(
            "trajectory replay byte limit exceeded: maximum {MAX_TRACE_BYTES} bytes"
        )));
    }
    let mut rows = 0usize;
    let mut patches = 0usize;
    let mut first_avg_err = None;
    let mut last_avg_err = None;
    let mut actions: BTreeMap<String, usize> = BTreeMap::new();
    let mut tail_buf: Vec<TrajectoryReplayRow> = Vec::new();

    for line in data.lines().filter(|l| !l.trim().is_empty()) {
        if line.len() > MAX_TRACE_LINE_BYTES {
            return Err(OmegaError::Persist(format!(
                "trajectory replay line exceeds {MAX_TRACE_LINE_BYTES} byte limit"
            )));
        }
        if rows >= MAX_TRACE_ROWS {
            return Err(OmegaError::Persist(format!(
                "trajectory replay row count exceeds {MAX_TRACE_ROWS} limit"
            )));
        }
        let v: serde_json::Value =
            serde_json::from_str(line).map_err(|e| OmegaError::Persist(e.to_string()))?;
        rows += 1;
        let step = v.get("step").and_then(|x| x.as_u64()).unwrap_or(0);
        let action = v
            .get("action")
            .and_then(|x| x.as_str())
            .unwrap_or("-")
            .to_string();
        let patched = v.get("patched").and_then(|x| x.as_bool()).unwrap_or(false);
        if patched {
            patches += 1;
        }
        let avg_err = v.get("avg_err").and_then(|x| x.as_f64());
        if first_avg_err.is_none() {
            first_avg_err = avg_err;
        }
        if avg_err.is_some() {
            last_avg_err = avg_err;
        }
        *actions.entry(action.clone()).or_insert(0) += 1;
        let goal = v
            .get("goal")
            .and_then(|x| x.as_str())
            .map(|s| s.to_string());
        tail_buf.push(TrajectoryReplayRow {
            step,
            action,
            patched,
            avg_err,
            goal,
            l2_decision: v
                .get("l2_decision")
                .cloned()
                .and_then(|value| serde_json::from_value(value).ok()),
            l2_gate_state: v
                .get("l2_gate_state")
                .cloned()
                .and_then(|value| serde_json::from_value(value).ok())
                .unwrap_or_default(),
            l2_alpha: v
                .get("l2_alpha")
                .and_then(|value| value.as_f64())
                .unwrap_or(0.0),
            l2_expert_weights: v
                .get("l2_expert_weights")
                .cloned()
                .and_then(|value| serde_json::from_value(value).ok())
                .unwrap_or_default(),
            l2_beta: v
                .get("l2_beta")
                .and_then(|value| value.as_f64())
                .unwrap_or(0.0),
            l2_lyapunov_potential: v
                .get("l2_lyapunov_potential")
                .and_then(|value| value.as_f64())
                .unwrap_or(1.0),
            l2_lyapunov_veto: v
                .get("l2_lyapunov_veto")
                .and_then(|value| value.as_bool())
                .unwrap_or(false),
            l2_meta_cache_hit: v
                .get("l2_meta_cache_hit")
                .and_then(|value| value.as_bool())
                .unwrap_or(false),
            l2_dayan_residual: v
                .get("l2_dayan_residual")
                .and_then(|value| value.as_f64())
                .unwrap_or(0.0),
            l2_applied_policy: v
                .get("l2_applied_policy")
                .cloned()
                .and_then(|value| serde_json::from_value(value).ok())
                .unwrap_or_default(),
            l2_pending_policy: v
                .get("l2_pending_policy")
                .cloned()
                .and_then(|value| serde_json::from_value(value).ok())
                .unwrap_or_default(),
        });
    }

    let mut action_counts: Vec<_> = actions.into_iter().collect();
    action_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    let tail = if tail_buf.len() > tail_n {
        tail_buf.split_off(tail_buf.len() - tail_n)
    } else {
        tail_buf
    };

    Ok(TrajectoryReplaySummary {
        path: path.display().to_string(),
        rows,
        patches,
        first_avg_err,
        last_avg_err,
        action_counts,
        tail,
    })
}