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                updated_at TEXT NOT NULL
145            );
146
147            CREATE TABLE IF NOT EXISTS handle_history (
148                handle TEXT NOT NULL,
149                previous_hash TEXT NOT NULL,
150                changed_at TEXT NOT NULL
151            );
152
153            CREATE INDEX IF NOT EXISTS idx_handle_reg_prefix ON handle_registry(handle);
154            "#,
155        )?;
156        Ok(())
157    }
158
159    /// Writes an MCard into the filesystem, content-addressing the payload and updating the handle registry.
160    pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
161        let canonical_uri = self.canonicalize_uri(uri);
162        let now = crate::utils::now_iso8601();
163        let mut conn = self
164            .conn
165            .lock()
166            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
167
168        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
169
170        // 1. Check existing handle state to maintain sequence
171        let existing: Option<String> = {
172            let mut stmt = tx.prepare_cached(
173                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
174            )?;
175            stmt.query_row(params![&canonical_uri], |row| row.get(0))
176                .ok()
177        };
178
179        let seq = match &existing {
180            Some(_) => {
181                // Determine next sequence from history count
182                let mut count_stmt = tx.prepare_cached(
183                    "SELECT count(*) FROM handle_history WHERE handle = ?1",
184                )?;
185                let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
186                (count as u64) + 2
187            }
188            None => 1,
189        };
190
191        // 2. Construct canonical MCard & serialize
192        let mcard = MCard::new(&canonical_uri, payload, author, seq);
193        let serialized_card = serde_json::to_string(&mcard)?;
194        let hash_str = mcard.hash.as_str();
195
196        // 3. Insert CAS card blob (INV-02, INV-05)
197        {
198            let mut stmt_card = tx.prepare_cached(
199                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
200            )?;
201            stmt_card.execute(params![hash_str, serialized_card, now])?;
202        }
203
204        // 4. Update handle history if previous hash exists and differs (G-Set tracking)
205        if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
206            let mut stmt_hist = tx.prepare_cached(
207                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
208            )?;
209            stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
210        }
211
212        // 5. Update or insert handle registry entry (INV-04)
213        {
214            let mut stmt_reg = tx.prepare_cached(
215                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
216                 VALUES (?1, ?2, ?3)",
217            )?;
218            stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
219        }
220
221        tx.commit()?;
222        Ok(mcard)
223    }
224
225    /// Reads and cryptographically verifies an MCard by its URI handle (INV-02, INV-04).
226    pub fn read_file(&self, uri: &str) -> Result<MCard> {
227        let canonical_uri = self.canonicalize_uri(uri);
228        let conn = self
229            .conn
230            .lock()
231            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
232
233        // 1. Resolve handle to current hash
234        let current_hash: String = {
235            let mut stmt = conn.prepare_cached(
236                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
237            )?;
238            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
239                ClmError::storage(
240                    StorageErrorCode::CardNotFound,
241                    format!("Handle '{}' not found in MCardFs", canonical_uri),
242                )
243            })?
244        };
245
246        // 2. Fetch CAS card content
247        let content: String = {
248            let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
249            stmt.query_row(params![current_hash], |row| row.get(0))
250                .map_err(|_| {
251                    ClmError::storage(
252                        StorageErrorCode::CorruptedContent,
253                        format!("Card content for hash '{}' not found", current_hash),
254                    )
255                })?
256        };
257
258        // 3. Deserialize and verify zero-trust cryptographic identity
259        let mcard: MCard = serde_json::from_str(&content)?;
260        let expected_payload_bytes = serde_json::to_vec(&mcard.payload)?;
261        let expected_hash = ContentHash::compute(&expected_payload_bytes);
262
263        if expected_hash.as_str() != current_hash {
264            return Err(ClmError::storage(
265                StorageErrorCode::CorruptedContent,
266                format!(
267                    "Cryptographic mismatch for handle '{}': registry={} computed={}",
268                    canonical_uri, current_hash, expected_hash
269                ),
270            ));
271        }
272
273        Ok(mcard)
274    }
275
276    /// Checks if an MCard exists by its handle URI.
277    pub fn exists(&self, uri: &str) -> Result<bool> {
278        let canonical_uri = self.canonicalize_uri(uri);
279        let conn = self
280            .conn
281            .lock()
282            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
283        let mut stmt = conn.prepare_cached(
284            "SELECT count(*) FROM handle_registry WHERE handle = ?1",
285        )?;
286        let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
287        Ok(count > 0)
288    }
289
290    /// Returns stat metadata for a virtual file.
291    pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
292        let canonical_uri = self.canonicalize_uri(uri);
293        let conn = self
294            .conn
295            .lock()
296            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
297
298        let (hash_str, updated_at): (String, String) = {
299            let mut stmt = conn.prepare_cached(
300                "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
301            )?;
302            stmt.query_row(params![&canonical_uri], |row| {
303                Ok((row.get(0)?, row.get(1)?))
304            })
305            .map_err(|_| {
306                ClmError::storage(
307                    StorageErrorCode::CardNotFound,
308                    format!("Handle '{}' not found", canonical_uri),
309                )
310            })?
311        };
312
313        let created_at: String = {
314            let mut stmt = conn.prepare_cached(
315                "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
316            )?;
317            stmt.query_row(params![&canonical_uri], |row| row.get(0))
318                .unwrap_or_else(|_| updated_at.clone())
319        };
320
321        let size_bytes: usize = {
322            let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
323            stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
324                .unwrap_or(0) as usize
325        };
326
327        let hash = ContentHash::parse(&hash_str)?;
328        Ok(MCardStat {
329            uri: canonical_uri,
330            hash,
331            size_bytes,
332            created_at,
333            updated_at,
334        })
335    }
336
337    /// Lists all MCard handles sharing the specified URI prefix.
338    pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
339        let conn = self
340            .conn
341            .lock()
342            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
343
344        let canonical_prefix = self.canonicalize_uri(prefix);
345        let pattern = if canonical_prefix.ends_with('/') {
346            format!("{}%", canonical_prefix)
347        } else if canonical_prefix == "mcard:" {
348            "mcard:%".to_string()
349        } else {
350            format!("{}/%", canonical_prefix)
351        };
352
353        let mut stmt = conn.prepare_cached(
354            "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
355        )?;
356        let rows = stmt.query_map(params![pattern], |row| row.get(0))?;
357
358        let mut handles = Vec::new();
359        for handle in rows {
360            handles.push(handle?);
361        }
362        Ok(handles)
363    }
364
365    /// Deregisters an MCard handle, preserving the underlying immutable CAS blob (INV-04).
366    pub fn delete_file(&self, uri: &str) -> Result<()> {
367        let canonical_uri = self.canonicalize_uri(uri);
368        let now = crate::utils::now_iso8601();
369        let mut conn = self
370            .conn
371            .lock()
372            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
373
374        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
375        {
376            // Record deletion in history
377            let mut stmt_hist = tx.prepare_cached(
378                "INSERT INTO handle_history (handle, previous_hash, changed_at) \
379                 SELECT handle, current_hash, ?1 FROM handle_registry WHERE handle = ?2",
380            )?;
381            stmt_hist.execute(params![now, &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}