clm-kernel 0.0.20

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 2 File & Storage System modeled as a P-Invariant Petri Net in Cordis Fibers (Sprint 517).
//! Canonical Path: kernel/clm_rust_core/src/layer2/storage_petri.rs

use crate::cpn::mcard_token::{PlaceMCard, TokenMCard, TransitionMCard};
use crate::cpn::place_type_lattice::{PlaceRole, PlaceTypeBinding, PlaceTypeLattice};
use crate::cpn::token_namespace::{MCardMarking, MCardTokenNamespace};
use crate::layer2::vfs::MCardFileSystem;
use crate::layer1::fractal_net_harness::{register_place_specs, PlaceSpec};

/// Layer 2 File & Storage System modeled as a P-Invariant Petri Net in Cordis Fibers.
pub struct StoragePetriNet {
    pub fs: MCardFileSystem,
    pub namespace: MCardTokenNamespace,
    pub lattice: PlaceTypeLattice,
}

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

impl StoragePetriNet {
    /// Creates a new `StoragePetriNet` with in-memory VFS, unified namespace, and bounded type lattice.
    pub fn new() -> Self {
        let fs = MCardFileSystem::new_in_memory().expect("in-memory fs");
        let mut namespace = MCardTokenNamespace::new("storage_net");

        // Sprint 533: place table replaces five build-and-register blocks.
        let specs = [
            PlaceSpec::new("p_raw_bytes", "clm://type/storage/raw_bytes", PlaceRole::InitialBottom),
            PlaceSpec::new("p_staged_card", "clm://type/storage/verified_mcard", PlaceRole::Intermediate),
            PlaceSpec::new("p_directory_manifest", "clm://type/storage/directory_manifest", PlaceRole::TerminalTop),
            PlaceSpec::new("p_handle_history", "clm://type/storage/handle_history", PlaceRole::Intermediate),
            PlaceSpec::new("p_storage_exception", "clm://type/storage/exception_trap", PlaceRole::Exception),
        ];
        let places = register_place_specs(&mut namespace, &specs).expect("valid storage places");

        let lattice = PlaceTypeLattice::from_net(&places, &[], None);

        Self {
            fs,
            namespace,
            lattice,
        }
    }

    /// Creates and registers a typed directory place enforcing admission.
    pub fn create_typed_directory_place(
        &mut self,
        place_id: &str,
        allowed_type_uri: &str,
    ) -> Result<PlaceMCard, String> {
        let place = PlaceMCard::create(
            place_id,
            allowed_type_uri,
            None,
            "Intermediate",
            Some("blake3"),
            None,
        )?;
        let binding = PlaceTypeBinding::new(
            place.clone(),
            PlaceRole::Intermediate,
            Some(allowed_type_uri.to_string()),
            None,
        );
        self.namespace.register_place(place.clone(), Some(binding));
        Ok(place)
    }

    /// Deposits a `TokenMCard` into a typed directory place, enforcing type guards.
    pub fn deposit_into_directory_place(
        &self,
        marking: &MCardMarking,
        place_id: &str,
        token: &TokenMCard,
    ) -> Result<MCardMarking, String> {
        let Some(place) = self.namespace.places.get(place_id) else {
            return Err(format!("Directory Place '{place_id}' not found"));
        };
        if !place.admits(token, marking.count(place_id)) {
            return Err(format!(
                "Directory PlaceMCard '{place_id}' rejected TokenMCard with color_type='{}'",
                token.color_type
            ));
        }
        let mut next = marking.clone();
        next.append(place_id, token.qualified_hash());
        Ok(next)
    }

    /// Executes `put_file` as a `TransitionMCard` inside Cordis Fibers.
    pub fn put_file_transition(
        &mut self,
        marking: &MCardMarking,
        uri: &str,
        raw_bytes: &[u8],
    ) -> Result<(MCardMarking, TokenMCard), String> {
        let payload = serde_json::json!({
            "content_hex": hex::encode(raw_bytes),
            "size": raw_bytes.len(),
        });
        let in_tok = TokenMCard::from_payload(
            payload,
            "clm://type/storage/raw_bytes",
            "tok_raw",
            Some("blake3"),
            None,
        )?;
        let mut next = marking.clone();
        next.append("p_raw_bytes", in_tok.qualified_hash());

        let trans = TransitionMCard::create(
            &format!("t_put_file:{uri}"),
            vec!["p_raw_bytes".to_string()],
            vec!["p_staged_card".to_string()],
            "clm://type/storage/raw_bytes",
            "clm://type/storage/verified_mcard",
            None,
            &format!("put_file({uri})"),
            Some("blake3"),
            None,
        )?;
        self.namespace.register_transition(trans);

        let rec = self.fs.write_raw_bytes(uri, raw_bytes, Some("blake3")).map_err(|e| e.to_string())?;
        let out_tok = TokenMCard {
            card: rec,
            color_type: "clm://type/storage/verified_mcard".to_string(),
            payload: serde_json::json!({ "uri": uri, "bytes_written": raw_bytes.len() }),
            token_id: format!("tok:verified:{uri}"),
        };

        let mut final_marking = next.clone();
        final_marking.append("p_staged_card", out_tok.qualified_hash());
        Ok((final_marking, out_tok))
    }
}