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 and its envelope record.
192        //
193        // The handle binds the *file*, and the file is an envelope record: a separate structured
194        // record whose digest covers its own canonical bytes (charter L3). The MCard identity it
195        // carries is the payload hash. Previously the row stored the envelope while the digest was
196        // computed over the payload only, and the coordinate was a bare ISO timestamp — so
197        // `hash != H(a, content)` and the row could not verify itself.
198        let mcard = MCard::new(&canonical_uri, payload, author, seq);
199        let envelope = crate::layer0::codec::canonical_json(&mcard).map_err(|e| e.to_string())?;
200        let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
201            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
202        let hash_str = record.hash.clone();
203
204        // 3. Insert the self-verifying envelope record (INV-02, INV-05)
205        {
206            let mut stmt_card = tx.prepare_cached(
207                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
208            )?;
209            stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
210        }
211
212        // 4. Update handle history if previous hash exists and differs (G-Set tracking)
213        if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
214            let mut stmt_hist = tx.prepare_cached(
215                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
216            )?;
217            stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
218        }
219
220        // 5. Update or insert handle registry entry (INV-04)
221        {
222            let mut stmt_reg = tx.prepare_cached(
223                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
224                 VALUES (?1, ?2, ?3)",
225            )?;
226            stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
227        }
228
229        tx.commit()?;
230        Ok(mcard)
231    }
232
233    /// Reads and cryptographically verifies an MCard by its URI handle (INV-02, INV-04).
234    pub fn read_file(&self, uri: &str) -> Result<MCard> {
235        let canonical_uri = self.canonicalize_uri(uri);
236        let conn = self
237            .conn
238            .lock()
239            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
240
241        // 1. Resolve handle to current hash
242        let current_hash: String = {
243            let mut stmt = conn.prepare_cached(
244                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
245            )?;
246            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
247                ClmError::storage(
248                    StorageErrorCode::CardNotFound,
249                    format!("Handle '{}' not found in MCardFs", canonical_uri),
250                )
251            })?
252        };
253
254        // 2. Fetch the stored row (content + coordinate)
255        let (content, g_time): (Vec<u8>, String) = {
256            let mut stmt = conn.prepare_cached("SELECT content, g_time FROM card WHERE hash = ?1")?;
257            stmt.query_row(params![current_hash], |row| Ok((row.get(0)?, row.get(1)?)))
258                .map_err(|_| {
259                    ClmError::storage(
260                        StorageErrorCode::CorruptedContent,
261                        format!("Card content for hash '{}' not found", current_hash),
262                    )
263                })?
264        };
265
266        // 3. Verify the row from the row alone, then deserialize the envelope.
267        let record = crate::layer0::mcard_record::MCardRecord {
268            hash: current_hash.clone(),
269            content: content.clone(),
270            g_time: g_time.clone(),
271        };
272        if !matches!(
273            crate::layer0::mcard_record::verify_record(&record),
274            crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
275        ) {
276            return Err(ClmError::storage(
277                StorageErrorCode::CorruptedContent,
278                format!("Cryptographic mismatch for handle '{}': stored row does not verify", canonical_uri),
279            ));
280        }
281
282        let mcard: MCard = serde_json::from_slice(&content)?;
283        Ok(mcard)
284    }
285
286    /// Checks if an MCard exists by its handle URI.
287    pub fn exists(&self, uri: &str) -> Result<bool> {
288        let canonical_uri = self.canonicalize_uri(uri);
289        let conn = self
290            .conn
291            .lock()
292            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
293        let mut stmt = conn.prepare_cached(
294            "SELECT count(*) FROM handle_registry WHERE handle = ?1",
295        )?;
296        let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
297        Ok(count > 0)
298    }
299
300    /// Returns stat metadata for a virtual file.
301    pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
302        let canonical_uri = self.canonicalize_uri(uri);
303        let conn = self
304            .conn
305            .lock()
306            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
307
308        let (hash_str, updated_at): (String, String) = {
309            let mut stmt = conn.prepare_cached(
310                "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
311            )?;
312            stmt.query_row(params![&canonical_uri], |row| {
313                Ok((row.get(0)?, row.get(1)?))
314            })
315            .map_err(|_| {
316                ClmError::storage(
317                    StorageErrorCode::CardNotFound,
318                    format!("Handle '{}' not found", canonical_uri),
319                )
320            })?
321        };
322
323        let created_at: String = {
324            let mut stmt = conn.prepare_cached(
325                "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
326            )?;
327            stmt.query_row(params![&canonical_uri], |row| row.get(0))
328                .unwrap_or_else(|_| updated_at.clone())
329        };
330
331        let size_bytes: usize = {
332            let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
333            stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
334                .unwrap_or(0) as usize
335        };
336
337        // `stat.hash` names the MCard (the payload digest carried in the envelope record), not
338        // the envelope record's own digest.
339        let hash = {
340            let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
341            let body: Vec<u8> = stmt.query_row(params![hash_str], |row| row.get(0)).unwrap_or_default();
342            match serde_json::from_slice::<MCard>(&body) {
343                Ok(envelope) => ContentHash::parse(&envelope.hash)?,
344                Err(_) => ContentHash::parse(&hash_str)?,
345            }
346        };
347        Ok(MCardStat {
348            uri: canonical_uri,
349            hash,
350            size_bytes,
351            created_at,
352            updated_at,
353        })
354    }
355
356    /// Lists all MCard handles sharing the specified URI prefix.
357    pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
358        let conn = self
359            .conn
360            .lock()
361            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
362
363        let canonical_prefix = self.canonicalize_uri(prefix);
364        let pattern = if canonical_prefix.ends_with('/') {
365            format!("{}%", canonical_prefix)
366        } else if canonical_prefix == "mcard:" {
367            "mcard:%".to_string()
368        } else {
369            format!("{}/%", canonical_prefix)
370        };
371
372        let mut stmt = conn.prepare_cached(
373            "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
374        )?;
375        let rows = stmt.query_map(params![pattern], |row| row.get(0))?;
376
377        let mut handles = Vec::new();
378        for handle in rows {
379            handles.push(handle?);
380        }
381        Ok(handles)
382    }
383
384    /// Deregisters an MCard handle, preserving the underlying immutable CAS blob (INV-04).
385    pub fn delete_file(&self, uri: &str) -> Result<()> {
386        let canonical_uri = self.canonicalize_uri(uri);
387        let now = crate::utils::now_iso8601();
388        let mut conn = self
389            .conn
390            .lock()
391            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
392
393        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
394        {
395            // Record deletion in history
396            let mut stmt_hist = tx.prepare_cached(
397                "INSERT INTO handle_history (handle, previous_hash, changed_at) \
398                 SELECT handle, current_hash, ?1 FROM handle_registry WHERE handle = ?2",
399            )?;
400            stmt_hist.execute(params![now, &canonical_uri])?;
401
402            // Remove from active registry
403            let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
404            let affected = stmt_del.execute(params![&canonical_uri])?;
405
406            if affected == 0 {
407                return Err(ClmError::storage(
408                    StorageErrorCode::CardNotFound,
409                    format!("Handle '{}' not found for deletion", canonical_uri),
410                ));
411            }
412        }
413        tx.commit()?;
414        Ok(())
415    }
416}