omega-cognitive-kernel 1.4.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
//! Per-step crash-recovery journal for idempotent step execution.

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum StepJournalStatus {
    Started,
    Dispatching,
    Executed,
    NotExecuted,
    Committed,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct StepJournalRecord {
    pub(super) step_id: Uuid,
    pub(super) goal: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) goal_digest: Option<String>,
    pub(super) attempt: u64,
    pub(super) status: StepJournalStatus,
}

pub(super) fn step_goal_digest(goal: &str) -> String {
    crate::safety::crypto::hex_encode(&crate::safety::crypto::sha256(goal.as_bytes()))
}

pub(super) fn step_journal_goal_matches_record(record: &StepJournalRecord, goal: &str) -> bool {
    match record.goal_digest.as_deref() {
        Some(digest) => digest == step_goal_digest(goal),
        None => record.goal == goal,
    }
}

pub(super) fn step_journal_records_have_same_goal(
    left: &StepJournalRecord,
    right: &StepJournalRecord,
) -> bool {
    match (left.goal_digest.as_deref(), right.goal_digest.as_deref()) {
        (Some(left_digest), Some(right_digest)) => left_digest == right_digest,
        (Some(left_digest), None) => left_digest == step_goal_digest(&right.goal),
        (None, Some(right_digest)) => step_goal_digest(&left.goal) == right_digest,
        (None, None) => left.goal == right.goal,
    }
}

pub(super) fn step_journal_path(state_path: &Path, step_id: Uuid) -> PathBuf {
    let parent = state_path
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let file_name = state_path
        .file_name()
        .map(|name| name.to_string_lossy())
        .unwrap_or_else(|| "state".into());
    parent
        .join(format!("{file_name}.step-journal"))
        .join(format!("{step_id}.jsonl"))
}

#[cfg(any(unix, windows))]
pub(super) fn step_journal_lock_path(state_path: &Path, step_id: Uuid) -> PathBuf {
    step_journal_path(state_path, step_id).with_extension("lock")
}

pub(super) fn read_step_journal(
    state_path: &Path,
    step_id: Uuid,
) -> Result<Option<StepJournalRecord>> {
    let path = step_journal_path(state_path, step_id);
    if !path.exists() {
        return Ok(None);
    }
    let data = std::fs::read_to_string(&path).map_err(|error| {
        OmegaError::Persist(format!("step journal read {}: {error}", path.display()))
    })?;
    if data.is_empty() || !data.ends_with('\n') {
        return Err(OmegaError::Persist(format!(
            "step journal {} has an incomplete trailing record",
            path.display()
        )));
    }

    let mut latest: Option<StepJournalRecord> = None;
    for (index, line) in data.lines().enumerate() {
        let record: StepJournalRecord = serde_json::from_str(line).map_err(|error| {
            OmegaError::Persist(format!(
                "malformed step journal {} at line {}: {error}",
                path.display(),
                index + 1
            ))
        })?;
        if let Some(previous) = latest.as_ref() {
            if !step_journal_records_have_same_goal(&record, previous) {
                return Err(OmegaError::Persist(format!(
                    "step journal {} changes the goal for an existing ID",
                    path.display()
                )));
            }
        }
        if record.step_id != step_id {
            return Err(OmegaError::Persist(format!(
                "step journal {} contains a mismatched step ID",
                path.display()
            )));
        }
        let valid_transition = match latest.as_ref() {
            None => record.attempt == 1 && record.status == StepJournalStatus::Started,
            Some(previous) if record.attempt == previous.attempt => matches!(
                (previous.status, record.status),
                (StepJournalStatus::Started, StepJournalStatus::Dispatching)
                    | (StepJournalStatus::Started, StepJournalStatus::NotExecuted)
                    | (StepJournalStatus::Dispatching, StepJournalStatus::Executed)
                    | (
                        StepJournalStatus::Dispatching,
                        StepJournalStatus::NotExecuted
                    )
                    | (StepJournalStatus::Executed, StepJournalStatus::Committed)
            ),
            Some(previous) => {
                record.attempt == previous.attempt.saturating_add(1)
                    && record.status == StepJournalStatus::Started
                    && matches!(
                        previous.status,
                        StepJournalStatus::Started | StepJournalStatus::NotExecuted
                    )
            }
        };
        if !valid_transition {
            return Err(OmegaError::Persist(format!(
                "invalid step journal transition in {} at line {}",
                path.display(),
                index + 1
            )));
        }
        latest = Some(record);
    }
    latest
        .map(Some)
        .ok_or_else(|| OmegaError::Persist(format!("step journal {} is empty", path.display())))
}

pub(super) fn append_step_journal(
    state_path: &Path,
    record: &StepJournalRecord,
    create_new: bool,
) -> Result<()> {
    let path = step_journal_path(state_path, record.step_id);
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    crate::private_fs::create_dir_all(parent).map_err(|error| {
        OmegaError::Persist(format!(
            "step journal directory {}: {error}",
            parent.display()
        ))
    })?;
    let mut options = crate::private_fs::open_options();
    options.write(true);
    if create_new {
        options.create_new(true);
    } else {
        options.create(true).append(true);
    }
    let mut file = options.open(&path).map_err(|error| {
        OmegaError::Persist(format!("step journal open {}: {error}", path.display()))
    })?;
    let line = serde_json::to_string(record).map_err(|error| {
        OmegaError::Persist(format!("step journal encode {}: {error}", path.display()))
    })?;
    writeln!(file, "{line}").map_err(|error| {
        OmegaError::Persist(format!("step journal write {}: {error}", path.display()))
    })?;
    file.sync_data().map_err(|error| {
        OmegaError::Persist(format!("step journal sync {}: {error}", path.display()))
    })
}

pub(super) fn fresh_step_id() -> Uuid {
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU32 = AtomicU32::new(1);
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64;
    // Process IDs are unavailable on some std targets, including WASI.
    // Combine wall-clock nanoseconds with a process-local sequence instead.
    let suffix = COUNTER.fetch_add(1, Ordering::Relaxed) as u64;
    Uuid::from_u128(((timestamp as u128) << 64) | suffix as u128)
}