omega-cognitive-kernel 1.3.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
use std::boxed::Box;
use std::collections::BTreeMap;

use crate::adaptive::state::AdaptiveStateMachine;
use crate::adaptive::types::{
    AdaptiveConfig, AdaptiveError, AdaptiveMode, ExecutionReceipt, FeedbackReceipt,
    FeedbackRequest, PolicySnapshot, ProposalRequest, ProposalResponse, RecoveryRecommendation,
};
use crate::error::{OmegaError, Result};
use crate::persist::{KernelSnapshot, StateStore, CURRENT_SCHEMA_VERSION};

/// Durable Phase 1 Adaptive Kernel Protocol v1 session backed by a [`StateStore`].
///
/// Phase 1 enforces **Keep / Shadow only** execution: no active parameter
/// mutations are permitted, every transition persists through [`StateStore`]
/// before committing in-memory state (fail-closed on storage errors), and
/// legacy `schema v6` snapshots migrate to `v7` without gaining active rights.
pub struct DurableAdaptiveSession {
    store: Box<dyn StateStore>,
    machine: AdaptiveStateMachine,
    snapshot: KernelSnapshot,
}

impl DurableAdaptiveSession {
    /// Opens a durable `Keep`-only adaptive session backed by `store`.
    pub fn open_keep(store: Box<dyn StateStore>, baseline_policy: PolicySnapshot) -> Result<Self> {
        Self::open_internal(
            store,
            AdaptiveConfig {
                mode: AdaptiveMode::Keep,
                ..AdaptiveConfig::default()
            },
            baseline_policy,
        )
    }

    /// Opens a durable `Shadow`-mode adaptive session backed by `store`.
    ///
    /// Even if `config.mode` requests [`AdaptiveMode::Active`], Phase 1 clamps
    /// the session to [`AdaptiveMode::Shadow`] so no executable parameter
    /// mutation occurs.
    pub fn open_shadow(
        store: Box<dyn StateStore>,
        config: AdaptiveConfig,
        baseline_policy: PolicySnapshot,
    ) -> Result<Self> {
        Self::open_internal(
            store,
            AdaptiveConfig {
                mode: AdaptiveMode::Shadow,
                ..config
            },
            baseline_policy,
        )
    }

    /// Opens a durable `Active`-mode adaptive session with explicit opt-in.
    ///
    /// Legacy snapshots (`schema < 7`) still fail closed with
    /// `active_permission_granted == false` and emit only `Keep` until migrated.
    pub fn open_active(
        store: Box<dyn StateStore>,
        config: AdaptiveConfig,
        baseline_policy: PolicySnapshot,
    ) -> Result<Self> {
        Self::open_internal(
            store,
            AdaptiveConfig {
                mode: AdaptiveMode::Active,
                ..config
            },
            baseline_policy,
        )
    }

    fn open_internal(
        store: Box<dyn StateStore>,
        config: AdaptiveConfig,
        baseline_policy: PolicySnapshot,
    ) -> Result<Self> {
        let (snapshot, machine) = match store.load_snapshot()? {
            Some(mut loaded) => {
                let original_version = loaded.version;
                loaded = loaded.migrate()?;
                let machine = if let Some(persisted) = loaded.adaptive_state.clone() {
                    AdaptiveStateMachine::from_persisted_state(config, persisted)
                        .map_err(|e| OmegaError::Persist(e.to_string()))?
                } else {
                    // An existing snapshot with no adaptive_state (including migrated v0-v6
                    // snapshots whose load_snapshot() already bumped version to v7) must
                    // never gain active permission implicitly.
                    let legacy_ver = original_version.min(CURRENT_SCHEMA_VERSION - 1);
                    AdaptiveStateMachine::from_legacy_snapshot(legacy_ver, config, baseline_policy)
                        .map_err(|e| OmegaError::Persist(e.to_string()))?
                };
                (loaded, machine)
            }
            None => {
                let machine = AdaptiveStateMachine::new(config, baseline_policy)
                    .map_err(|e| OmegaError::Persist(e.to_string()))?;
                let snapshot = KernelSnapshot {
                    adaptive_state: Some(machine.export_state()),
                    ..Default::default()
                };
                (snapshot, machine)
            }
        };

        Ok(Self {
            store,
            machine,
            snapshot,
        })
    }

