clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1 Bounded Place Type Lattice & Exception Trap Routing (Sprint 508).
//!
//! Implements:
//! - `PlaceRole`: `InitialBottom` (⊥), `Intermediate` (τ_mid), `Exception` (τ_exception), `TerminalTop` (⊤)
//! - `PlaceTypeBinding`: Associates a `PlaceMCard` with a Layer 0 `TypeLattice` URI, MISU identity
//!   precondition (`verifyIdentity ⊓ φ`), and Cordis `BooleanPCard` (`X -> 2`).
//! - `PlaceTypeLattice`: Tarjan SCC condensation + Bounded Lattice `(P, ⊑, ⊔, ⊓, ⊥, τ_mid, τ_exception, ⊤)`.

use crate::layer0::vocabulary_types::{TYPE_URI_CLM_TYPE};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::cpn::mcard_token::{check_type_expr, PlaceMCard, TokenMCard};
use crate::domain::BailVerdict;

/// Virtual Bottom identifier when multiple initial places exist.
pub const VIRTUAL_BOTTOM: &str = "__bot__";
/// Virtual Top identifier when multiple terminal places exist.
pub const VIRTUAL_TOP: &str = "__top__";

/// Structural role of a Place within the Bounded Place Type Lattice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum PlaceRole {
    /// Initial entry place (`⊥`).
    InitialBottom,
    /// Intermediate execution place (`τ_mid`).
    Intermediate,
    /// Dedicated exception trap place (`τ_exception`).
    Exception,
    /// Terminal completion place (`⊤`).
    TerminalTop,
}

impl PlaceRole {
    /// Returns the canonical string representation of the `PlaceRole`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::InitialBottom => "InitialBottom",
            Self::Intermediate => "Intermediate",
            Self::Exception => "Exception",
            Self::TerminalTop => "TerminalTop",
        }
    }
}

fn normalize_type_uri(type_uri: Option<&str>, fallback_expr: &str) -> String {
    let Some(raw) = type_uri else {
        return fallback_expr.to_string();
    };
    let cleaned = raw.trim();
    // Sprint 531: singular and plural prefixes are the same namespace.
    let suffix_opt = cleaned
        .strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
        .or_else(|| cleaned.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE));
    if let Some(suffix) = suffix_opt {
        let low = suffix.trim().to_lowercase();
        return match low.as_str() {
            "any" => "any".to_string(),
            "int" | "integer" => "int".to_string(),
            "str" | "string" => "str".to_string(),
            "structured" | "dict" => "structured".to_string(),
            "exception-token" | "exception" => "exception".to_string(),
            _ => low,
        };
    }
    cleaned.to_string()
}

pub fn format_canonical_type_uri(type_expr: &str) -> String {
    let normalized = normalize_type_uri(Some(type_expr), type_expr);
    if normalized.starts_with(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE) {
        normalized
    } else {
        format!("{TYPE_URI_CLM_TYPE}{normalized}")
    }
}

/// Associates a `PlaceMCard` with a Layer 0 `TypeLattice` URI and MISU identity precondition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlaceTypeBinding {
    /// Underlying `PlaceMCard` guarded by this binding.
    pub place: PlaceMCard,
    /// Structural role in the Place Type Lattice.
    pub role: PlaceRole,
    /// Optional Layer 0 `TypeLattice` URI.
    pub type_uri: Option<String>,
    /// Optional MISU identity prefix requirement (`verifyIdentity ⊓ φ`).
    pub required_identity_prefix: Option<String>,
}

impl PlaceTypeBinding {
    /// Creates a new `PlaceTypeBinding` for `place`.
    pub fn new(
        place: PlaceMCard,
        role: PlaceRole,
        type_uri: Option<String>,
        required_identity_prefix: Option<String>,
    ) -> Self {
        Self { place, role, type_uri, required_identity_prefix }
    }

    /// Resolves the normalized type expression for admission checking.
    pub fn effective_type_expr(&self) -> String {
        normalize_type_uri(self.type_uri.as_deref(), &self.place.type_expr)
    }

    /// Validates `token` against MCard verification, MISU identity meet law, capacity, and type guard.
    pub fn validate_token(
        &self,
        token: &TokenMCard,
        author_did: Option<&str>,
        current_occupancy: usize,
    ) -> BailVerdict {
        if !token.verify() {
            return BailVerdict::Bail {
                reason: format!("Token '{}' failed MCardRecord verification", token.token_id),
                invariant_code: "INV-508-VERIFY".to_string(),
                context_dump: json!({ "token_id": token.token_id }),
            };
        }
        if let Some(prefix) = &self.required_identity_prefix {
            let ok = author_did.is_some_and(|did| did.starts_with(prefix));
            if !ok {
                return BailVerdict::Bail {
                    reason: format!("MISU Meet Law (verifyIdentity ⊓ φ) failed on place '{}'", self.place.place_id),
                    invariant_code: "INV-508-MISU".to_string(),
                    context_dump: json!({ "place_id": self.place.place_id, "expected_prefix": prefix }),
                };
            }
        }
        if let Some(cap) = self.place.capacity {
            if current_occupancy >= cap {
                return BailVerdict::Bail {
                    reason: format!("Place '{}' capacity {} exceeded", self.place.place_id, cap),
                    invariant_code: "INV-508-CAP".to_string(),
                    context_dump: json!({ "place_id": self.place.place_id, "capacity": cap }),
                };
            }
        }
        let eff = self.effective_type_expr();
        if !check_type_expr(&token.payload, &token.color_type, &eff) {
            return BailVerdict::Bail {
                reason: format!(
                    "Token '{}' (color '{}') rejected by place '{}' type guard '{}'",
                    token.token_id, token.color_type, self.place.place_id, eff
                ),
                invariant_code: "INV-508-TYPE".to_string(),
                context_dump: json!({ "place_id": self.place.place_id, "expected": eff, "actual": token.color_type }),
            };
        }
        self.place.evaluate_guard(token, current_occupancy)
    }
}