clm-kernel 0.0.12

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
//! Layer 2: MCard Virtual Filesystem (VFS) & Deterministic DirectoryManifest (Sprint 510)
//! Canonical Path: kernel/clm_rust_core/src/layer2/vfs.rs

use crate::error::{ClmError, Result, StorageErrorCode};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
pub use crate::mcard_fs::{MCardFileSystem, MCardStat};
use rusqlite::params;
use serde::{Deserialize, Serialize};

/// Deterministic child entry inside a `DirectoryManifest` `MCard` (`INV-510-04`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectoryManifestEntry {
    pub name: String,
    pub kind: String,
    pub target_ref: String,
    #[serde(default)]
    pub metadata_ref: Option<String>,
}

/// Deterministic, content-addressed directory manifest `MCard` (`INV-510-04`).
///
/// Entries are canonically sorted by `(name, kind, target_ref, metadata_ref)` before
/// JCS-style canonical JSON serialization so child permutation does not change identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectoryManifest {
    pub entries: Vec<DirectoryManifestEntry>,
    pub algorithm: String,
}

impl DirectoryManifest {
    pub fn new(entries: Vec<DirectoryManifestEntry>, algorithm: Option<&str>) -> Self {
        Self {
            entries,
            algorithm: algorithm.unwrap_or("blake3").to_string(),
        }
    }

    /// Returns entries canonically sorted by `(name, kind, target_ref, metadata_ref)`.
    pub fn sorted_entries(&self) -> Vec<DirectoryManifestEntry> {
        let mut sorted = self.entries.clone();
        sorted.sort_by(|a, b| {
            (&a.name, &a.kind, &a.target_ref, a.metadata_ref.as_deref().unwrap_or(""))
                .cmp(&(&b.name, &b.kind, &b.target_ref, b.metadata_ref.as_deref().unwrap_or("")))
        });
        sorted
    }

    /// Serializes the manifest to canonical UTF-8 JSON bytes (`INV-510-04`).
    pub fn to_canonical_bytes(&self) -> Vec<u8> {
        let entries_json: Vec<serde_json::Value> = self
            .sorted_entries()
            .into_iter()
            .map(|e| {
                serde_json::json!({
                    "kind": e.kind,
                    "metadata_ref": e.metadata_ref,
                    "name": e.name,
                    "target_ref": e.target_ref,
                })
            })
            .collect();
        let doc = serde_json::json!({
            "entries": entries_json,
            "schema": "clm://layer2/directory_manifest/v1",
        });
        crate::domain::to_canonical_json_bytes(&doc)
    }

    /// Reifies the `DirectoryManifest` into a content-addressed `MCardRecord`.
    pub fn to_mcard_record(&self) -> Result<MCardRecord> {
        MCardRecord::create(&self.to_canonical_bytes(), Some(&self.algorithm))
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))
    }

    /// Returns the qualified `a:hex` reference for this manifest (`INV-510-04`).
    pub fn qualified_ref(&self) -> Result<String> {
        let rec = self.to_mcard_record()?;
        Ok(format!("{}:{}", self.algorithm, rec.hash))
    }

    /// Parses a `DirectoryManifest` from canonical JSON bytes.
    pub fn from_canonical_bytes(raw: &[u8], algorithm: Option<&str>) -> Result<Self> {
        let val: serde_json::Value = serde_json::from_slice(raw)?;
        let entries_arr = val
            .get("entries")
            .and_then(|v| v.as_array())
            .ok_or_else(|| {
                ClmError::storage(
                    StorageErrorCode::CorruptedContent,
                    "Invalid DirectoryManifest entries".to_string(),
                )
            })?;
        let mut entries = Vec::with_capacity(entries_arr.len());
        for item in entries_arr {
            entries.push(DirectoryManifestEntry {
                name: item
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                kind: item
                    .get("kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("file")
                    .to_string(),
                target_ref: item
                    .get("target_ref")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                metadata_ref: item
                    .get("metadata_ref")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
            });
        }
        Ok(Self::new(entries, algorithm))
    }
}

