Skip to main content

clm_rust_core/
mcard_fs.rs

1//! MCard Universal Virtual Filesystem Engine (Sprint 191).
2//!
3//! Enforces:
4//! 1. Zero-FS Hermeticity (INV-09): Operates in-memory or on SQLite CAS without host disk I/O.
5//! 2. Handle Registry Singularity (INV-04) & Tri-Database Separation (INV-05):
6//!    Directly wraps canonical `card`, `handle_registry`, and `handle_history` tables.
7//! 3. Content-Addressable Identity (INV-02): BLAKE3 hashes for all MCard payloads.
8//! 4. Spatiotemporal Compositionality: Mountable in Cordis Context for scoped fiber execution.
9
10use crate::domain::{MCard, MCardPayload};
11use crate::error::{ClmError, Result, StorageErrorCode};
12use crate::types::{AgentDid, ContentHash};
13use rusqlite::{params, Connection};
14use serde::{Deserialize, Serialize};
15use std::sync::{Arc, Mutex};
16
17/// File metadata stat for an MCard in the virtual filesystem.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct MCardStat {
20    pub uri: String,
21    pub hash: ContentHash,
22    pub size_bytes: usize,
23    pub created_at: String,
24    pub updated_at: String,
25}
26
27pub use crate::layer2::vfs::{DirectoryManifest, DirectoryManifestEntry};
28
29/// The universal immutable filesystem engine mapping URIs to content-addressed MCards.
30#[derive(Clone)]
31pub struct MCardFileSystem {
32    pub(crate) conn: Arc<Mutex<Connection>>,
33    pub(crate) context_prefix: String,
34}
35
36impl MCardFileSystem {
37    /// Initializes an isolated, zero-disk in-memory MCard filesystem (INV-09).
38    pub fn new_in_memory() -> Result<Self> {
39        let conn = Connection::open_in_memory()?;
40        Self::init_schema(&conn)?;
41        Ok(Self {
42            conn: Arc::new(Mutex::new(conn)),
43            context_prefix: String::new(),
44        })
45    }
46
47    /// Initializes an in-memory MCard filesystem scoped to a specific context prefix.
48    pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
49        let mut fs = Self::new_in_memory()?;
50        fs.context_prefix = prefix.trim_matches('/').to_string();
51        Ok(fs)
52    }
53
54    /// Wraps an existing SQLite connection manager or shared connection with an optional context prefix.
55    pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
56        Self {
57            conn,
58            context_prefix: context_prefix.trim_matches('/').to_string(),
59        }
60    }
61
62    /// Wraps an existing SQLite connection manager or shared connection (root prefix).
63    pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
64        {
65            let locked = conn
66                .lock()
67                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
68            Self::init_schema(&locked)?;
69        }
70        Ok(Self {
71            conn,
72            context_prefix: String::new(),
73        })
74    }
75
76    /// Returns a new `MCardFileSystem` handle sharing the same storage but isolated to `prefix`.
77    pub fn with_prefix(&self, prefix: &str) -> Self {
78        Self {
79            conn: self.conn.clone(),
80            context_prefix: prefix.trim_matches('/').to_string(),
81        }
82    }
83
84    /// Returns the active context prefix for this filesystem handle.
85    pub fn context_prefix(&self) -> &str {
86        &self.context_prefix
87    }
88
89    /// Resolves canonical URI with context prefix scoping (DOD-191-04).
90    pub fn canonicalize_uri(&self, path: &str) -> String {
91        let clean = path.trim_start_matches('/');
92        if let Some(rest) = clean.strip_prefix("mcard:") {
93            let rest_clean = rest.trim_start_matches('/');
94            if self.context_prefix.is_empty() {
95                format!("mcard:{}", rest_clean)
96            } else if rest_clean.starts_with(&self.context_prefix) {
97                format!("mcard:{}", rest_clean)
98            } else {
99                format!("mcard:{}/{}", self.context_prefix, rest_clean)
100            }
101        } else if self.context_prefix.is_empty() {
102            format!("mcard:{}", clean)
103        } else {
104            format!("mcard:{}/{}", self.context_prefix, clean)
105        }
106    }
107
108    /// Ephemerally mounts a scoped MCardFileSystem on a Fiber, registering a LIFO unmount
109    /// callback on the fiber's DisposableList that cleans up all transient handles on disposal (DOD-191-07).
110    pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
111        let scoped_fs = self.with_prefix(prefix);
112        let prefix_clean = prefix.trim_matches('/').to_string();
113        let handle_pattern = if prefix_clean.is_empty() {
114            "mcard:%".to_string()
115        } else {
116            format!("mcard:{}/%", prefix_clean)
117        };
118        let conn_clone = self.conn.clone();
119
120        fiber.register_disposable(move || {
121            let conn = conn_clone.lock().map_err(|e| e.to_string())?;
122            conn.execute(
123                "DELETE FROM handle_history WHERE handle LIKE ?1",
124                rusqlite::params![&handle_pattern],
125            )
126            .map_err(|e| e.to_string())?;
127            conn.execute(
128                "DELETE FROM handle_registry WHERE handle LIKE ?1",
129                rusqlite::params![&handle_pattern],
130            )
131            .map_err(|e| e.to_string())?;
132            Ok(())
133        });
134
135        Ok(scoped_fs)
136    }
137
138    /// Ensures the canonical Tri-Database schema exists (INV-04, INV-05).
139    fn init_schema(conn: &Connection) -> Result<()> {
140        conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)?;
141        Ok(())
142    }
143
144    /// Writes an MCard into the filesystem, content-addressing the payload and updating the handle registry.
145    pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
146        let canonical_uri = self.canonicalize_uri(uri);
147        let now = crate::utils::now_iso8601();
148        let mut conn = self
149            .conn
150            .lock()
151            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
152
153        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
154
155        // 1. Check existing handle state to maintain sequence
156        let existing: Option<String> = {
157            let mut stmt = tx.prepare_cached(
158                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
159            )?;
160            stmt.query_row(params![&canonical_uri], |row| row.get(0))
161                .ok()
162        };
163
164        let seq = match &existing {
165            Some(_) => {
166                // Determine next sequence from history count
167                let mut count_stmt = tx.prepare_cached(
168                    "SELECT count(*) FROM handle_history WHERE handle = ?1",
169                )?;
170                let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
171                (count as u64) + 2
172            }
173            None => 1,
174        };
175
176        // 2. Construct canonical MCard and its envelope record.
177        //
178        // The handle binds the *file*, and the file is an envelope record: a separate structured
179        // record whose digest covers its own canonical bytes (charter L3). The MCard identity it
180        // carries is the payload hash. Previously the row stored the envelope while the digest was
181        // computed over the payload only, and the coordinate was a bare ISO timestamp — so
182        // `hash != H(a, content)` and the row could not verify itself.
183        let mcard = MCard::new(&canonical_uri, payload, author, seq);
184        let envelope = crate::layer0::codec::canonical_json(&mcard).map_err(|e| e.to_string())?;
185        let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
186            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
187        let hash_str = record.hash.clone();
188
189        // 3. Insert the self-verifying envelope record (INV-02, INV-05)
190        {
191            let mut stmt_card = tx.prepare_cached(
192                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
193            )?;
194            stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
195        }
196
197        // 4. Update handle history if previous hash exists and differs (G-Set tracking)
198        if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
199            let mut stmt_hist = tx.prepare_cached(
200                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
201            )?;
202            stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
203        }
204
205        // 5. Update or insert handle registry entry (INV-04)
206        {
207            let mut stmt_reg = tx.prepare_cached(
208                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
209                 VALUES (?1, ?2, ?3)",
210            )?;
211            stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
212        }
213
214        tx.commit()?;
215        Ok(mcard)
216    }
217
218    /// Reads and cryptographically verifies an MCard by its URI handle (INV-02, INV-04).
219    pub fn read_file(&self, uri: &str) -> Result<MCard> {
220        let canonical_uri = self.canonicalize_uri(uri);
221        let conn = self
222            .conn
223            .lock()
224            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
225
226        // 1. Resolve handle to current hash
227        let current_hash: String = {
228            let mut stmt = conn.prepare_cached(
229                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
230            )?;
231            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
232                ClmError::storage(
233                    StorageErrorCode::CardNotFound,
234                    format!("Handle '{}' not found in MCardFs", canonical_uri),
235                )
236            })?
237        };
238
239        // 2. Fetch the stored row (content + coordinate)
240        let (content, g_time): (Vec<u8>, String) = {
241            let mut stmt = conn.prepare_cached("SELECT content, g_time FROM card WHERE hash = ?1")?;
242            stmt.query_row(params![current_hash], |row| Ok((row.get(0)?, row.get(1)?)))
243                .map_err(|_| {
244                    ClmError::storage(
245                        StorageErrorCode::CorruptedContent,
246                        format!("Card content for hash '{}' not found", current_hash),
247                    )
248                })?
249        };
250
251        // 3. Verify the row from the row alone, then deserialize the envelope.
252        let record = crate::layer0::mcard_record::MCardRecord {
253            hash: current_hash.clone(),
254            content: content.clone(),
255            g_time: g_time.clone(),
256        };
257        if !matches!(
258            crate::layer0::mcard_record::verify_record(&record),
259            crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
260        ) {
261            return Err(ClmError::storage(
262                StorageErrorCode::CorruptedContent,
263                format!("Cryptographic mismatch for handle '{}': stored row does not verify", canonical_uri),
264            ));
265        }
266
267        let mcard: MCard = serde_json::from_slice(&content)?;
268        Ok(mcard)
269    }
270
271    /// Checks if an MCard exists by its handle URI.
272    pub fn exists(&self, uri: &str) -> Result<bool> {
273        let canonical_uri = self.canonicalize_uri(uri);
274        let conn = self
275            .conn
276            .lock()
277            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
278        let mut stmt = conn.prepare_cached(
279            "SELECT count(*) FROM handle_registry WHERE handle = ?1",
280        )?;
281        let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
282        Ok(count > 0)
283    }
284
285    /// Returns stat metadata for a virtual file.
286    pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
287        let canonical_uri = self.canonicalize_uri(uri);
288        let conn = self
289            .conn
290            .lock()
291            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
292
293        let (hash_str, updated_at): (String, String) = {
294            let mut stmt = conn.prepare_cached(
295                "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
296            )?;
297            stmt.query_row(params![&canonical_uri], |row| {
298                Ok((row.get(0)?, row.get(1)?))
299            })
300            .map_err(|_| {
301                ClmError::storage(
302                    StorageErrorCode::CardNotFound,
303                    format!("Handle '{}' not found", canonical_uri),
304                )
305            })?
306        };
307
308        let created_at: String = {
309            let mut stmt = conn.prepare_cached(
310                "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
311            )?;
312            stmt.query_row(params![&canonical_uri], |row| row.get(0))
313                .unwrap_or_else(|_| updated_at.clone())
314        };
315
316        let size_bytes: usize = {
317            let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
318            stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
319                .unwrap_or(0) as usize
320        };
321
322        // `stat.hash` names the MCard (the payload digest carried in the envelope record), not
323        // the envelope record's own digest.
324        let hash = {
325            let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
326            let body: Vec<u8> = stmt.query_row(params![hash_str], |row| row.get(0)).unwrap_or_default();
327            match serde_json::from_slice::<MCard>(&body) {
328                Ok(envelope) => ContentHash::parse(&envelope.hash)?,
329                Err(_) => ContentHash::parse(&hash_str)?,
330            }
331        };
332        Ok(MCardStat {
333            uri: canonical_uri,
334            hash,
335            size_bytes,
336            created_at,
337            updated_at,
338        })
339    }
340
341    /// Lists all MCard handles sharing the specified URI prefix.
342    pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
343        let conn = self
344            .conn
345            .lock()
346            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
347
348        let canonical_prefix = self.canonicalize_uri(prefix);
349        let pattern = if canonical_prefix.ends_with('/') {
350            format!("{}%", canonical_prefix)
351        } else if canonical_prefix == "mcard:" {
352            "mcard:%".to_string()
353        } else {
354            format!("{}/%", canonical_prefix)
355        };
356
357        let mut stmt = conn.prepare_cached(
358            "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
359        )?;
360        let rows = stmt.query_map(params![pattern], |row| row.get(0))?;
361
362        let mut handles = Vec::new();
363        for handle in rows {
364            handles.push(handle?);
365        }
366        Ok(handles)
367    }
368
369    /// Deregisters an MCard handle, preserving the underlying immutable CAS blob (INV-04).
370    pub fn delete_file(&self, uri: &str) -> Result<()> {
371        let canonical_uri = self.canonicalize_uri(uri);
372        let mut conn = self
373            .conn
374            .lock()
375            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
376
377        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
378        {
379            // Remove handle history records first to satisfy foreign key constraint on handle_registry
380            let mut stmt_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
381            stmt_hist.execute(params![&canonical_uri])?;
382
383            // Remove from active registry
384            let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
385            let affected = stmt_del.execute(params![&canonical_uri])?;
386
387            if affected == 0 {
388                return Err(ClmError::storage(
389                    StorageErrorCode::CardNotFound,
390                    format!("Handle '{}' not found for deletion", canonical_uri),
391                ));
392            }
393        }
394        tx.commit()?;
395        Ok(())
396    }
397}
398