clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! MCard Universal Virtual Filesystem Engine (Sprint 191).
//!
//! Enforces:
//! 1. Zero-FS Hermeticity (INV-09): Operates in-memory or on SQLite CAS without host disk I/O.
//! 2. Handle Registry Singularity (INV-04) & Tri-Database Separation (INV-05):
//!    Directly wraps canonical `card`, `handle_registry`, and `handle_history` tables.
//! 3. Content-Addressable Identity (INV-02): hashes follow each row's declared g_time algorithm.
//! 4. Spatiotemporal Compositionality: Mountable in Cordis Context for scoped fiber execution.

use crate::{domain::{MCard, MCardPayload}, layer0::vocabulary::HANDLE_MCARD};
use crate::error::{ClmError, Result, StorageErrorCode};
use crate::types::{AgentDid, ContentHash};
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

/// File metadata stat for an MCard in the virtual filesystem.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardStat {
    pub uri: String,
    pub hash: ContentHash,
    pub size_bytes: usize,
    pub created_at: String,
    pub updated_at: String,
}

pub use crate::layer2::vfs::{DirectoryManifest, DirectoryManifestEntry};

/// The universal immutable filesystem engine mapping URIs to content-addressed MCards.
#[derive(Clone)]
pub struct MCardFileSystem {
    pub(crate) conn: Arc<Mutex<Connection>>,
    pub(crate) context_prefix: String,
}

/// Kind marker for the record that retires a handle.
const TOMBSTONE_KIND: &str = "TOMBSTONE";

/// True when a handle head names a retirement record rather than live content.
fn head_is_tombstone(conn: &Connection, hash: &str) -> Result<bool> {
    let record = crate::layer2::record_store::read_record(conn, hash)?
        .ok_or_else(|| ClmError::storage(StorageErrorCode::CorruptedContent, "handle points to missing card"))?;
    let bytes = record.content;
    if bytes.len() > 4096 {
        return Ok(false);
    }
    Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
        .ok()
        .and_then(|v| {
            v.get("kind")
                .and_then(|k| k.as_str())
                .map(|k| k == TOMBSTONE_KIND)
        })
        .unwrap_or(false))
}

/// Names a stored row the way a transition record does: `<algorithm>:<hex>`.
fn qualified_ref(conn: &Connection, hash: &str) -> Result<String> {
    let record = crate::layer2::record_store::read_record(conn, hash)?
        .ok_or_else(|| ClmError::storage(StorageErrorCode::CorruptedContent, "handle points to missing card"))?;
    let algorithm = crate::layer2::record_store::require_verified(&record)?;
    Ok(format!("{algorithm}:{}", record.hash))
}

