clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 2 `PetriProcessPCard` Service Wrapper & 9-Operation Authenticated Namespace Protocol (Sprint 511)
//! Canonical Path: kernel/clm_rust_core/src/layer2/petri_process.rs

use crate::layer0::fiber_transitions::{trace, CORE_TRACE};
use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
use crate::cpn::mcard_token::TokenMCard;
use crate::layer2::vfs::MCardFileSystem;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Canonical 9 operations of the authenticated MCard Namespace Protocol.
pub const NAMESPACE_PROTOCOL_OPS: &[&str; 9] = &[
    "version", "put", "get", "stat", "resolve", "bind", "list", "history", "watch",
];

/// Result of executing a `PetriProcessPCard` transition cycle (`p_in -> p_ready -> p_done -> p_out | p_exception`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessExecutionResult {
    /// True if the transition committed to `p_out`.
    pub committed: bool,
    /// True if the transition trapped to `p_exception`.
    pub trapped_to_exception: bool,
    /// Output or exception `TokenMCard`.
    pub output_token: TokenMCard,
    /// Ordered sequence of visited Petri Net places.
    pub places_visited: Vec<String>,
    /// Recorded 5-state Cordis `Fiber` trace.
    pub fiber_trace: Vec<String>,
    /// Structured JSON response or error payload.
    pub payload: Value,
}

/// Layer 2 Petri Net Process wrapper enforcing MISU DID authentication and capability prefix bounds.
#[derive(Clone)]
pub struct PetriProcessPCard {
    /// Logical process identifier.
    pub process_id: String,
    /// Required Cordis service capabilities.
    pub required_services: Vec<String>,
    /// Allowed handle prefix scopes.
    pub allowed_prefixes: Vec<String>,
}

impl PetriProcessPCard {
    /// Creates a new `PetriProcessPCard` for `process_id`.
    pub fn new(process_id: &str) -> Self {
        Self {
            process_id: process_id.to_string(),
            required_services: Vec::new(),
            allowed_prefixes: Vec::new(),
        }
    }

    /// Returns the 5 canonical Petri Net place IDs `(p_in, p_ready, p_done, p_out, p_exception)`.
    pub fn place_ids(&self) -> (String, String, String, String, String) {
        (
            format!("{}:p_in", self.process_id),
            format!("{}:p_ready", self.process_id),
            format!("{}:p_done", self.process_id),
            format!("{}:p_out", self.process_id),
            format!("{}:p_exception", self.process_id),
        )
    }

    /// Executes `handler` inside the process Petri Net with MISU DID and scope checks.
    pub fn execute<F>(
        &self,
        request: &Value,
        sponsor_did: Option<&str>,
        target_handle: Option<&str>,
        handler: F,
    ) -> ProcessExecutionResult
    where
        F: FnOnce(&Value) -> Result<Value, String>,
    {
        let (p_in, p_ready, p_done, p_out, p_exc) = self.place_ids();
        let did_ok = sponsor_did
            .map(|d| d.starts_with(crate::layer0::vocabulary_identities::DID_KEY) || d.starts_with(crate::layer0::vocabulary::URI_SCHEME_DID_CLM))
            .unwrap_or(false);
        if !did_ok {
            return self.trapped("unauthenticated_sponsor_did", "t_acquire", vec![p_in, p_exc], rejected_trace());
        }

        if let Some(target) = target_handle {
            if !self.allowed_prefixes.is_empty() {
                let clean = target
                    .trim_start_matches('/')
                    .strip_prefix(crate::layer0::vocabulary::HANDLE_MCARD)
                    .unwrap_or(target)
                    .trim_start_matches('/');
                let allowed = self
                    .allowed_prefixes
                    .iter()
                    .any(|p| clean.starts_with(p.trim_matches('/')));
                if !allowed {
                    let error = format!("unauthorized_handle_scope:{target}");
                    return self.trapped(&error, "t_acquire", vec![p_in, p_exc], rejected_trace());
                }
            }
        }

        match handler(request) {
            Ok(out_val) => {
                let out_tok = TokenMCard::from_json(&out_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_OUT, None)
                    .expect("out token");
                ProcessExecutionResult {
                    committed: true,
                    trapped_to_exception: false,
                    output_token: out_tok,
                    places_visited: vec![p_in, p_ready, p_done, p_out],
                    fiber_trace: CORE_TRACE.map(String::from).to_vec(),
                    payload: out_val,
                }
            }
            Err(err) => self.trapped(&err, "t_invoke", vec![p_in, p_ready, p_exc], CORE_TRACE.map(String::from).to_vec()),
        }
    }

