clm-kernel 0.0.12

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::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("did:key:") || d.starts_with("did:clm:"))
            .unwrap_or(false);
        if !did_ok {
            let exc_val = serde_json::json!({
                "error": "unauthenticated_sponsor_did",
                "kind": "process_exception",
                "process_id": self.process_id,
                "stage": "t_acquire",
            });
            let exc_tok = TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
                .expect("exc token");
            return ProcessExecutionResult {
                committed: false,
                trapped_to_exception: true,
                output_token: exc_tok,
                places_visited: vec![p_in, p_exc],
                fiber_trace: vec![
                    "PENDING".to_string(),
                    "LOADING".to_string(),
                    "UNLOADING".to_string(),
                    "DISPOSED".to_string(),
                ],
                payload: exc_val,
            };
        }

        if let Some(target) = target_handle {
            if !self.allowed_prefixes.is_empty() {
                let clean = target
                    .trim_start_matches('/')
                    .strip_prefix("mcard:")
                    .unwrap_or(target)
                    .trim_start_matches('/');
                let allowed = self
                    .allowed_prefixes
                    .iter()
                    .any(|p| clean.starts_with(p.trim_matches('/')));
                if !allowed {
                    let exc_val = serde_json::json!({
                        "error": format!("unauthorized_handle_scope:{target}"),
                        "kind": "process_exception",
                        "process_id": self.process_id,
                        "stage": "t_acquire",
                    });
                    let exc_tok =
                        TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
                            .expect("exc token");
                    return ProcessExecutionResult {
                        committed: false,
                        trapped_to_exception: true,
                        output_token: exc_tok,
                        places_visited: vec![p_in, p_exc],
                        fiber_trace: vec![
                            "PENDING".to_string(),
                            "LOADING".to_string(),
                            "UNLOADING".to_string(),
                            "DISPOSED".to_string(),
                        ],
                        payload: exc_val,
                    };
                }
            }
        }

        match handler(request) {
            Ok(out_val) => {
                let out_tok = TokenMCard::from_json(&out_val, "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: vec![
                        "PENDING".to_string(),
                        "LOADING".to_string(),
                        "ACTIVE".to_string(),
                        "UNLOADING".to_string(),
                        "DISPOSED".to_string(),
                    ],
                    payload: out_val,
                }
            }
            Err(err) => {
                let exc_val = serde_json::json!({
                    "error": err,
                    "kind": "process_exception",
                    "process_id": self.process_id,
                    "stage": "t_invoke",
                });
                let exc_tok = TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
                    .expect("exc token");
                ProcessExecutionResult {
                    committed: false,
                    trapped_to_exception: true,
                    output_token: exc_tok,
                    places_visited: vec![p_in, p_ready, p_exc],
                    fiber_trace: vec![
                        "PENDING".to_string(),
                        "LOADING".to_string(),
                        "ACTIVE".to_string(),
                        "UNLOADING".to_string(),
                        "DISPOSED".to_string(),
                    ],
                    payload: exc_val,
                }
            }
        }
    }
}

/// 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: "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("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": "blake3",
                "op": "stat",
                "size_bytes": raw.len(),
                "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!("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!("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!("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",
            }))
        })
    }
}