impl MCardFileSystem {
    /// Initializes an isolated, zero-disk in-memory MCard filesystem (INV-09).
    pub fn new_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        Self::init_schema(&conn)?;
        Ok(Self {
            conn: Arc::new(Mutex::new(conn)),
            context_prefix: String::new(),
        })
    }

    /// Initializes an in-memory MCard filesystem scoped to a specific context prefix.
    pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
        let mut fs = Self::new_in_memory()?;
        fs.context_prefix = prefix.trim_matches('/').to_string();
        Ok(fs)
    }

    /// Wraps an existing SQLite connection manager or shared connection with an optional context prefix.
    pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
        Self {
            conn,
            context_prefix: context_prefix.trim_matches('/').to_string(),
        }
    }

    /// Wraps an existing SQLite connection manager or shared connection (root prefix).
    pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
        {
            let locked = conn
                .lock()
                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
            Self::init_schema(&locked)?;
        }
        Ok(Self {
            conn,
            context_prefix: String::new(),
        })
    }

    /// Returns a new `MCardFileSystem` handle sharing the same storage but isolated to `prefix`.
    pub fn with_prefix(&self, prefix: &str) -> Self {
        Self {
            conn: self.conn.clone(),
            context_prefix: prefix.trim_matches('/').to_string(),
        }
    }

    /// Returns the active context prefix for this filesystem handle.
    pub fn context_prefix(&self) -> &str {
        &self.context_prefix
    }

    /// Resolves canonical URI with context prefix scoping (DOD-191-04).
    pub fn canonicalize_uri(&self, path: &str) -> String {
        let clean = path.trim_start_matches('/');
        if let Some(rest) = clean.strip_prefix(crate::layer0::vocabulary::HANDLE_MCARD) {
            let rest_clean = rest.trim_start_matches('/');
            if self.context_prefix.is_empty() {
                format!("{HANDLE_MCARD}{}", rest_clean)
            } else if rest_clean.starts_with(&self.context_prefix) {
                format!("{HANDLE_MCARD}{}", rest_clean)
            } else {
                format!("{HANDLE_MCARD}{}/{}", self.context_prefix, rest_clean)
            }
        } else if self.context_prefix.is_empty() {
            format!("{HANDLE_MCARD}{}", clean)
        } else {
            format!("{HANDLE_MCARD}{}/{}", self.context_prefix, clean)
        }
    }

    /// Ephemerally mounts a scoped MCardFileSystem on a Fiber, registering a LIFO unmount
    /// callback on the fiber's DisposableList that cleans up all transient handles on disposal (DOD-191-07).
    pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
        let scoped_fs = self.with_prefix(prefix);
        let prefix_clean = prefix.trim_matches('/').to_string();
        let handle_pattern = if prefix_clean.is_empty() {
            crate::layer0::vocabulary::HANDLE_MCARD_3.to_string()
        } else {
            format!("{HANDLE_MCARD}{}/%", prefix_clean)
        };
        let conn_clone = self.conn.clone();

        fiber.register_disposable(move || {
            let conn = conn_clone.lock().map_err(|e| e.to_string())?;
            conn.execute(
                "DELETE FROM handle_history WHERE handle LIKE ?1",
                rusqlite::params![&handle_pattern],
            )
            .map_err(|e| e.to_string())?;
            conn.execute(
                "DELETE FROM handle_registry WHERE handle LIKE ?1",
                rusqlite::params![&handle_pattern],
            )
            .map_err(|e| e.to_string())?;
            Ok(())
        });

        Ok(scoped_fs)
    }

    /// Ensures the canonical Tri-Database schema exists (INV-04, INV-05).
    fn init_schema(conn: &Connection) -> Result<()> {
        conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)?;
        Ok(())
    }

    /// Writes an MCard into the filesystem, content-addressing the payload and updating the handle registry.
    pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
        let canonical_uri = self.canonicalize_uri(uri);
        let now = crate::utils::now_iso8601();
        let mut conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;

        // 1. Check existing handle state to maintain sequence
        let existing: Option<String> = {
            let mut stmt = tx.prepare_cached(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0))
                .ok()
        };

        let seq = match &existing {
            Some(_) => {
                // Determine next sequence from history count
                let mut count_stmt = tx.prepare_cached(
                    "SELECT count(*) FROM handle_history WHERE handle = ?1",
                )?;
                let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
                (count as u64) + 2
            }
            None => 1,
        };

        // 2. Construct canonical MCard and its envelope record. The handle binds the *file*, whose
        // digest covers its own canonical bytes; the MCard identity it carries is the payload hash.
        let mcard = MCard::new(&canonical_uri, payload, author, seq);
        let envelope = crate::layer0::mcard_projection::encode_content(&mcard)?;
        let record = crate::layer0::mcard_record::MCardRecord::create(&envelope, None)
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
        let hash_str = record.hash.clone();
        let mcard: MCard = crate::layer0::mcard_projection::project_record(&record)?;

        crate::layer2::record_store::insert_record(&tx, &record)?;

        // 4. Update handle history if previous hash exists and differs (G-Set tracking)
        if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
            let mut stmt_hist = tx.prepare_cached(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
            )?;
            stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
        }

        // 5. Update or insert handle registry entry (INV-04)
        {
            let mut stmt_reg = tx.prepare_cached(
                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
                 VALUES (?1, ?2, ?3)",
            )?;
            stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
        }

        tx.commit()?;
        Ok(mcard)
    }

    /// Reads and cryptographically verifies an MCard by its URI handle (INV-02, INV-04).
    pub fn read_file(&self, uri: &str) -> Result<MCard> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        // 1. Resolve handle to current hash
        let current_hash: String = {
            let mut stmt = conn.prepare_cached(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found in MCardFs", canonical_uri),
                )
            })?
        };

        if head_is_tombstone(&conn, &current_hash)? {
            return Err(ClmError::storage(
                StorageErrorCode::CardNotFound,
                format!("Handle '{}' is retired", canonical_uri),
            ));
        }

        let record = crate::layer2::record_store::read_record(&conn, &current_hash)?
            .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "stored card is missing"))?;
        crate::layer0::mcard_projection::project_record(&record)
            .map_err(|error| ClmError::storage(StorageErrorCode::CorruptedContent, error))
    }

    /// Checks if an MCard exists by its handle URI.
    pub fn exists(&self, uri: &str) -> Result<bool> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
        let head: Option<String> = {
            let mut stmt = conn.prepare_cached(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0)).ok()
        };
        match head {
            Some(hash) => Ok(!head_is_tombstone(&conn, &hash)?),
            None => Ok(false),
        }
    }

    /// Returns stat metadata for a virtual file.
    pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let (hash_str, updated_at): (String, String) = {
            let mut stmt = conn.prepare_cached(
                "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| {
                Ok((row.get(0)?, row.get(1)?))
            })
            .map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found", canonical_uri),
                )
            })?
        };

        if head_is_tombstone(&conn, &hash_str)? {
            return Err(ClmError::storage(
                StorageErrorCode::CardNotFound,
                format!("Handle '{}' is retired", canonical_uri),
            ));
        }

        let created_at: String = {
            let mut stmt = conn.prepare_cached(
                "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0))
                .unwrap_or_else(|_| updated_at.clone())
        };

        let record = crate::layer2::record_store::read_record(&conn, &hash_str)?
            .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "stored card is missing"))?;
        let size_bytes = record.content.len();
        let hash = ContentHash::parse(&record.hash)?;
        Ok(MCardStat {
            uri: canonical_uri,
            hash,
            size_bytes,
            created_at,
            updated_at,
        })
    }

    /// Lists all MCard handles sharing the specified URI prefix.
    pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let canonical_prefix = self.canonicalize_uri(prefix);
        let pattern = if canonical_prefix.ends_with('/') {
            format!("{}%", canonical_prefix)
        } else if canonical_prefix == crate::layer0::vocabulary::HANDLE_MCARD {
            crate::layer0::vocabulary::HANDLE_MCARD_3.to_string()
        } else {
            format!("{}/%", canonical_prefix)
        };

        let mut stmt = conn.prepare_cached(
            "SELECT handle, current_hash FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
        )?;
        let rows = stmt.query_map(params![pattern], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })?;

        let mut handles = Vec::new();
        for row in rows {
            let (handle, head) = row?;
            if !head_is_tombstone(&conn, &head)? {
                handles.push(handle);
            }
        }
        Ok(handles)
    }

    /// Retires an MCard handle by appending a TOMBSTONE record and binding the head to it.
    ///
    /// Retirement is a name-plane event: the content card stays readable by hash, the handle row
    /// and its history stay on the tape, and `current_hash` names the record that retired it.
    pub fn retire(&self, uri: &str, reason: Option<&str>, author: AgentDid) -> Result<()> {
        let canonical_uri = self.canonicalize_uri(uri);
        let now = crate::utils::now_iso8601();
        let mut conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;

        let previous_hash: String = {
            let mut stmt = tx.prepare_cached(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found for retirement", canonical_uri),
                )
            })?
        };

        let qualified_from = qualified_ref(&tx, &previous_hash)?;
        let mut payload = serde_json::json!({
            "kind": TOMBSTONE_KIND,
            "handle": canonical_uri,
            "from": qualified_from,
            "to": serde_json::Value::Null,
            "author": author.as_str(),
            "retiredAt": now,
        });
        if let Some(reason) = reason {
            payload["reason"] = serde_json::Value::String(reason.to_string());
        }
        let envelope = crate::layer0::codec::canonical_json(&payload).map_err(|e| e.to_string())?;
        let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;

        crate::layer2::record_store::insert_record(&tx, &record)?;
        tx.execute(
            "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
            params![&canonical_uri, &previous_hash, now],
        )?;
        // UPDATE, not REPLACE: a replace deletes the row the history row just references.
        tx.execute(
            "UPDATE handle_registry SET current_hash = ?1, updated_at = ?2 WHERE handle = ?3",
            params![&record.hash, now, &canonical_uri],
        )?;

        tx.commit()?;
        Ok(())
    }

    /// Retires an MCard handle, preserving the underlying immutable CAS blob (INV-04).
    pub fn delete_file(&self, uri: &str) -> Result<()> {
        self.retire(uri, None, AgentDid::parse(crate::layer0::vocabulary_identities::DID_CLM_AGENT_DEFAULT)?)
    }
}