    /// The result of a request trapped to `p_exception` at `stage`.
    fn trapped(
        &self,
        error: &str,
        stage: &'static str,
        places_visited: Vec<String>,
        fiber_trace: Vec<String>,
    ) -> ProcessExecutionResult {
        let exception = ProcessException { error, kind: "process_exception", process_id: &self.process_id, stage };
        let payload = serde_json::to_value(exception).expect("exception payload");
        let output_token = TokenMCard::from_json(&payload, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_EXCEPTION, None)
            .expect("exc token");
        ProcessExecutionResult { committed: false, trapped_to_exception: true, output_token, places_visited, fiber_trace, payload }
    }
}

/// The payload of a `p_exception` token; the field order is the stored key order.
#[derive(Serialize)]
struct ProcessException<'a> {
    error: &'a str,
    kind: &'static str,
    process_id: &'a str,
    stage: &'static str,
}

/// The firing trace of a request rejected at `t_acquire`: the fiber never reaches ACTIVE.
fn rejected_trace() -> Vec<String> {
    [trace::PENDING, trace::LOADING, trace::UNLOADING, trace::DISPOSED].map(String::from).to_vec()
}

/// 9-operation authenticated MCard Namespace Protocol service (`version`, `put`, `get`, `stat`, `resolve`, `bind`, `list`, `history`, `watch`).
pub struct MCardNamespaceProtocolService {
    /// Underlying `MCardFileSystem`.
    pub fs: MCardFileSystem,
    /// Protocol semantic version string.
    pub protocol_version: String,
    /// Allowed handle prefixes for capability scoping.
    pub allowed_prefixes: Vec<String>,
    watch_log: Vec<Value>,
}

impl MCardNamespaceProtocolService {
    /// Creates an in-memory `MCardNamespaceProtocolService`.
    pub fn new_in_memory() -> Self {
        Self {
            fs: MCardFileSystem::new_in_memory().expect("in-memory fs"),
            protocol_version: crate::layer0::vocabulary_identities::VERSION_N_1_0_0.to_string(),
            allowed_prefixes: Vec::new(),
            watch_log: Vec::new(),
        }
    }

    fn run_op<F>(
        &self,
        op_name: &str,
        req: &Value,
        sponsor_did: Option<&str>,
        target_handle: Option<&str>,
        handler: F,
    ) -> ProcessExecutionResult
    where
        F: FnOnce(&Value) -> Result<Value, String>,
    {
        let mut proc = PetriProcessPCard::new(&format!("ns:{op_name}"));
        proc.allowed_prefixes = self.allowed_prefixes.clone();
        proc.execute(req, sponsor_did, target_handle, handler)
    }

