clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 5 Epistemic Learning Petri Net with Cordis HMR (Sprint 518, GAP-18, INV-518).
//! Canonical Path: kernel/clm_rust_core/src/layer5/petri_learning.rs

use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::cpn::mcard_token::{PlaceMCard, TokenMCard, TransitionMCard};
use crate::cpn::place_type_lattice::{PlaceRole, PlaceTypeLattice};
use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
use crate::domain::BailVerdict;
use crate::layer1::fractal_net_harness::{register_place_specs, PlaceSpec};

pub type EpistemicPlaceMCard = PlaceMCard;
pub type LearningTransitionPCard = TransitionMCard;

/// Result of firing a Layer 5 epistemic learning transition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LearningCycleResult {
    pub assimilated: bool,
    pub trapped_to_falsified: bool,
    pub delta_e: f64,
    pub crystallized_pcard_token: TokenMCard,
    pub marking: MCardMarking,
    pub receipt: FiringReceiptMCard,
    pub hmr_trace: Vec<String>,
}

/// Layer 5 Meta-Circular Loop Gamma modeled as an Epistemic Petri Net with Cordis HMR.
pub struct Layer5EpistemicLearningNet {
    pub namespace: MCardTokenNamespace,
    pub lattice: PlaceTypeLattice,
    pub active_instincts: HashMap<String, String>,
}

impl Default for Layer5EpistemicLearningNet {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer5EpistemicLearningNet {
    /// Creates a new `Layer5EpistemicLearningNet` with 4 canonical epistemic places.
    pub fn new() -> Self {
        let mut namespace = MCardTokenNamespace::new("layer5_learning");

        // Sprint 533: place table replaces four build-and-register blocks.
        // Each binding keeps its explicit type URI, as before.
        let specs = [
            PlaceSpec::new("p_untrained", crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_UNTRAINED, PlaceRole::InitialBottom)
                .with_binding_type_uri(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_UNTRAINED),
            PlaceSpec::new("p_candidate", crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_CANDIDATE, PlaceRole::Intermediate)
                .with_binding_type_uri(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_CANDIDATE),
            PlaceSpec::new("p_assimilated", crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_ASSIMILATED, PlaceRole::TerminalTop)
                .with_binding_type_uri(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_ASSIMILATED),
            PlaceSpec::new("p_falsified_exception", crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_FALSIFIED_TRAP, PlaceRole::Exception)
                .with_binding_type_uri(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_FALSIFIED_TRAP),
        ];
        let places = register_place_specs(&mut namespace, &specs).expect("valid learning places");

        let mut exc_ids = BTreeSet::new();
        exc_ids.insert("p_falsified_exception".to_string());
        let lattice = PlaceTypeLattice::from_net(&places, &[], Some(&exc_ids));

        Self {
            namespace,
            lattice,
            active_instincts: HashMap::new(),
        }
    }

    /// Deposits an observation `TokenMCard` into `p_untrained`.
    pub fn seed_observation(
        &mut self,
        marking: &MCardMarking,
        observation_payload: Value,
    ) -> (MCardMarking, TokenMCard) {
        let tok = TokenMCard::from_payload(
            observation_payload,
            crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_UNTRAINED,
            "tok_obs",
            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
            None,
        ).expect("observation token");

        let mut next_marking = marking.clone();
        next_marking.append("p_untrained", tok.qualified_hash());
        self.namespace.tokens_by_ref.insert(tok.qualified_hash(), tok.clone());
        self.namespace.records_by_ref.insert(tok.qualified_hash(), tok.card.clone());
        self.namespace.marking = next_marking.clone();
        (next_marking, tok)
    }