    /// Returns a read-only view of the underlying protocol state machine.
    pub fn machine(&self) -> &AdaptiveStateMachine {
        &self.machine
    }

    /// Returns the loaded/migrated [`KernelSnapshot`] schema version.
    pub fn schema_version(&self) -> u32 {
        self.snapshot.version
    }

    /// Evaluates and durably persists a `propose` request (fail-closed on storage error).
    pub fn propose(
        &mut self,
        req: ProposalRequest,
    ) -> core::result::Result<ProposalResponse, AdaptiveSessionError> {
        let mut candidate = self.machine.clone();
        let response = candidate.propose(req)?;
        self.commit_machine(candidate)?;
        Ok(response)
    }

    /// Evaluates and durably persists an `acknowledge_applied` receipt.
    pub fn acknowledge_applied(
        &mut self,
        receipt: ExecutionReceipt,
    ) -> core::result::Result<PolicySnapshot, AdaptiveSessionError> {
        let mut candidate = self.machine.clone();
        let confirmed = candidate.acknowledge_applied(receipt)?;
        self.commit_machine(candidate)?;
        Ok(confirmed)
    }

    /// Evaluates and durably persists an external `feedback` request.
    pub fn feedback(
        &mut self,
        req: FeedbackRequest,
    ) -> core::result::Result<FeedbackReceipt, AdaptiveSessionError> {
        let mut candidate = self.machine.clone();
        let receipt = candidate.feedback(req)?;
        self.commit_machine(candidate)?;
        Ok(receipt)
    }

    /// Durably records an expired request tombstone so it can never re-execute across restarts.
    pub fn record_expired_tombstone(
        &mut self,
        request_id: impl Into<String>,
    ) -> core::result::Result<(), AdaptiveSessionError> {
        let mut candidate = self.machine.clone();
        candidate.record_expired_tombstone(request_id);
        self.commit_machine(candidate)?;
        Ok(())
    }

    /// Returns the currently confirmed parameter map (unchanged in Keep/Shadow modes).
    pub fn confirmed_params(&self) -> &BTreeMap<String, f64> {
        &self.machine.confirmed_policy().params
    }

    /// Returns the currently confirmed [`PolicySnapshot`].
    pub fn confirmed_policy(&self) -> &PolicySnapshot {
        self.machine.confirmed_policy()
    }

    /// Returns whether active adaptation permission is granted for this session.
    pub fn active_permission_granted(&self) -> bool {
        self.machine.active_permission_granted()
    }

    /// Produces a bounded recovery recommendation under a strictly newer version.
    pub fn recommend_recovery(
        &self,
        recovery_params: BTreeMap<String, f64>,
    ) -> core::result::Result<RecoveryRecommendation, AdaptiveSessionError> {
        Ok(self.machine.recommend_recovery(recovery_params)?)
    }

    fn commit_machine(
        &mut self,
        next_machine: AdaptiveStateMachine,
    ) -> core::result::Result<(), AdaptiveSessionError> {
        let mut next_snapshot = self.snapshot.clone();
        next_snapshot.version = CURRENT_SCHEMA_VERSION;
        next_snapshot.adaptive_state = Some(next_machine.export_state());
        self.store
            .save_snapshot(&next_snapshot)
            .map_err(|e| AdaptiveSessionError::Storage(e.to_string()))?;
        self.snapshot = next_snapshot;
        self.machine = next_machine;
        Ok(())
    }
}

/// Error returned by [`DurableAdaptiveSession`] distinguishing protocol and storage failures.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AdaptiveSessionError {
    /// Fail-closed protocol contract violation.
    Protocol(AdaptiveError),
    /// Underlying [`StateStore`] persistence failure; in-memory state was not mutated.
    Storage(String),
}

impl From<AdaptiveError> for AdaptiveSessionError {
    fn from(value: AdaptiveError) -> Self {
        Self::Protocol(value)
    }
}

impl std::fmt::Display for AdaptiveSessionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Protocol(err) => write!(f, "adaptive protocol error: {err}"),
            Self::Storage(msg) => write!(f, "adaptive storage error: {msg}"),
        }
    }
}

impl std::error::Error for AdaptiveSessionError {}