clm-kernel 0.0.10

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 4 GUI / Web / Trellis Hypermedia Navigation Petri Net (Sprint 518, GAP-18, INV-518).
//! Canonical Path: kernel/clm_rust_core/src/layer4/petri_navigation.rs

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

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

pub type ViewPlaceMCard = PlaceMCard;
pub type NavigationTransitionPCard = TransitionMCard;
pub type SessionTokenMCard = TokenMCard;

/// Outcome of a Layer 4 Trellis navigation transition (`t_nav`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NavigationResult {
    pub navigated: bool,
    pub trapped_to_error_modal: bool,
    pub current_view_place_id: String,
    pub session_token: SessionTokenMCard,
    pub marking: MCardMarking,
    pub receipt: FiringReceiptMCard,
    pub continuation_trace: Vec<String>,
}

/// Stotts & Furuta Trellis Hypermedia Petri Net for Layer 4 GUI / Web / CLI navigation.
pub struct Layer4TrellisNavigationNet {
    pub namespace: MCardTokenNamespace,
    pub lattice: PlaceTypeLattice,
    pub links: HashMap<(String, String), String>,
}

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

impl Layer4TrellisNavigationNet {
    /// Creates a new `Layer4TrellisNavigationNet` with `p_error_modal` exception trap.
    pub fn new() -> Self {
        let mut namespace = MCardTokenNamespace::new("layer4_navigation");

        let err_modal = PlaceMCard::create(
            "p_error_modal",
            "clm://type/view/error_modal",
            None,
            "Exception",
            Some("blake3"),
            None,
        ).expect("error modal place");

        let err_binding = PlaceTypeBinding::new(
            err_modal.clone(),
            PlaceRole::Exception,
            Some("clm://type/view/error_modal".to_string()),
            None,
        );
        namespace.register_place(err_modal.clone(), Some(err_binding));

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

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

    pub fn rebuild_lattice(&mut self) {
        let places: Vec<PlaceMCard> = self.namespace.places.values().cloned().collect();
        let transitions: Vec<TransitionMCard> = self.namespace.transitions.values().cloned().collect();
        let mut exc_ids = BTreeSet::new();
        exc_ids.insert("p_error_modal".to_string());
        self.lattice = PlaceTypeLattice::from_net(&places, &transitions, Some(&exc_ids));
    }

    /// Registers a Web Page / View as a `ViewPlaceMCard`.
    pub fn register_view_place(
        &mut self,
        place_id: &str,
        route_uri: &str,
        role: PlaceRole,
        _supertypes: Vec<String>,
    ) -> ViewPlaceMCard {
        let role_str = match role {
            PlaceRole::InitialBottom => "InitialBottom",
            PlaceRole::Intermediate => "Intermediate",
            PlaceRole::TerminalTop => "TerminalTop",
            PlaceRole::Exception => "Exception",
        };
        let place = PlaceMCard::create(
            place_id,
            route_uri,
            None,
            role_str,
            Some("blake3"),
            None,
        ).expect("view place");

        let binding = PlaceTypeBinding::new(
            place.clone(),
            role,
            Some(route_uri.to_string()),
            None,
        );
        self.namespace.register_place(place.clone(), Some(binding));
        self.rebuild_lattice();
        place
    }

    /// Registers a hyperlink / UI command as a `NavigationTransitionPCard`.
    pub fn register_hyperlink(
        &mut self,
        from_place_id: &str,
        action_name: &str,
        to_place_id: &str,
    ) -> NavigationTransitionPCard {
        self.links.insert(
            (from_place_id.to_string(), action_name.to_string()),
            to_place_id.to_string(),
        );

        let tid = format!("t_nav:{from_place_id}:{action_name}->{to_place_id}");
        let transition = TransitionMCard::create(
            &tid,
            vec![from_place_id.to_string()],
            vec![to_place_id.to_string()],
            "clm://type/session/active",
            "clm://type/session/active",
            Some(BTreeMap::new()),
            &format!("hyperlink({from_place_id}, {action_name}) -> {to_place_id}"),
            Some("blake3"),
            None,
        ).expect("navigation transition");

        self.namespace.register_transition(transition.clone());
        self.rebuild_lattice();
        transition
    }

    /// Creates a `SessionTokenMCard` at `entry_place_id`.
    pub fn start_session(
        &mut self,
        entry_place_id: &str,
        session_id: &str,
        sponsor_did: Option<&str>,
    ) -> (MCardMarking, SessionTokenMCard) {
        let payload = json!({
            "current_place": entry_place_id,
            "history": [entry_place_id],
            "session_id": session_id,
            "sponsor_did": sponsor_did.unwrap_or("did:key:z6MkUserSession"),
        });
        let tok = TokenMCard::from_payload(
            payload,
            "clm://type/session/active",
            "tok_session",
            Some("blake3"),
            None,
        ).expect("session token");

        let mut marking = self.namespace.marking.clone();
        marking.append(entry_place_id, 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 = marking.clone();
        (marking, tok)
    }

    /// Navigates from `from_place_id` via `action_name` inside a Delimited Continuation Fiber.
    pub fn click_hyperlink(
        &mut self,
        marking: &MCardMarking,
        from_place_id: &str,
        action_name: &str,
        session_token: &SessionTokenMCard,
    ) -> NavigationResult {
        let target_opt = self.links.get(&(from_place_id.to_string(), action_name.to_string())).cloned();
        let transition_id = match &target_opt {
            Some(to_pid) => format!("t_nav:{from_place_id}:{action_name}->{to_pid}"),
            None => {
                let fallback_id = format!("t_nav_invalid:{from_place_id}:{action_name}");
                let fallback_t = TransitionMCard::create(
                    &fallback_id,
                    vec![from_place_id.to_string()],
                    vec![from_place_id.to_string()],
                    "clm://type/session/active",
                    "clm://type/session/active",
                    Some(BTreeMap::new()),
                    &format!("invalid_link({from_place_id}, {action_name})"),
                    Some("blake3"),
                    None,
                ).expect("fallback transition");
                self.namespace.register_transition(fallback_t);
                fallback_id
            }
        };

        self.namespace.marking = marking.clone();
        self.namespace.tokens_by_ref.insert(session_token.qualified_hash(), session_token.clone());
        self.namespace.records_by_ref.insert(session_token.qualified_hash(), session_token.card.clone());

        let target_clone = target_opt.clone();
        let action_str = action_name.to_string();
        let from_str = from_place_id.to_string();

        let res = self.namespace.fire_in_cordis_fiber(
            &transition_id,
            None,
            Some("p_error_modal"),
            None,
            move |raw_inputs| {
                let Some(tgt) = &target_clone else {
                    return Err(format!("Undefined hyperlink '{action_str}' from '{from_str}'"));
                };
                let prev_data = &raw_inputs[0];
                let mut history = prev_data.get("history")
                    .and_then(|h| h.as_array())
                    .cloned()
                    .unwrap_or_default();
                history.push(json!(tgt));
                Ok(json!({
                    "current_place": tgt,
                    "history": history,
                    "session_id": prev_data.get("session_id").and_then(|s| s.as_str()).unwrap_or("session"),
                    "sponsor_did": prev_data.get("sponsor_did").and_then(|s| s.as_str()).unwrap_or(""),
                }))
            },
            Some("blake3"),
        );

        let (receipt, verdict) = res.expect("fiber execution");
        if matches!(verdict, BailVerdict::Pass) && target_opt.is_some() {
            let target_pid = target_opt.unwrap();
            let new_tokens = self.namespace.get_place_tokens(&target_pid);
            let out_tok = new_tokens.last().cloned().unwrap_or_else(|| session_token.clone());
            NavigationResult {
                navigated: true,
                trapped_to_error_modal: false,
                current_view_place_id: target_pid,
                session_token: out_tok,
                marking: self.namespace.marking.clone(),
                receipt,
                continuation_trace: vec![
                    "SUSPENDED".to_string(),
                    "LOADING".to_string(),
                    "ACTIVE".to_string(),
                    "SUSPENDED".to_string(),
                ],
            }
        } else {
            let err_tokens = self.namespace.get_place_tokens("p_error_modal");
            let err_tok = err_tokens.last().cloned().unwrap_or_else(|| session_token.clone());
            NavigationResult {
                navigated: false,
                trapped_to_error_modal: true,
                current_view_place_id: "p_error_modal".to_string(),
                session_token: err_tok,
                marking: self.namespace.marking.clone(),
                receipt,
                continuation_trace: vec![
                    "SUSPENDED".to_string(),
                    "LOADING".to_string(),
                    "ACTIVE".to_string(),
                    "DISPOSED".to_string(),
                ],
            }
        }
    }
}

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

    #[test]
    fn test_layer4_trellis_navigation() {
        let mut net = Layer4TrellisNavigationNet::new();
        net.register_view_place("p_home_view", "clm://type/view/home", PlaceRole::Intermediate, vec![]);
        net.register_view_place("p_settings_view", "clm://type/view/settings", PlaceRole::Intermediate, vec![]);
        net.register_hyperlink("p_home_view", "open_settings", "p_settings_view");

        let (marking, session_tok) = net.start_session("p_home_view", "sess_01", None);
        assert_eq!(net.namespace.get_place_tokens("p_home_view").len(), 1);

        let res1 = net.click_hyperlink(&marking, "p_home_view", "open_settings", &session_tok);
        assert!(res1.navigated);
        assert!(!res1.trapped_to_error_modal);
        assert_eq!(res1.current_view_place_id, "p_settings_view");
        assert_eq!(
            res1.continuation_trace,
            vec!["SUSPENDED", "LOADING", "ACTIVE", "SUSPENDED"]
        );

        let res2 = net.click_hyperlink(&res1.marking, "p_settings_view", "undefined_action", &res1.session_token);
        assert!(!res2.navigated);
        assert!(res2.trapped_to_error_modal);
        assert_eq!(res2.current_view_place_id, "p_error_modal");
        assert_eq!(
            res2.continuation_trace,
            vec!["SUSPENDED", "LOADING", "ACTIVE", "DISPOSED"]
        );
    }
}