omega-cognitive-kernel 1.0.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
//! Stable v1 runtime contracts for the five-signal kernel boundary.
//!
//! The contracts in this module deliberately contain no runtime algorithm. They
//! are the shared vocabulary between the memory, bridge, and training domains.
//! Concrete implementations remain owned by the host application or by the
//! corresponding domain module.

use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

/// A single state/action/result observation owned by the kernel runtime.
///
/// The default `Action` and `Outcome` types keep the public spelling
/// `Experience<State>` convenient while allowing strongly typed integrations
/// to use `Experience<State, Action, Outcome>` without maintaining shadow state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Experience<State, Action = String, Outcome = String> {
    /// State observed before the action.
    pub state: State,
    /// Action selected or executed for this experience.
    pub action: Action,
    /// Result reported by the executor or host.
    pub outcome: Outcome,
    /// Stable episode identifier, when the host groups experiences into episodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub episode_id: Option<String>,
}

impl<State, Action, Outcome> Experience<State, Action, Outcome> {
    /// Creates an experience from one state, action, and observed outcome.
    pub fn new(state: State, action: Action, outcome: Outcome) -> Self {
        Self {
            state,
            action,
            outcome,
            episode_id: None,
        }
    }

    /// Associates the experience with an episode without changing its facts.
    pub fn in_episode(mut self, episode_id: impl Into<String>) -> Self {
        self.episode_id = Some(episode_id.into());
        self
    }
}

/// The only five lifecycle signals accepted by a v1 runtime boundary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Signal<State, Action = String, Outcome = String> {
    /// Read memory and ask the bridge to coordinate the next action.
    PreAct {
        /// Current state supplied by the host.
        state: State,
    },
    /// Record an executed result and make it available to training.
    PostAct {
        /// The completed state/action/outcome fact.
        experience: Experience<State, Action, Outcome>,
    },
    /// Close an episode and trigger episode-level evaluation or learning.
    EpisodeFinish {
        /// Stable episode identifier.
        episode_id: String,
        /// Experiences belonging to the completed episode.
        experiences: Vec<Experience<State, Action, Outcome>>,
    },
    /// Apply an audited, boundary-checked human or rule intervention.
    Intervention {
        /// State at which the intervention was requested.
        state: State,
        /// Action or policy value affected by the intervention.
        action: Action,
        /// Mandatory reason retained for auditability.
        reason: String,
    },
    /// Accept an external evaluation as a learning signal, not a self-evaluation.
    Feedback {
        /// Experience being evaluated.
        experience: Experience<State, Action, Outcome>,
        /// External score supplied by the evaluator.
        score: f64,
    },
}

/// Memory-domain contract for runtime state and experience persistence.
///
/// Implementations may use a bounded ring, a database, or a snapshot-backed
/// store. The kernel contract only requires that the same experience is used by
/// persistence, audit, and training consumers.
pub trait Memory<State, Action = String, Outcome = String> {
    /// Implementation-specific failure type.
    type Error;

    /// Records one experience as the canonical fact for downstream consumers.
    fn record(&mut self, experience: Experience<State, Action, Outcome>)
        -> Result<(), Self::Error>;

    /// Returns the number of retained experiences.
    fn len(&self) -> usize;

    /// Returns whether no experience is currently retained.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Bridge-domain contract for coordinating the existing control plane.
///
/// L0/L1/L2, `RuleEffect`, and `ControlDirective` implementations belong behind
/// this boundary; this trait does not prescribe or duplicate their algorithms.
pub trait Bridge<State, Action = String> {
    /// Implementation-specific failure type.
    type Error;

    /// Coordinates a pre-action state into a host-facing action.
    fn pre_act(&mut self, state: &State) -> Result<Action, Self::Error>;

    /// Applies a boundary-checked intervention and returns the controlled action.
    fn intervene(
        &mut self,
        state: &State,
        action: Action,
        reason: &str,
    ) -> Result<Action, Self::Error>;
}

/// Training-domain contract for consuming the unified experience stream.
///
/// This is intentionally an orchestration contract. Concrete training
/// algorithms remain outside the kernel and can implement this trait.
pub trait Training<State, Action = String, Outcome = String> {
    /// Implementation-specific failure type.
    type Error;

    /// Consumes one post-action experience.
    fn post_act(
        &mut self,
        experience: &Experience<State, Action, Outcome>,
    ) -> Result<(), Self::Error>;

    /// Consumes all experiences at the end of an episode.
    fn episode_finish(
        &mut self,
        episode_id: &str,
        experiences: &[Experience<State, Action, Outcome>],
    ) -> Result<(), Self::Error>;

    /// Consumes an externally supplied evaluation score.
    fn feedback(
        &mut self,
        experience: &Experience<State, Action, Outcome>,
        score: f64,
    ) -> Result<(), Self::Error>;
}

/// Compile-time marker for implementations that expose the unified signal boundary.
pub trait SignalHandler<State, Action = String, Outcome = String> {
    /// Implementation-specific failure type.
    type Error;

    /// Processes exactly one lifecycle signal.
    fn handle_signal(&mut self, signal: Signal<State, Action, Outcome>) -> Result<(), Self::Error>;
}

#[cfg(test)]
mod tests {
    use super::{Experience, Signal};
    use alloc::string::String;
    use alloc::vec;

    #[test]
    fn signal_round_trip_preserves_experience_facts() {
        let experience =
            Experience::new(String::from("s0"), String::from("a0"), String::from("ok"))
                .in_episode("episode-1");
        let signal = Signal::PostAct { experience };
        let encoded = serde_json::to_string(&signal).expect("signal serializes");
        let decoded: Signal<String> = serde_json::from_str(&encoded).expect("signal deserializes");
        assert_eq!(decoded, signal);
    }

    #[test]
    fn episode_finish_is_a_single_signal_with_ordered_facts() {
        let facts = vec![
            Experience::new(String::from("s0"), String::from("a0"), String::from("ok")),
            Experience::new(String::from("s1"), String::from("a1"), String::from("done")),
        ];
        let signal = Signal::EpisodeFinish {
            episode_id: String::from("episode-1"),
            experiences: facts,
        };
        match signal {
            Signal::EpisodeFinish { experiences, .. } => assert_eq!(experiences.len(), 2),
            _ => panic!("unexpected signal variant"),
        }
    }
}