omega-cognitive-kernel 0.15.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
#[allow(unused_imports)]
use crate::prelude::*;

pub mod bandit_decision;
/// Decision-maker traits and policies for selecting actions.
pub mod decision;
/// Action-execution traits and synchronous or asynchronous adapters.
pub mod executor;
/// Predictors that combine model-based and lightweight learned dynamics.
pub mod hybrid_predictor;
/// Observation traits and adapters for files, directories, and HTTP sources.
pub mod observer;
/// Prediction traits and model implementations for world state.
pub mod predictor;

// Re-export async traits and adapters when async feature is enabled
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use observer::{
    AsyncDirSnapshotObserver, AsyncFileObserver, AsyncHttpObserver, AsyncObserver,
    AsyncObserverAdapter,
};

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use executor::{AsyncExecutor, AsyncExecutorAdapter, AsyncLoggingExecutor};

pub use hybrid_predictor::{HybridWorldModel, HybridWorldPredictor, TinyAttentionPredictor};

use crate::error::Result;
use crate::l1::learner::Learner;
use crate::memory::MemoryFacade;
use crate::types::*;
use alloc::collections::BTreeMap;

/// Data structure representing L0 world layer.
pub struct L0WorldLayer<O, P, D, E>
where
    O: observer::Observer,
    P: predictor::Predictor,
    D: decision::DecisionMaker,
    E: executor::Executor,
{
    /// Observer for this value.
    pub observer: O,
    /// Predictor for this value.
    pub predictor: P,
    /// Decision for this value.
    pub decision: D,
    /// Executor for this value.
    pub executor: E,
    /// Memory for this value.
    pub memory: MemoryFacade,
    /// Post-step learning (case/strategy/CAS + idle decay).
    pub learner: Learner,
}

impl<O, P, D, E> L0WorldLayer<O, P, D, E>
where
    O: observer::Observer,
    P: predictor::Predictor,
    D: decision::DecisionMaker,
    E: executor::Executor,
{
    /// Performs step for this type.
    pub fn step(
        &mut self,
        intent: &Intent,
        constraints: &BTreeMap<String, f64>,
    ) -> Result<Trajectory> {
        self.step_with_executor_hooks(intent, constraints, || Ok(()), || Ok(()))
    }

    pub(crate) fn step_with_executor_hooks<Before, After>(
        &mut self,
        intent: &Intent,
        constraints: &BTreeMap<String, f64>,
        mut before_executor: Before,
        mut after_executor_success: After,
    ) -> Result<Trajectory>
    where
        Before: FnMut() -> Result<()>,
        After: FnMut() -> Result<()>,
    {
        let observations = self.observer.observe()?;
        let mem_ctx = self.memory.retrieve(&intent.goal, 5)?;
        let predictions = self.predictor.predict(&observations, &mem_ctx)?;
        let actions = self
            .decision
            .decide(intent, &predictions, constraints, &mem_ctx)?;
        before_executor()?;
        let outcomes = self.executor.execute(&actions)?;
        after_executor_success()?;
        let errors = self.compute_errors(&predictions, &actions);

        let mut meta = BTreeMap::new();
        meta.insert(
            "goal".into(),
            serde_json::Value::String(intent.goal.clone()),
        );
        meta.insert(
            "damping".into(),
            serde_json::json!(self.memory.cognitive_effect.error_damping),
        );
        if let Some(a) = actions.first() {
            meta.insert("chosen_action".into(), serde_json::json!(a.name));
        }

        let traj = Trajectory {
            observations,
            predictions,
            actions,
            outcomes,
            prediction_errors: errors,
            meta,
        };

        // Learning path owned by Learner (update + idle strategy decay).
        self.learner.update(&mut self.memory, &traj)?;
        Ok(traj)
    }

    /// Error tracks predictor uncertainty, with a small action-quality term.
    fn compute_errors(&self, preds: &[Prediction], actions: &[Action]) -> Vec<f64> {
        let action_penalty = match actions.first().map(|a| a.name.as_str()) {
            Some("stabilize") => -0.05,
            Some("exploit") => -0.02,
            Some("explore") => 0.03,
            _ => 0.0,
        };
        preds
            .iter()
            .map(|p| (p.uncertainty + action_penalty).clamp(0.05, 1.0))
            .collect()
    }
}