    /// Executes a `LearningTransitionPCard` gated by `delta_e > 0`.
    pub fn run_learning_transition(
        &mut self,
        marking: &MCardMarking,
        observation_token: &TokenMCard,
        skill_handle: &str,
        baseline_fitness: f64,
        candidate_fitness: f64,
        synthesized_guard: &str,
    ) -> LearningCycleResult {
        let delta_e = ((candidate_fitness - baseline_fitness) * 1_000_000.0).round() / 1_000_000.0;
        let tid = format!("t_learn:{skill_handle}");

        let transition = TransitionMCard::create(
            &tid,
            vec!["p_untrained".to_string()],
            vec!["p_assimilated".to_string()],
            crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_UNTRAINED,
            crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_EPISTEMIC_ASSIMILATED,
            Some(BTreeMap::new()),
            &format!("delta_e({candidate_fitness} - {baseline_fitness}) > 0"),
            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
            None,
        ).expect("learning transition");

        self.namespace.register_transition(transition);
        self.namespace.marking = marking.clone();
        self.namespace.tokens_by_ref.insert(observation_token.qualified_hash(), observation_token.clone());
        self.namespace.records_by_ref.insert(observation_token.qualified_hash(), observation_token.card.clone());

        let prev_ref = self.active_instincts.get(skill_handle).cloned();
        let guard_str = synthesized_guard.to_string();
        let handle_str = skill_handle.to_string();

        let res = self.namespace.fire_in_cordis_fiber(
            &tid,
            None,
            Some("p_falsified_exception"),
            None,
            move |_raw_inputs| {
                if delta_e <= 0.0 {
                    return Err(format!("Epistemic hypothesis falsified for '{handle_str}': delta_e={delta_e} <= 0"));
                }
                Ok(json!({
                    "kind": "crystallized_pcard",
                    "skill_handle": handle_str,
                    "synthesized_guard": guard_str,
                    "delta_e": delta_e,
                }))
            },
            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
        );

        let (receipt, verdict) = res.expect("fiber execution");
        if matches!(verdict, BailVerdict::Pass) {
            let out_tokens = self.namespace.get_place_tokens("p_assimilated");
            let out_tok = out_tokens.last().cloned().unwrap_or_else(|| observation_token.clone());
            self.active_instincts.insert(skill_handle.to_string(), out_tok.qualified_hash());
            LearningCycleResult {
                assimilated: true,
                trapped_to_falsified: false,
                delta_e,
                crystallized_pcard_token: out_tok,
                marking: self.namespace.marking.clone(),
                receipt,
                hmr_trace: vec![
                    "OLD_FIBER_UNLOADING".to_string(),
                    "OLD_FIBER_DISPOSED".to_string(),
                    "NEW_FIBER_ACTIVE".to_string(),
                ],
            }
        } else {
            if let Some(prev) = prev_ref {
                self.active_instincts.insert(skill_handle.to_string(), prev);
            } else {
                self.active_instincts.remove(skill_handle);
            }
            let exc_tokens = self.namespace.get_place_tokens("p_falsified_exception");
            let exc_tok = exc_tokens.last().cloned().unwrap_or_else(|| observation_token.clone());
            LearningCycleResult {
                assimilated: false,
                trapped_to_falsified: true,
                delta_e,
                crystallized_pcard_token: exc_tok,
                marking: self.namespace.marking.clone(),
                receipt,
                hmr_trace: vec![
                    "CANDIDATE_FIBER_ABORTED".to_string(),
                    "PREVIOUS_FIBER_PRESERVED".to_string(),
                ],
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_layer5_epistemic_learning() {
        let mut net = Layer5EpistemicLearningNet::new();
        let (m0, tok0) = net.seed_observation(&net.namespace.marking.clone(), json!({ "sensor_reading": 42.0 }));
        assert_eq!(net.namespace.get_place_tokens("p_untrained").len(), 1);

        let res1 = net.run_learning_transition(
            &m0,
            &tok0,
            "adaptive_sort",
            0.5,
            0.85,
            "len(arr) > 10 -> quicksort",
        );
        assert!(res1.assimilated);
        assert!(!res1.trapped_to_falsified);
        assert_eq!(res1.delta_e, 0.35);
        assert_eq!(
            res1.hmr_trace,
            vec!["OLD_FIBER_UNLOADING", "OLD_FIBER_DISPOSED", "NEW_FIBER_ACTIVE"]
        );
        assert!(net.active_instincts.contains_key("adaptive_sort"));

        let (m1, tok1) = net.seed_observation(&res1.marking, json!({ "sensor_reading": 99.0 }));
        let res2 = net.run_learning_transition(
            &m1,
            &tok1,
            "adaptive_sort",
            0.9,
            0.7,
            "bogus_guard",
        );
        assert!(!res2.assimilated);
        assert!(res2.trapped_to_falsified);
        assert_eq!(res2.delta_e, -0.2);
        assert_eq!(
            res2.hmr_trace,
            vec!["CANDIDATE_FIBER_ABORTED", "PREVIOUS_FIBER_PRESERVED"]
        );
        assert_eq!(
            net.active_instincts.get("adaptive_sort"),
            Some(&res1.crystallized_pcard_token.qualified_hash())
        );
    }
}