impl MCardFileSystem {
    /// Writes raw content bytes into `card` and binds `uri` in `handle_registry` (`INV-510-01`, `INV-510-02`).
    pub fn write_raw_bytes(
        &self,
        uri: &str,
        content: &[u8],
        algorithm: Option<&str>,
    ) -> Result<MCardRecord> {
        let canonical_uri = self.canonicalize_uri(uri);
        let now = crate::utils::now_iso8601();
        let record = MCardRecord::create(content, algorithm)
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
        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 existing: Option<String> = tx
            .query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
                params![&canonical_uri],
                |row| row.get(0),
            )
            .ok();
        tx.execute(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
            params![&record.hash, &record.content, &record.g_time],
        )?;
        if let Some(prev) = existing.as_ref().filter(|p| **p != record.hash) {
            tx.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
                params![&canonical_uri, prev, &now],
            )?;
        }
        tx.execute(
            "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
            params![&canonical_uri, &record.hash, &now],
        )?;
        tx.commit()?;
        Ok(record)
    }

    /// Reads and verifies exact raw bytes bound to `uri` (`INV-510-01`).
    pub fn read_raw_bytes(&self, uri: &str) -> Result<Vec<u8>> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
        let current_hash: String = conn
            .query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
                params![&canonical_uri],
                |row| row.get(0),
            )
            .map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{canonical_uri}' not found"),
                )
            })?;
        let (content, g_time): (Vec<u8>, String) = conn
            .query_row(
                "SELECT content, g_time FROM card WHERE hash = ?1",
                params![&current_hash],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CorruptedContent,
                    format!("Card '{current_hash}' missing"),
                )
            })?;
        let rec = MCardRecord {
            hash: current_hash,
            content: content.clone(),
            g_time,
        };
        if !matches!(verify_record(&rec), RecordVerification::DeclaredOk { .. }) {
            return Err(ClmError::storage(
                StorageErrorCode::CorruptedContent,
                format!("Cryptographic verification failed for '{canonical_uri}'"),
            ));
        }
        Ok(content)
    }

    /// Atomic Compare-and-Swap handle binding (`INV-510-03`).
    /// Returns `Ok(true)` on commit, or `Ok(false)` when `expected_old_ref` mismatches the current head.
    pub fn bind(&self, uri: &str, new_ref: &str, expected_old_ref: Option<&str>) -> Result<bool> {
        let canonical_uri = self.canonicalize_uri(uri);
        let new_hash = new_ref.split_once(':').map(|(_, h)| h).unwrap_or(new_ref);
        let expected_hash =
            expected_old_ref.map(|r| r.split_once(':').map(|(_, h)| h).unwrap_or(r));
        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 actual_hash: Option<String> = tx
            .query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
                params![&canonical_uri],
                |row| row.get(0),
            )
            .ok();

        if actual_hash.as_deref() != expected_hash {
            let exc_json = serde_json::json!({
                "actual_old_ref": actual_hash,
                "expected_old_ref": expected_hash,
                "handle": canonical_uri,
                "kind": "storage_cas_conflict",
                "requested_new_ref": new_hash,
            });
            let exc_bytes = crate::domain::to_canonical_json_bytes(&exc_json);
            if let Ok(exc_rec) = MCardRecord::create(&exc_bytes, Some("blake3")) {
                let _ = tx.execute(
                    "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
                    params![&exc_rec.hash, &exc_rec.content, &exc_rec.g_time],
                );
            }
            tx.commit()?;
            return Ok(false);
        }

        if let Some(prev) = actual_hash.as_ref().filter(|p| p.as_str() != new_hash) {
            tx.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
                params![&canonical_uri, prev, &now],
            )?;
        }
        tx.execute(
            "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
            params![&canonical_uri, new_hash, &now],
        )?;
        tx.commit()?;
        Ok(true)
    }

    /// Writes a `DirectoryManifest` `MCard` to `dir_uri` (`INV-510-04`).
    pub fn write_directory_manifest(
        &self,
        dir_uri: &str,
        manifest: &DirectoryManifest,
    ) -> Result<MCardRecord> {
        self.write_raw_bytes(
            dir_uri,
            &manifest.to_canonical_bytes(),
            Some(&manifest.algorithm),
        )
    }

    /// Reads a `DirectoryManifest` `MCard` from `dir_uri` (`INV-510-04`).
    pub fn read_directory_manifest(&self, dir_uri: &str) -> Result<DirectoryManifest> {
        let raw = self.read_raw_bytes(dir_uri)?;
        DirectoryManifest::from_canonical_bytes(&raw, Some("blake3"))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum McardUriType {
    Hash,
    Handle,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedMcardUri {
    pub uri_type: McardUriType,
    pub target: String,
    pub fragment: Option<String>,
    pub original: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransclusionCycleError {
    pub cycle_path: Vec<String>,
}

impl std::fmt::Display for TransclusionCycleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Transclusion cycle detected: {}", self.cycle_path.join(" -> "))
    }
}

impl std::error::Error for TransclusionCycleError {}

pub fn canonicalize_mcard_uri(path: &str, context_prefix: &str) -> String {
    let clean = path.trim_start_matches('/');
    let mut prefix = context_prefix.trim_matches('/');
    if prefix == "mcard" {
        prefix = "";
    }
    if let Some(rest) = clean.strip_prefix("mcard:") {
        let rest = rest.trim_start_matches('/');
        if prefix.is_empty() || rest == prefix || rest.starts_with(&format!("{prefix}/")) {
            return format!("mcard:{rest}");
        }
        return format!("mcard:{prefix}/{rest}");
    }
    if prefix.is_empty() {
        format!("mcard:{clean}")
    } else {
        format!("mcard:{prefix}/{clean}")
    }
}

fn is_qualified_hash(value: &str) -> bool {
    let Some((algo, hex)) = value.split_once(':') else {
        return false;
    };
    matches!(algo, "blake3" | "sha256" | "sha512" | "sha3-256" | "sha1" | "md5")
        && (32..=128).contains(&hex.len())
        && hex.chars().all(|c| c.is_ascii_hexdigit())
}

pub fn format_mcard_uri(parsed: &ParsedMcardUri) -> String {
    let frag = parsed
        .fragment
        .as_ref()
        .map(|f| format!("#{}", f.trim_start_matches('#')))
        .unwrap_or_default();
    let kind = match parsed.uri_type {
        McardUriType::Hash => "hash",
        McardUriType::Handle => "handle",
    };
    format!("mcard://{kind}/{}{frag}", parsed.target)
}

pub fn parse_mcard_uri(uri: &str) -> std::result::Result<ParsedMcardUri, String> {
    if uri.is_empty() {
        return Err("Invalid MCard URI: expected non-empty string".to_string());
    }
    let (base, fragment) = match uri.split_once('#') {
        Some((base, frag)) => (base, Some(frag.to_string())),
        None => (uri, None),
    };
    if let Some(target) = base.strip_prefix("mcard://hash/") {
        let target = target.trim_end_matches('/');
        if !target.contains(':') {
            return Err(format!("Malformed hash URI: expected '<algorithm>:<hex>', got '{target}'"));
        }
        return Ok(ParsedMcardUri {
            uri_type: McardUriType::Hash,
            target: target.to_string(),
            fragment,
            original: uri.to_string(),
        });
    }
    if let Some(rest) = base.strip_prefix("mcard://handle/") {
        let raw = rest.split('?').next().unwrap_or(rest).trim_end_matches('/');
        return Ok(ParsedMcardUri {
            uri_type: McardUriType::Handle,
            target: canonicalize_mcard_uri(raw, ""),
            fragment,
            original: uri.to_string(),
        });
    }
    if base.starts_with("mcard://receipts/") || base.starts_with("mcard://schemas/") {
        let raw = base.trim_start_matches("mcard://").trim_end_matches('/');
        return Ok(ParsedMcardUri {
            uri_type: McardUriType::Handle,
            target: canonicalize_mcard_uri(raw, ""),
            fragment,
            original: uri.to_string(),
        });
    }
    if let Some(raw) = base.strip_prefix("mcard://") {
        let raw = raw.trim_end_matches('/');
        if is_qualified_hash(raw) {
            return Ok(ParsedMcardUri {
                uri_type: McardUriType::Hash,
                target: raw.to_lowercase(),
                fragment,
                original: uri.to_string(),
            });
        }
        return Ok(ParsedMcardUri {
            uri_type: McardUriType::Handle,
            target: canonicalize_mcard_uri(raw, ""),
            fragment,
            original: uri.to_string(),
        });
    }
    Ok(ParsedMcardUri {
        uri_type: McardUriType::Handle,
        target: canonicalize_mcard_uri(base, ""),
        fragment,
        original: uri.to_string(),
    })
}

pub fn validate_transclusion_chain(chain: &[String], next_ref: &str) -> std::result::Result<(), TransclusionCycleError> {
    let next = next_ref.to_lowercase();
    if chain.iter().any(|ref_| ref_.to_lowercase() == next) {
        let mut cycle_path = chain.to_vec();
        cycle_path.push(next_ref.to_string());
        return Err(TransclusionCycleError { cycle_path });
    }
    Ok(())
}