clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1: declarative Fractal Petri Net harness & TypedPetriNetKernel (Sprint 533, Sprint 551).
//!
//! The namespace-firing nets rebuilt the same place table and registered it by
//! hand. `PlaceSpec` plus `register_place_specs` turns that into one declaration.
//! `TypedPetriNetKernel` unifies runtime nets with exception trap routing.

use std::collections::BTreeSet;
use serde_json::Value;

use crate::cpn::mcard_token::{PlaceMCard, TokenMCard, TransitionMCard};
use crate::cpn::place_type_lattice::{PlaceRole, PlaceTypeBinding, PlaceTypeLattice};
use crate::cpn::token_namespace::{FiringReceiptMCard, MCardTokenNamespace};

/// One place and its lattice role.
#[derive(Debug, Clone)]
pub struct PlaceSpec<'a> {
    pub place_id: &'a str,
    pub type_expr: &'a str,
    pub role: PlaceRole,
    /// Binding-level type URI. `None` falls back to the place's own expression.
    pub binding_type_uri: Option<&'a str>,
}

impl<'a> PlaceSpec<'a> {
    pub fn new(place_id: &'a str, type_expr: &'a str, role: PlaceRole) -> Self {
        Self { place_id, type_expr, role, binding_type_uri: None }
    }

    /// Binds the place under an explicit type URI rather than its own expression.
    pub fn with_binding_type_uri(mut self, type_uri: &'a str) -> Self {
        self.binding_type_uri = Some(type_uri);
        self
    }
}

/// Builds one place from a spec. Use this for dynamic places too.
pub fn build_place(spec: &PlaceSpec<'_>) -> Result<PlaceMCard, String> {
    PlaceMCard::create(spec.place_id, spec.type_expr, None, spec.role.as_str(), Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3), None)
}

/// Builds and registers every place in a table, returning them in declaration order.
pub fn register_place_specs(
    namespace: &mut MCardTokenNamespace,
    specs: &[PlaceSpec<'_>],
) -> Result<Vec<PlaceMCard>, String> {
    let mut places = Vec::with_capacity(specs.len());
    for spec in specs {
        let place = build_place(spec)?;
        let binding = PlaceTypeBinding::new(
            place.clone(),
            spec.role,
            spec.binding_type_uri.map(|uri| uri.to_string()),
            None,
        );
        namespace.register_place(place.clone(), Some(binding));
        places.push(place);
    }
    Ok(places)
}

/// A sovereign typed Petri Net execution kernel (Sprint 551, INV-551).
#[derive(Debug, Clone)]
pub struct TypedPetriNetKernel {
    pub namespace: MCardTokenNamespace,
    pub lattice: PlaceTypeLattice,
    pub exception_place_id: String,
    token_counter: usize,
}

impl TypedPetriNetKernel {
    pub fn new(net_id: &str, exception_place_id: Option<&str>) -> Self {
        let exc_id = exception_place_id.unwrap_or("p_exception").to_string();
        let namespace = MCardTokenNamespace::new(net_id);
        let mut exc_set = BTreeSet::new();
        exc_set.insert(exc_id.clone());
        let lattice = PlaceTypeLattice::from_net(&[], &[], Some(&exc_set));
        Self {
            namespace,
            lattice,
            exception_place_id: exc_id,
            token_counter: 0,
        }
    }

    pub fn rebuild_lattice(&mut self) -> Result<PlaceTypeLattice, String> {
        let places: Vec<PlaceMCard> = self.namespace.places.values().cloned().collect();
        let transitions: Vec<TransitionMCard> = self.namespace.transitions.values().cloned().collect();
        let mut exc_set = BTreeSet::new();
        exc_set.insert(self.exception_place_id.clone());
        self.lattice = PlaceTypeLattice::from_net(&places, &transitions, Some(&exc_set));
        Ok(self.lattice.clone())
    }

    pub fn deposit_token(
        &mut self,
        place_id: &str,
        payload: Value,
        color_type: &str,
        handle: Option<&str>,
    ) -> Result<TokenMCard, String> {
        self.token_counter += 1;
        let token_id = match handle {
            Some(h) => h.to_string(),
            None => format!("tok_{}_{}", place_id, self.token_counter),
        };
        let token = TokenMCard::from_payload(
            payload,
            color_type,
            &token_id,
            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
            None,
        )?;
        self.namespace.deposit_token(place_id, token.clone(), None, None);
        Ok(token)
    }

    pub fn fire_with_exception_trap<F>(
        &mut self,
        transition: &TransitionMCard,
        handler: F,
    ) -> Result<FiringReceiptMCard, String>
    where
        F: Fn(&[Value]) -> Result<Value, String>,
    {
        if !self.namespace.transitions.contains_key(&transition.transition_id) {
            self.namespace.register_transition(transition.clone());
        }
        let (receipt, _) = self.namespace.fire_in_cordis_fiber(
            &transition.transition_id,
            None,
            Some(&self.exception_place_id),
            None,
            handler,
            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
        )?;
        Ok(receipt)
    }
}