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