Skip to main content

clm_rust_core/layer2/
vfs.rs

1//! Layer 2: MCard Virtual Filesystem (VFS) & Deterministic DirectoryManifest (Sprint 510)
2//! Canonical Path: kernel/clm_rust_core/src/layer2/vfs.rs
3
4use crate::error::{ClmError, Result, StorageErrorCode};
5use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
6pub use crate::mcard_fs::{MCardFileSystem, MCardStat};
7pub use super::uri::{format_mcard_uri, parse_mcard_uri, validate_transclusion_chain, McardUri, McardUriKind};
8use rusqlite::params;
9use serde::{Deserialize, Serialize};
10
11/// Deterministic child entry inside a `DirectoryManifest` `MCard` (`INV-510-04`).
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct DirectoryManifestEntry {
14    pub name: String,
15    pub kind: String,
16    pub target_ref: String,
17    #[serde(default)]
18    pub metadata_ref: Option<String>,
19}
20
21/// Deterministic, content-addressed directory manifest `MCard` (`INV-510-04`).
22///
23/// Entries are canonically sorted by `(name, kind, target_ref, metadata_ref)` before
24/// JCS-style canonical JSON serialization so child permutation does not change identity.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct DirectoryManifest {
27    pub entries: Vec<DirectoryManifestEntry>,
28    pub algorithm: String,
29}
30
31impl DirectoryManifest {
32    pub fn new(entries: Vec<DirectoryManifestEntry>, algorithm: Option<&str>) -> Self {
33        Self {
34            entries,
35            algorithm: algorithm.unwrap_or("blake3").to_string(),
36        }
37    }
38
39    /// Returns entries canonically sorted by `(name, kind, target_ref, metadata_ref)`.
40    pub fn sorted_entries(&self) -> Vec<DirectoryManifestEntry> {
41        let mut sorted = self.entries.clone();
42        sorted.sort_by(|a, b| {
43            (&a.name, &a.kind, &a.target_ref, a.metadata_ref.as_deref().unwrap_or(""))
44                .cmp(&(&b.name, &b.kind, &b.target_ref, b.metadata_ref.as_deref().unwrap_or("")))
45        });
46        sorted
47    }
48
49    /// Serializes the manifest to canonical UTF-8 JSON bytes (`INV-510-04`).
50    pub fn to_canonical_bytes(&self) -> Vec<u8> {
51        let entries_json: Vec<serde_json::Value> = self
52            .sorted_entries()
53            .into_iter()
54            .map(|e| {
55                serde_json::json!({
56                    "kind": e.kind,
57                    "metadata_ref": e.metadata_ref,
58                    "name": e.name,
59                    "target_ref": e.target_ref,
60                })
61            })
62            .collect();
63        let doc = serde_json::json!({
64            "entries": entries_json,
65            "schema": "clm://layer2/directory_manifest/v1",
66        });
67        crate::domain::to_canonical_json_bytes(&doc)
68    }
69
70    /// Reifies the `DirectoryManifest` into a content-addressed `MCardRecord`.
71    pub fn to_mcard_record(&self) -> Result<MCardRecord> {
72        MCardRecord::create(&self.to_canonical_bytes(), Some(&self.algorithm))
73            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))
74    }
75
76    /// Returns the qualified `a:hex` reference for this manifest (`INV-510-04`).
77    pub fn qualified_ref(&self) -> Result<String> {
78        let rec = self.to_mcard_record()?;
79        Ok(format!("{}:{}", self.algorithm, rec.hash))
80    }
81
82    /// Parses a `DirectoryManifest` from canonical JSON bytes.
83    pub fn from_canonical_bytes(raw: &[u8], algorithm: Option<&str>) -> Result<Self> {
84        let val: serde_json::Value = serde_json::from_slice(raw)?;
85        let entries_arr = val
86            .get("entries")
87            .and_then(|v| v.as_array())
88            .ok_or_else(|| {
89                ClmError::storage(
90                    StorageErrorCode::CorruptedContent,
91                    "Invalid DirectoryManifest entries".to_string(),
92                )
93            })?;
94        let mut entries = Vec::with_capacity(entries_arr.len());
95        for item in entries_arr {
96            entries.push(DirectoryManifestEntry {
97                name: item.get("name").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
98                kind: item.get("kind").and_then(|v| v.as_str()).unwrap_or("file").to_string(),
99                target_ref: item.get("target_ref").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
100                metadata_ref: item.get("metadata_ref").and_then(|v| v.as_str()).map(|s| s.to_string()),
101            });
102        }
103        Ok(Self::new(entries, algorithm))
104    }
105}
106
107impl MCardFileSystem {
108    /// Writes raw content bytes into `card` and binds `uri` in `handle_registry` (`INV-510-01`, `INV-510-02`).
109    pub fn write_raw_bytes(
110        &self,
111        uri: &str,
112        content: &[u8],
113        algorithm: Option<&str>,
114    ) -> Result<MCardRecord> {
115        let canonical_uri = self.canonicalize_uri(uri);
116        let now = crate::utils::now_iso8601();
117        let record = MCardRecord::create(content, algorithm)
118            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
119        let mut conn = self
120            .conn
121            .lock()
122            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
123        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
124        {
125            let mut stmt_sel = tx.prepare_cached(
126                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
127            )?;
128            let existing: Option<String> = stmt_sel
129                .query_row(params![&canonical_uri], |row| row.get(0))
130                .ok();
131            let mut stmt_card = tx.prepare_cached(
132                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
133            )?;
134            stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
135            if let Some(prev) = existing.as_ref().filter(|p| **p != record.hash) {
136                let mut stmt_hist = tx.prepare_cached(
137                    "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
138                )?;
139                stmt_hist.execute(params![&canonical_uri, prev, &now])?;
140            }
141            let mut stmt_reg = tx.prepare_cached(
142                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
143            )?;
144            stmt_reg.execute(params![&canonical_uri, &record.hash, &now])?;
145        }
146        tx.commit()?;
147        Ok(record)
148    }
149
150    /// Reads and verifies exact raw bytes bound to `uri` (`INV-510-01`).
151    pub fn read_raw_bytes(&self, uri: &str) -> Result<Vec<u8>> {
152        let canonical_uri = self.canonicalize_uri(uri);
153        let conn = self
154            .conn
155            .lock()
156            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
157        let current_hash: String = {
158            let mut stmt_reg = conn.prepare_cached(
159                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
160            )?;
161            stmt_reg
162                .query_row(params![&canonical_uri], |row| row.get(0))
163                .map_err(|_| {
164                    ClmError::storage(
165                        StorageErrorCode::CardNotFound,
166                        format!("Handle '{canonical_uri}' not found"),
167                    )
168                })?
169        };
170        let (content, g_time): (Vec<u8>, String) = {
171            let mut stmt_card = conn.prepare_cached(
172                "SELECT content, g_time FROM card WHERE hash = ?1",
173            )?;
174            stmt_card
175                .query_row(params![&current_hash], |row| Ok((row.get(0)?, row.get(1)?)))
176                .map_err(|_| {
177                    ClmError::storage(
178                        StorageErrorCode::CorruptedContent,
179                        format!("Card '{current_hash}' missing"),
180                    )
181                })?
182        };
183        let rec = MCardRecord {
184            hash: current_hash,
185            content,
186            g_time,
187        };
188        if !matches!(verify_record(&rec), RecordVerification::DeclaredOk { .. }) {
189            return Err(ClmError::storage(
190                StorageErrorCode::CorruptedContent,
191                format!("Cryptographic verification failed for '{canonical_uri}'"),
192            ));
193        }
194        Ok(rec.content)
195    }
196
197    /// Atomic Compare-and-Swap handle binding (`INV-510-03`).
198    /// Returns `Ok(true)` on commit, or `Ok(false)` when `expected_old_ref` mismatches the current head.
199    pub fn bind(&self, uri: &str, new_ref: &str, expected_old_ref: Option<&str>) -> Result<bool> {
200        let canonical_uri = self.canonicalize_uri(uri);
201        let new_hash = new_ref.split_once(':').map(|(_, h)| h).unwrap_or(new_ref);
202        let expected_hash =
203            expected_old_ref.map(|r| r.split_once(':').map(|(_, h)| h).unwrap_or(r));
204        let now = crate::utils::now_iso8601();
205
206        let mut conn = self
207            .conn
208            .lock()
209            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
210        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
211        let actual_hash: Option<String> = {
212            let mut stmt_sel = tx.prepare_cached(
213                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
214            )?;
215            stmt_sel.query_row(params![&canonical_uri], |row| row.get(0)).ok()
216        };
217
218        if actual_hash.as_deref() != expected_hash {
219            let exc_json = serde_json::json!({
220                "actual_old_ref": actual_hash,
221                "expected_old_ref": expected_hash,
222                "handle": canonical_uri,
223                "kind": "storage_cas_conflict",
224                "requested_new_ref": new_hash,
225            });
226            let exc_bytes = crate::domain::to_canonical_json_bytes(&exc_json);
227            if let Ok(exc_rec) = MCardRecord::create(&exc_bytes, Some("blake3")) {
228                if let Ok(mut stmt_card) = tx.prepare_cached(
229                    "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
230                ) {
231                    let _ = stmt_card.execute(params![&exc_rec.hash, &exc_rec.content, &exc_rec.g_time]);
232                }
233            }
234            tx.commit()?;
235            return Ok(false);
236        }
237
238        {
239            if let Some(prev) = actual_hash.as_ref().filter(|p| p.as_str() != new_hash) {
240                let mut stmt_hist = tx.prepare_cached(
241                    "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
242                )?;
243                stmt_hist.execute(params![&canonical_uri, prev, &now])?;
244            }
245            let mut stmt_reg = tx.prepare_cached(
246                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
247            )?;
248            stmt_reg.execute(params![&canonical_uri, new_hash, &now])?;
249        }
250        tx.commit()?;
251        Ok(true)
252    }
253
254    /// Writes a `DirectoryManifest` `MCard` to `dir_uri` (`INV-510-04`).
255    pub fn write_directory_manifest(
256        &self,
257        dir_uri: &str,
258        manifest: &DirectoryManifest,
259    ) -> Result<MCardRecord> {
260        self.write_raw_bytes(
261            dir_uri,
262            &manifest.to_canonical_bytes(),
263            Some(&manifest.algorithm),
264        )
265    }
266
267    /// Reads a `DirectoryManifest` `MCard` from `dir_uri` (`INV-510-04`).
268    pub fn read_directory_manifest(&self, dir_uri: &str) -> Result<DirectoryManifest> {
269        let raw = self.read_raw_bytes(dir_uri)?;
270        DirectoryManifest::from_canonical_bytes(&raw, Some("blake3"))
271    }
272}
273
274pub use crate::layer2::uri::*;