clm-kernel 0.0.10

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Host Filesystem Mount Adapter, Ordered Namespace Union & Layer 1 Collection Server (Sprint 512)
//! Canonical Path: kernel/clm_rust_core/src/layer2/host_mount.rs

use crate::cpn::mcard_token::{NetMCard, TokenMCard};
use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
use crate::layer2::petri_process::MCardNamespaceProtocolService;
use crate::layer2::vfs::DirectoryManifest;
use std::collections::{BTreeMap, BTreeSet};

/// Adapter bridging host-like filesystem verbs (`ls`, `cat`, `mkdir`, `cp`, `mv`, `rm`) to `MCardNamespaceProtocolService`.
pub struct MCardHostMountAdapter {
    /// Underlying 9-op authenticated namespace protocol service.
    pub service: MCardNamespaceProtocolService,
    /// Sponsor DID capability used for mounted operations.
    pub sponsor_did: String,
}

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

impl MCardHostMountAdapter {
    /// Creates a new in-memory `MCardHostMountAdapter`.
    pub fn new() -> Self {
        Self {
            service: MCardNamespaceProtocolService::new_in_memory(),
            sponsor_did: "did:key:z6MkRustHostMount".to_string(),
        }
    }

    /// Writes `content` to `path` via the `put` namespace operation and returns the qualified ref.
    pub fn put_file(&self, path: &str, content: &[u8]) -> Result<String, String> {
        let res = self
            .service
            .put(path, content, Some("blake3"), Some(&self.sponsor_did));
        if !res.committed {
            return Err("put_file failed".to_string());
        }
        Ok(res.payload["qualified_ref"]
            .as_str()
            .unwrap_or_default()
            .to_string())
    }

    /// Reads raw bytes from `path` after verifying `card(hash, content, g_time)`.
    pub fn cat(&self, path: &str) -> Result<Vec<u8>, String> {
        self.service
            .fs
            .read_raw_bytes(path)
            .map_err(|e| e.to_string())
    }

    /// Lists handles under `prefix` via the `list` namespace operation.
    pub fn ls(&self, prefix: &str) -> Result<Vec<String>, String> {
        let res = self.service.list(prefix, Some(&self.sponsor_did));
        if !res.committed {
            return Err("ls failed".to_string());
        }
        let arr = res.payload["items"]
            .as_array()
            .cloned()
            .unwrap_or_default();
        Ok(arr
            .into_iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect())
    }

    /// Mints an empty `DirectoryManifest` MCard at `dir_path`.
    pub fn mkdir(&self, dir_path: &str) -> Result<String, String> {
        let manifest = DirectoryManifest::new(Vec::new(), Some("blake3"));
        self.put_file(dir_path, &manifest.to_canonical_bytes())
    }

    /// Zero-copy content-addressed copy by binding `dst_path` to `src_path`'s qualified ref.
    pub fn cp(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
        let resolved = self.service.resolve(src_path, Some(&self.sponsor_did));
        if !resolved.committed {
            return Err(format!("Source '{src_path}' not found"));
        }
        let qref = resolved.payload["qualified_ref"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        let dst_res = self.service.resolve(dst_path, Some(&self.sponsor_did));
        let expected_old = if dst_res.committed {
            dst_res.payload["qualified_ref"]
                .as_str()
                .map(|s| s.to_string())
        } else {
            None
        };
        let bnd = self.service.bind(
            dst_path,
            &qref,
            expected_old.as_deref(),
            Some(&self.sponsor_did),
        );
        if !bnd.committed {
            return Err(format!("cp bind failed for '{dst_path}'"));
        }
        Ok(qref)
    }

    /// Moves `src_path` to `dst_path` by zero-copy `cp` followed by tombstone `rm`.
    pub fn mv(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
        let qref = self.cp(src_path, dst_path)?;
        self.rm(src_path)?;
        Ok(qref)
    }

    /// Tombstones `path` without deleting underlying immutable `card` rows.
    pub fn rm(&self, path: &str) -> Result<(), String> {
        self.service
            .fs
            .delete_file(path)
            .map_err(|e| e.to_string())
    }
}

/// Ordered Namespace Union (`C_1 |_| C_2`) with explicit Meet collision check (`INV-512-02`).
pub struct NamespaceUnionMount {
    mounts: Vec<(String, MCardHostMountAdapter)>,
}

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

impl NamespaceUnionMount {
    /// Creates an empty `NamespaceUnionMount`.
    pub fn new() -> Self {
        Self { mounts: Vec::new() }
    }

    /// Mounts `adapter` under `name`, rejecting handle collisions (`Meet != bottom`).
    pub fn add_mount(&mut self, name: &str, adapter: MCardHostMountAdapter) -> Result<(), String> {
        let mut existing = BTreeSet::new();
        for (_, m) in &self.mounts {
            for h in m.ls("mcard:")? {
                existing.insert(h);
            }
        }
        let incoming = adapter.ls("mcard:")?;
        for h in &incoming {
            if existing.contains(h) {
                return Err(format!(
                    "Namespace union collision detected (Meet != bottom) on handle '{h}'"
                ));
            }
        }
        self.mounts.push((name.to_string(), adapter));
        Ok(())
    }

