omega-cognitive-kernel 0.7.1

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

use chrono::{DateTime, Utc};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Modality {
    Text,
    Image,
    Audio,
    Structured,
    Internal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Observation {
    pub timestamp: DateTime<Utc>,
    pub modality: Modality,
    pub content: serde_json::Value,
    pub confidence: f64,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Prediction {
    pub expected: serde_json::Value,
    pub uncertainty: f64,
    pub horizon_secs: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Intent {
    pub goal: String,
    pub priority: f64,
    pub bias_from_memory: HashMap<String, f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    pub name: String,
    pub params: HashMap<String, serde_json::Value>,
    pub constraints_checked: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BanditConfig {
    /// Minimum decisions to keep an arm before considering a switch.
    pub min_dwell_steps: u64,
    /// Required UCB advantage over the incumbent arm.
    pub switch_margin: f64,
    /// Multiplier for rollback/safety-degradation signals in the UCB reward.
    pub rollback_penalty: f64,
    /// Cost charged to the destination arm when changing arms.
    pub switch_cost: f64,
}

impl Default for BanditConfig {
    fn default() -> Self {
        Self {
            min_dwell_steps: 3,
            switch_margin: 0.05,
            rollback_penalty: 0.35,
            switch_cost: 0.02,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum L2DecisionReason {
    InitialExplore,
    Exploit,
    Explore,
    Switched,
    DwellHold,
    MarginHold,
    SafetyOverride,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct L2DecisionRecord {
    pub selected_arm: usize,
    pub selected_bias: String,
    pub candidate_arm: usize,
    pub mean_reward: f64,
    /// Multiplicative exploration term of the selected arm.
    pub exploration_bonus: f64,
    /// UCB score of the selected arm; null while that arm is still unexplored.
    pub ucb_score: Option<f64>,
    pub candidate_ucb_score: Option<f64>,
    pub current_ucb_score: Option<f64>,
    pub reason: L2DecisionReason,
    pub dwell_steps: u64,
    pub dwell_suppressed: bool,
    pub margin_suppressed: bool,
    /// The committed L2 policy changed the original UCB candidate and its
    /// candidate was the action actually selected. Missing legacy records
    /// cannot claim a policy intervention.
    #[serde(default)]
    pub l2_policy_applied: bool,
    pub switched: bool,
    pub safety_override: bool,
    pub adjusted_reward: Option<f64>,
    pub rollback_count: u64,
    pub switch_cost_applied: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct L2Policy {
    pub prior: [f64; 2],
    pub beta: f64,
    pub alpha: f64,
    pub committed: bool,
    pub expert: usize,
    pub expert_probabilities: [f64; 4],
    pub gate_state: crate::l2::control::L2GateState,
    pub confidence: f64,
    /// Experimental spectral KL weighting. Disabled for legacy controllers.
    #[serde(default)]
    pub spectral_weighting: bool,
}
impl Default for L2Policy {
    fn default() -> Self {
        Self {
            prior: [0.5, 0.5],
            beta: 0.0,
            alpha: 0.0,
            committed: false,
            expert: 0,
            expert_probabilities: [0.25; 4],
            gate_state: crate::l2::control::L2GateState::Dormant,
            confidence: 0.0,
            spectral_weighting: false,
        }
    }
}
impl L2Policy {
    pub fn keep_l0() -> Self {
        Self::default()
    }

    /// The only value that may cross the L2 -> L0 commit boundary.
    ///
    /// This is deliberately a second validation at the consumer as well as at
    /// the producer. A proposal, an L0 dwell/margin hold, a dormant controller,
    /// KEEP_L0, a veto, and a malformed snapshot all collapse to exactly the
    /// same zero policy. Keeping this check here prevents a future producer
    /// from accidentally turning a diagnostic field into an intervention.
    pub fn effective(self) -> Self {
        let probabilities_sum = self.expert_probabilities.iter().sum::<f64>();
        let prior_sum = self.prior.iter().sum::<f64>();
        let valid = self.committed
            && self.gate_state == crate::l2::control::L2GateState::Active
            && self.expert > 0
            && self.expert < 4
            && self.alpha > 0.0
            && self.alpha <= 0.35
            && self.alpha.is_finite()
            && self.beta > 0.0
            && self.beta.is_finite()
            && self.confidence.is_finite()
            && (0.0..=1.0).contains(&self.confidence)
            && self.prior.iter().all(|p| p.is_finite() && *p > 0.0)
            && (prior_sum - 1.0).abs() < 1.0e-6
            && self
                .expert_probabilities
                .iter()
                .all(|p| p.is_finite() && *p > 0.0)
            && (probabilities_sum - 1.0).abs() < 1.0e-6;
        if valid {
            self
        } else {
            Self::default()
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct DecisionFeedback {
    pub l1_rollback: bool,
    pub safety_degradation: bool,
    /// Error improvement is a positive reward contribution.
    pub error_delta: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trajectory {
    pub observations: Vec<Observation>,
    pub predictions: Vec<Prediction>,
    pub actions: Vec<Action>,
    pub outcomes: Vec<serde_json::Value>,
    pub prediction_errors: Vec<f64>,
    pub meta: HashMap<String, serde_json::Value>,
}

/// Structured, safely-applied effect of a cognitive patch.
/// This is what actually changes L0 behavior — not the `code` string.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RuleEffect {
    /// Multiplies prediction error / uncertainty (1.0 = no change, lower = better).
    pub error_damping: f64,
    /// Additive preference scores for action names.
    pub action_preference: HashMap<String, f64>,
    /// Floor for reported uncertainty after damping.
    pub min_uncertainty: f64,
    /// Additive score bias toward "explore" (negative favors exploit/stabilize).
    #[serde(default)]
    pub explore_bonus: f64,
    /// Soft threshold for treating uncertainty as "high" (higher = more tolerant).
    #[serde(default = "default_risk_tolerance")]
    pub risk_tolerance: f64,
}

fn default_risk_tolerance() -> f64 {
    0.45
}

impl Default for RuleEffect {
    fn default() -> Self {
        Self {
            error_damping: 1.0,
            action_preference: HashMap::new(),
            min_uncertainty: 0.05,
            explore_bonus: 0.0,
            risk_tolerance: 0.45,
        }
    }
}

impl RuleEffect {
    pub const ALLOWED_ACTIONS: &'static [&'static str] =
        &["noop", "observe", "explore", "exploit", "stabilize"];

    pub fn sanitize(mut self) -> Self {
        self.error_damping = if self.error_damping.is_finite() {
            self.error_damping.clamp(0.2, 1.5)
        } else {
            1.0
        };
        self.min_uncertainty = if self.min_uncertainty.is_finite() {
            self.min_uncertainty.clamp(0.01, 0.5)
        } else {
            0.05
        };
        self.explore_bonus = if self.explore_bonus.is_finite() {
            self.explore_bonus.clamp(-1.5, 1.5)
        } else {
            0.0
        };
        self.risk_tolerance = if self.risk_tolerance.is_finite() {
            self.risk_tolerance.clamp(0.15, 0.85)
        } else {
            0.45
        };
        self.action_preference.retain(|k, v| {
            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) || !v.is_finite() {
                return false;
            }
            *v = v.clamp(-5.0, 5.0);
            true
        });
        self
    }

    pub fn validate_bounds(&self) -> Option<String> {
        if !(0.15..=2.0).contains(&self.error_damping) {
            return Some(format!(
                "error_damping {:.3} outside [0.15, 2.0]",
                self.error_damping
            ));
        }
        if !(0.0..=1.0).contains(&self.min_uncertainty) {
            return Some(format!(
                "min_uncertainty {:.3} outside [0.0, 1.0]",
                self.min_uncertainty
            ));
        }
        if !(-2.0..=2.0).contains(&self.explore_bonus) {
            return Some(format!(
                "explore_bonus {:.3} outside [-2.0, 2.0]",
                self.explore_bonus
            ));
        }
        if !(0.1..=0.9).contains(&self.risk_tolerance) {
            return Some(format!(
                "risk_tolerance {:.3} outside [0.1, 0.9]",
                self.risk_tolerance
            ));
        }
        for (k, v) in &self.action_preference {
            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) {
                return Some(format!("unknown action preference key: {k}"));
            }
            if !(-10.0..=10.0).contains(v) {
                return Some(format!("action preference {k}={v} outside [-10, 10]"));
            }
        }
        None
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CognitivePatch {
    pub patch_id: Uuid,
    pub description: String,
    pub code: String,
    pub target_module: String,
    pub expected_effect: String,
    pub risk_level: f64,
    pub created_at: DateTime<Utc>,
    pub effect: RuleEffect,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetaMetrics {
    pub complexity: f64,
    pub consistency: f64,
    pub predictive_power: f64,
    pub self_ref_stability: f64,
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone, Default)]
pub struct SystemState {
    pub active_code: HashMap<String, String>,
    pub highest_attractor: String,
    pub generative_base: Option<String>,
    pub last_trajectory_summary: Option<String>,
    pub avg_prediction_error: f64,
    pub total_steps: u64,
}