    /// Negotiates protocol version and returns supported namespace operations.
    pub fn version(&self, client_version: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "client_version": client_version });
        let server_ver = self.protocol_version.clone();
        self.run_op("version", &req, sponsor_did, None, move |_| {
            let c_maj = client_version.split('.').next().unwrap_or("0");
            let s_maj = server_ver.split('.').next().unwrap_or("1");
            if c_maj != s_maj {
                return Err(format!("Incompatible protocol major version: {client_version}"));
            }
            Ok(serde_json::json!({
                "negotiated_version": server_ver,
                "op": "version",
                "operations": NAMESPACE_PROTOCOL_OPS,
                "server_version": self.protocol_version,
            }))
        })
    }

    /// Stores `content` at `handle` and seals an immutable `MCardRecord`.
    pub fn put(
        &self,
        handle: &str,
        content: &[u8],
        algorithm: Option<&str>,
        sponsor_did: Option<&str>,
    ) -> ProcessExecutionResult {
        let algo = algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3);
        let req = serde_json::json!({ "algorithm": algo, "size_bytes": content.len() });
        self.run_op("put", &req, sponsor_did, Some(handle), |_| {
            let rec = self
                .fs
                .write_raw_bytes(handle, content, Some(algo))
                .map_err(|e| e.to_string())?;
            Ok(serde_json::json!({
                "algorithm": algo,
                "g_time": rec.g_time,
                "hash": rec.hash,
                "op": "put",
                "qualified_ref": format!("{algo}:{}", rec.hash),
                "size_bytes": content.len(),
            }))
        })
    }

    /// Retrieves verified content bytes from `handle`.
    pub fn get(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "ref": handle });
        self.run_op("get", &req, sponsor_did, Some(handle), |_| {
            let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
            Ok(serde_json::json!({
                "content_utf8": String::from_utf8_lossy(&raw),
                "op": "get",
                "size_bytes": raw.len(),
            }))
        })
    }

    /// Returns metadata (`size_bytes`, `algorithm`, `type_uri`) for `handle`.
    pub fn stat(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "target": handle });
        self.run_op("stat", &req, sponsor_did, Some(handle), |_| {
            let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
            Ok(serde_json::json!({
                "algorithm": crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3,
                "op": "stat",
                "size_bytes": raw.len(),
                "type_uri": crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_STORAGE_VERIFIED_MCARD,
            }))
        })
    }

    /// Resolves `handle` to its current algorithm-qualified `a:hex` reference.
    pub fn resolve(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "handle": handle });
        self.run_op("resolve", &req, sponsor_did, Some(handle), |_| {
            let st = self.fs.stat_file(handle).map_err(|e| e.to_string())?;
            Ok(serde_json::json!({
                "handle": st.uri,
                "op": "resolve",
                "qualified_ref": format!("{HASH_PREFIX_BLAKE3}{}", st.hash),
            }))
        })
    }

    /// Atomically compare-and-swaps `handle` to `new_ref` given `expected_old_ref`.
    pub fn bind(
        &mut self,
        handle: &str,
        new_ref: &str,
        expected_old_ref: Option<&str>,
        sponsor_did: Option<&str>,
    ) -> ProcessExecutionResult {
        let req = serde_json::json!({
            "expected_old_ref": expected_old_ref,
            "handle": handle,
            "new_ref": new_ref,
        });
        let fs = self.fs.clone();
        let canonical = fs.canonicalize_uri(handle);
        let qnew = if new_ref.contains(':') {
            new_ref.to_string()
        } else {
            format!("{HASH_PREFIX_BLAKE3}{new_ref}")
        };
        let next_cursor = self.watch_log.len() + 1;
        let res = self.run_op("bind", &req, sponsor_did, Some(handle), |_| {
            let ok = fs
                .bind(handle, new_ref, expected_old_ref)
                .map_err(|e| e.to_string())?;
            if !ok {
                return Err(format!("CAS conflict on '{handle}'"));
            }
            Ok(serde_json::json!({
                "bound": true,
                "cursor": next_cursor,
                "handle": canonical,
                "new_ref": qnew,
                "op": "bind",
            }))
        });
        if res.committed {
            self.watch_log.push(serde_json::json!({
                "cursor": next_cursor,
                "handle": self.fs.canonicalize_uri(handle),
                "new_ref": if new_ref.contains(':') { new_ref.to_string() } else { format!("{HASH_PREFIX_BLAKE3}{new_ref}") },
                "old_ref": expected_old_ref,
            }));
        }
        res
    }

    /// Lists handles matching `prefix`.
    pub fn list(&self, prefix: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "prefix": prefix });
        self.run_op("list", &req, sponsor_did, Some(prefix), |_| {
            let items = self.fs.list_dir(prefix).map_err(|e| e.to_string())?;
            Ok(serde_json::json!({
                "items": items,
                "op": "list",
                "prefix": prefix,
            }))
        })
    }

    /// Returns temporal handle history for `handle`.
    pub fn history(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "handle": handle });
        self.run_op("history", &req, sponsor_did, Some(handle), |_| {
            let canonical = self.fs.canonicalize_uri(handle);
            Ok(serde_json::json!({
                "handle": canonical,
                "op": "history",
            }))
        })
    }

    /// Streams bind events strictly newer than `since_cursor`.
    pub fn watch(&self, since_cursor: usize, sponsor_did: Option<&str>) -> ProcessExecutionResult {
        let req = serde_json::json!({ "since_cursor": since_cursor });
        let events: Vec<Value> = self
            .watch_log
            .iter()
            .filter(|ev| ev.get("cursor").and_then(|c| c.as_u64()).unwrap_or(0) as usize > since_cursor)
            .cloned()
            .collect();
        self.run_op("watch", &req, sponsor_did, None, move |_| {
            Ok(serde_json::json!({
                "events": events,
                "op": "watch",
            }))
        })
    }
}