    /// Lists handles across all union mounts under `prefix`.
    pub fn ls_union(&self, prefix: &str) -> Result<Vec<String>, String> {
        let mut seen = BTreeSet::new();
        for (_, m) in &self.mounts {
            for h in m.ls(prefix)? {
                if !seen.insert(h.clone()) {
                    return Err(format!("Runtime union collision on '{h}'"));
                }
            }
        }
        Ok(seen.into_iter().collect())
    }

    /// Reads `path` from the unique mount owning it, failing closed on collision.
    pub fn cat_union(&self, path: &str) -> Result<Vec<u8>, String> {
        let mut found: Vec<Vec<u8>> = Vec::new();
        for (_, m) in &self.mounts {
            if let Ok(bytes) = m.cat(path) {
                found.push(bytes);
            }
        }
        match found.len() {
            0 => Err(format!("Handle '{path}' not found in union namespace")),
            1 => Ok(found.remove(0)),
            _ => Err(format!("Ambiguous collision on '{path}' across union mounts")),
        }
    }
}

/// Exposes a running Layer 1 Petri Net as a Collection Server under `mcard://ns/<net_id>/` (INV-512-03, INV-517).
pub struct Layer1NetCollectionServer {
    pub net_id: String,
    pub namespace: MCardTokenNamespace,
    pub adapter: MCardHostMountAdapter,
    pub firings: BTreeMap<String, FiringReceiptMCard>,
}

impl Layer1NetCollectionServer {
    pub fn new(net_id: &str) -> Self {
        Self {
            net_id: net_id.to_string(),
            namespace: MCardTokenNamespace::new(net_id),
            adapter: MCardHostMountAdapter::new(),
            firings: BTreeMap::new(),
        }
    }

    pub fn with_namespace(
        net_id: &str,
        namespace: MCardTokenNamespace,
        adapter: Option<MCardHostMountAdapter>,
    ) -> Self {
        Self {
            net_id: net_id.to_string(),
            namespace,
            adapter: adapter.unwrap_or_default(),
            firings: BTreeMap::new(),
        }
    }

    pub fn marking(&self) -> &MCardMarking {
        &self.namespace.marking
    }

    pub fn base_uri(&self) -> String {
        format!("ns/{}", self.net_id)
    }

    pub fn record_firing(&mut self, receipt: FiringReceiptMCard) {
        self.firings.insert(receipt.qualified_hash(), receipt);
    }

    pub fn sync_to_collection(&mut self, _sponsor_did: Option<&str>) -> Result<(), String> {
        let base = self.base_uri();
        let places: Vec<_> = self.namespace.places.values().cloned().collect();
        let transitions: Vec<_> = self.namespace.transitions.values().cloned().collect();
        let mut tokens_by_place = BTreeMap::new();
        let mut refs_by_place = BTreeMap::new();

        for pid in self.namespace.places.keys() {
            let toks = self.namespace.get_place_tokens(pid);
            let refs = self.namespace.marking.place_refs(pid);
            tokens_by_place.insert(pid.clone(), toks);
            refs_by_place.insert(pid.clone(), refs);
        }

        let net_card = NetMCard::create(
            &self.net_id,
            places.clone(),
            transitions.clone(),
            tokens_by_place.clone(),
            Some("blake3"),
            None,
        )?;
        self.adapter.put_file(&format!("{base}/topology"), &net_card.card.content)?;

        let refs_val = serde_json::to_value(&refs_by_place).map_err(|e| e.to_string())?;
        let marking_tok = TokenMCard::from_json(&refs_val, "clm://type/petri/marking", Some("blake3"))?;
        self.adapter.put_file(&format!("{base}/marking"), &marking_tok.card.content)?;

        for place in &places {
            self.adapter.put_file(&format!("{base}/places/{}/spec", place.place_id), &place.card.content)?;
            if let Some(toks) = tokens_by_place.get(&place.place_id) {
                for (idx, tok) in toks.iter().enumerate() {
                    self.adapter.put_file(&format!("{base}/places/{}/tokens/{idx}", place.place_id), &tok.card.content)?;
                }
            }
        }

        for trans in &transitions {
            self.adapter.put_file(&format!("{base}/transitions/{}/spec", trans.transition_id), &trans.card.content)?;
        }

        for (fref, receipt) in &self.firings {
            let safe_ref = fref.replace(':', "_");
            self.adapter.put_file(&format!("{base}/firings/{safe_ref}"), &receipt.card.content)?;
        }

        Ok(())
    }

    pub fn read_resource(&self, subpath: &str) -> Result<String, String> {
        let clean = subpath.trim_start_matches('/');
        let base = self.base_uri();
        let target = if clean.starts_with(&base) {
            clean.to_string()
        } else {
            format!("{base}/{clean}")
        };
        let bytes = self.adapter.cat(&target)?;
        String::from_utf8(bytes).map_err(|e| e.to_string())
    }

    pub fn list_resources(&self) -> Result<Vec<String>, String> {
        self.adapter.ls(&self.base_uri())
    }
}