Skip to main content

clm_rust_core/layer2/
host_mount.rs

1//! Host Filesystem Mount Adapter, Ordered Namespace Union & Layer 1 Collection Server (Sprint 512)
2//! Canonical Path: kernel/clm_rust_core/src/layer2/host_mount.rs
3
4use crate::cpn::mcard_token::{NetMCard, TokenMCard};
5use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
6use crate::layer2::petri_process::MCardNamespaceProtocolService;
7use crate::layer2::vfs::DirectoryManifest;
8use std::collections::{BTreeMap, BTreeSet};
9
10/// Adapter bridging host-like filesystem verbs (`ls`, `cat`, `mkdir`, `cp`, `mv`, `rm`) to `MCardNamespaceProtocolService`.
11pub struct MCardHostMountAdapter {
12    /// Underlying 9-op authenticated namespace protocol service.
13    pub service: MCardNamespaceProtocolService,
14    /// Sponsor DID capability used for mounted operations.
15    pub sponsor_did: String,
16}
17
18impl Default for MCardHostMountAdapter {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl MCardHostMountAdapter {
25    /// Creates a new in-memory `MCardHostMountAdapter`.
26    pub fn new() -> Self {
27        Self {
28            service: MCardNamespaceProtocolService::new_in_memory(),
29            sponsor_did: crate::layer0::vocabulary_identities::DID_KEY_Z6MKRUSTHOSTMOUNT.to_string(),
30        }
31    }
32
33    /// Writes `content` to `path` via the `put` namespace operation and returns the qualified ref.
34    pub fn put_file(&self, path: &str, content: &[u8]) -> Result<String, String> {
35        let res = self
36            .service
37            .put(path, content, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3), Some(&self.sponsor_did));
38        if !res.committed {
39            return Err("put_file failed".to_string());
40        }
41        Ok(res.payload["qualified_ref"]
42            .as_str()
43            .unwrap_or_default()
44            .to_string())
45    }
46
47    /// Reads raw bytes from `path` after verifying `card(hash, content, g_time)`.
48    pub fn cat(&self, path: &str) -> Result<Vec<u8>, String> {
49        self.service
50            .fs
51            .read_raw_bytes(path)
52            .map_err(|e| e.to_string())
53    }
54
55    /// Lists handles under `prefix` via the `list` namespace operation.
56    pub fn ls(&self, prefix: &str) -> Result<Vec<String>, String> {
57        let res = self.service.list(prefix, Some(&self.sponsor_did));
58        if !res.committed {
59            return Err("ls failed".to_string());
60        }
61        let arr = res.payload["items"]
62            .as_array()
63            .cloned()
64            .unwrap_or_default();
65        Ok(arr
66            .into_iter()
67            .filter_map(|v| v.as_str().map(|s| s.to_string()))
68            .collect())
69    }
70
71    /// Mints an empty `DirectoryManifest` MCard at `dir_path`.
72    pub fn mkdir(&self, dir_path: &str) -> Result<String, String> {
73        let manifest = DirectoryManifest::new(Vec::new(), Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3));
74        self.put_file(dir_path, &manifest.to_canonical_bytes())
75    }
76
77    /// Zero-copy content-addressed copy by binding `dst_path` to `src_path`'s qualified ref.
78    pub fn cp(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
79        let resolved = self.service.resolve(src_path, Some(&self.sponsor_did));
80        if !resolved.committed {
81            return Err(format!("Source '{src_path}' not found"));
82        }
83        let qref = resolved.payload["qualified_ref"]
84            .as_str()
85            .unwrap_or_default()
86            .to_string();
87        let dst_res = self.service.resolve(dst_path, Some(&self.sponsor_did));
88        let expected_old = if dst_res.committed {
89            dst_res.payload["qualified_ref"]
90                .as_str()
91                .map(|s| s.to_string())
92        } else {
93            None
94        };
95        let bnd = self.service.bind(
96            dst_path,
97            &qref,
98            expected_old.as_deref(),
99            Some(&self.sponsor_did),
100        );
101        if !bnd.committed {
102            return Err(format!("cp bind failed for '{dst_path}'"));
103        }
104        Ok(qref)
105    }
106
107    /// Moves `src_path` to `dst_path` by zero-copy `cp` followed by tombstone `rm`.
108    pub fn mv(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
109        let qref = self.cp(src_path, dst_path)?;
110        self.rm(src_path)?;
111        Ok(qref)
112    }
113
114    /// Tombstones `path` without deleting underlying immutable `card` rows.
115    pub fn rm(&self, path: &str) -> Result<(), String> {
116        self.service
117            .fs
118            .delete_file(path)
119            .map_err(|e| e.to_string())
120    }
121}
122
123/// Ordered Namespace Union (`C_1 |_| C_2`) with explicit Meet collision check (`INV-512-02`).
124pub struct NamespaceUnionMount {
125    mounts: Vec<(String, MCardHostMountAdapter)>,
126}
127
128impl Default for NamespaceUnionMount {
129    fn default() -> Self {
130        Self::new()
131    }
132}
133
134impl NamespaceUnionMount {
135    /// Creates an empty `NamespaceUnionMount`.
136    pub fn new() -> Self {
137        Self { mounts: Vec::new() }
138    }
139
140    /// Mounts `adapter` under `name`, rejecting handle collisions (`Meet != bottom`).
141    pub fn add_mount(&mut self, name: &str, adapter: MCardHostMountAdapter) -> Result<(), String> {
142        let mut existing = BTreeSet::new();
143        for (_, m) in &self.mounts {
144            for h in m.ls(crate::layer0::vocabulary::HANDLE_MCARD)? {
145                existing.insert(h);
146            }
147        }
148        let incoming = adapter.ls(crate::layer0::vocabulary::HANDLE_MCARD)?;
149        for h in &incoming {
150            if existing.contains(h) {
151                return Err(format!(
152                    "Namespace union collision detected (Meet != bottom) on handle '{h}'"
153                ));
154            }
155        }
156        self.mounts.push((name.to_string(), adapter));
157        Ok(())
158    }
159
160    /// Lists handles across all union mounts under `prefix`.
161    pub fn ls_union(&self, prefix: &str) -> Result<Vec<String>, String> {
162        let mut seen = BTreeSet::new();
163        for (_, m) in &self.mounts {
164            for h in m.ls(prefix)? {
165                if !seen.insert(h.clone()) {
166                    return Err(format!("Runtime union collision on '{h}'"));
167                }
168            }
169        }
170        Ok(seen.into_iter().collect())
171    }
172
173    /// Reads `path` from the unique mount owning it, failing closed on collision.
174    pub fn cat_union(&self, path: &str) -> Result<Vec<u8>, String> {
175        let mut found: Vec<Vec<u8>> = Vec::new();
176        for (_, m) in &self.mounts {
177            if let Ok(bytes) = m.cat(path) {
178                found.push(bytes);
179            }
180        }
181        match found.len() {
182            0 => Err(format!("Handle '{path}' not found in union namespace")),
183            1 => Ok(found.remove(0)),
184            _ => Err(format!("Ambiguous collision on '{path}' across union mounts")),
185        }
186    }
187}
188
189/// Exposes a running Layer 1 Petri Net as a Collection Server under `mcard://ns/<net_id>/` (INV-512-03, INV-517).
190pub struct Layer1NetCollectionServer {
191    pub net_id: String,
192    pub namespace: MCardTokenNamespace,
193    pub adapter: MCardHostMountAdapter,
194    pub firings: BTreeMap<String, FiringReceiptMCard>,
195}
196
197impl Layer1NetCollectionServer {
198    pub fn new(net_id: &str) -> Self {
199        Self {
200            net_id: net_id.to_string(),
201            namespace: MCardTokenNamespace::new(net_id),
202            adapter: MCardHostMountAdapter::new(),
203            firings: BTreeMap::new(),
204        }
205    }
206
207    pub fn with_namespace(
208        net_id: &str,
209        namespace: MCardTokenNamespace,
210        adapter: Option<MCardHostMountAdapter>,
211    ) -> Self {
212        Self {
213            net_id: net_id.to_string(),
214            namespace,
215            adapter: adapter.unwrap_or_default(),
216            firings: BTreeMap::new(),
217        }
218    }
219
220    pub fn marking(&self) -> &MCardMarking {
221        &self.namespace.marking
222    }
223
224    pub fn base_uri(&self) -> String {
225        format!("ns/{}", self.net_id)
226    }
227
228    pub fn record_firing(&mut self, receipt: FiringReceiptMCard) {
229        self.firings.insert(receipt.qualified_hash(), receipt);
230    }
231
232    pub fn sync_to_collection(&mut self, _sponsor_did: Option<&str>) -> Result<(), String> {
233        let base = self.base_uri();
234        let places: Vec<_> = self.namespace.places.values().cloned().collect();
235        let transitions: Vec<_> = self.namespace.transitions.values().cloned().collect();
236        let mut tokens_by_place = BTreeMap::new();
237        let mut refs_by_place = BTreeMap::new();
238
239        for pid in self.namespace.places.keys() {
240            let toks = self.namespace.get_place_tokens(pid);
241            let refs = self.namespace.marking.place_refs(pid);
242            tokens_by_place.insert(pid.clone(), toks);
243            refs_by_place.insert(pid.clone(), refs);
244        }
245
246        let net_card = NetMCard::create(
247            &self.net_id,
248            places.clone(),
249            transitions.clone(),
250            tokens_by_place.clone(),
251            Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
252            None,
253        )?;
254        self.adapter.put_file(&format!("{base}/topology"), &net_card.card.content)?;
255
256        let refs_val = serde_json::to_value(&refs_by_place).map_err(|e| e.to_string())?;
257        let marking_tok = TokenMCard::from_json(&refs_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PETRI_MARKING, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3))?;
258        self.adapter.put_file(&format!("{base}/marking"), &marking_tok.card.content)?;
259
260        for place in &places {
261            self.adapter.put_file(&format!("{base}/places/{}/spec", place.place_id), &place.card.content)?;
262            if let Some(toks) = tokens_by_place.get(&place.place_id) {
263                for (idx, tok) in toks.iter().enumerate() {
264                    self.adapter.put_file(&format!("{base}/places/{}/tokens/{idx}", place.place_id), &tok.card.content)?;
265                }
266            }
267        }
268
269        for trans in &transitions {
270            self.adapter.put_file(&format!("{base}/transitions/{}/spec", trans.transition_id), &trans.card.content)?;
271        }
272
273        for (fref, receipt) in &self.firings {
274            let safe_ref = fref.replace(':', "_");
275            self.adapter.put_file(&format!("{base}/firings/{safe_ref}"), &receipt.card.content)?;
276        }
277
278        Ok(())
279    }
280
281    pub fn read_resource(&self, subpath: &str) -> Result<String, String> {
282        let clean = subpath.trim_start_matches('/');
283        let base = self.base_uri();
284        let target = if clean.starts_with(&base) {
285            clean.to_string()
286        } else {
287            format!("{base}/{clean}")
288        };
289        let bytes = self.adapter.cat(&target)?;
290        String::from_utf8(bytes).map_err(|e| e.to_string())
291    }
292
293    pub fn list_resources(&self) -> Result<Vec<String>, String> {
294        self.adapter.ls(&self.base_uri())
295    }
296}
297