Skip to main content

clm_rust_core/
crdt.rs

1//! CRDT-backed learning event sync scaffold for Stage 7.
2//!
3//! Implements vector-clock-ordered `LearningEvent`s and a per-node `CrdtLog`
4//! that can be merged across PKC boundaries. Conflicts are surfaced to the
5//! sheaf gluing engine (`crate::sheaf`) for topological resolution.
6
7use crate::sheaf::Marking;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11#[cfg(feature = "native")]
12use crate::archive::{ArchiveManifest, ArchiveFileEntry};
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16#[derive(Default)]
17pub enum PartialSharingMode {
18    ContentOnly,
19    ContentAndExecution,
20    #[default]
21    FullSovereign,
22}
23
24
25impl PartialSharingMode {
26    pub fn from_str(s: &str) -> Self {
27        match s {
28            "content_only" => PartialSharingMode::ContentOnly,
29            "content_and_execution" => PartialSharingMode::ContentAndExecution,
30            _ => PartialSharingMode::FullSovereign,
31        }
32    }
33}
34
35/// Computes set difference Delta = H_peer \ H_local between two archive manifests.
36#[cfg(feature = "native")]
37pub fn compute_manifest_delta(
38    local_manifest: &ArchiveManifest,
39    peer_manifest: &ArchiveManifest,
40) -> Vec<ArchiveFileEntry> {
41    let local_hashes: std::collections::HashSet<&str> = local_manifest
42        .files
43        .iter()
44        .map(|f| f.sha256.as_str())
45        .collect();
46
47    peer_manifest
48        .files
49        .iter()
50        .filter(|f| !local_hashes.contains(f.sha256.as_str()))
51        .cloned()
52        .collect()
53}
54
55/// G-Set CRDT merge: merges missing cards into target database with growth-only append semantics.
56#[cfg(feature = "native")]
57pub fn merge_gset_cards(
58    target_db: &str,
59    clm_root: &str,
60    incoming_cards: &[(String, String, String)], // (hash, content, g_time)
61    sharing_mode: PartialSharingMode,
62) -> Result<usize, String> {
63    let mut count = 0;
64    for (hash, content, g_time) in incoming_cards {
65        // Apply partial sharing filter
66        let db_clean = target_db.to_lowercase();
67        if sharing_mode == PartialSharingMode::ContentOnly && !db_clean.contains("content_memory") {
68            continue;
69        }
70        if sharing_mode == PartialSharingMode::ContentAndExecution
71            && !db_clean.contains("content_memory")
72            && !db_clean.contains("execution_log")
73        {
74            continue;
75        }
76
77        if target_db.contains('/') || target_db.ends_with(".db") {
78            let path = std::path::Path::new(target_db);
79            if let Ok(conn) = rusqlite::Connection::open(path) {
80                let _ = conn.execute(
81                    "CREATE TABLE IF NOT EXISTS card (hash TEXT PRIMARY KEY, content TEXT, g_time TEXT);",
82                    [],
83                );
84                if let Ok(inserted) = conn.execute(
85                    "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
86                    rusqlite::params![hash, content, g_time],
87                ) {
88                    count += inserted;
89                }
90            }
91        } else {
92            let _ = crate::db::setter_card_batch(target_db, clm_root, hash, content, g_time);
93            count += 1;
94        }
95    }
96    Ok(count)
97}
98
99#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
100// ORC-18: TRANSPARENT. TypeScript's `toJSON()` returns the BARE MAP; the derived Rust serde
101// emitted `{"entries": {...}}`. Two runtimes cannot exchange an event if their wire formats
102// differ, and this is the mesh's own clock.
103#[serde(transparent)]
104pub struct VectorClock {
105    pub entries: HashMap<String, u64>,
106}
107
108impl VectorClock {
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    pub fn increment(&mut self, node_id: &str) {
114        let counter = self.entries.entry(node_id.to_string()).or_insert(0);
115        *counter += 1;
116    }
117
118    pub fn merge(&self, other: &VectorClock) -> VectorClock {
119        let mut entries = self.entries.clone();
120        for (node, counter) in &other.entries {
121            let current = entries.entry(node.clone()).or_insert(0);
122            *current = (*current).max(*counter);
123        }
124        VectorClock { entries }
125    }
126
127    /// Causal ordering: returns true iff every entry in self is <= other and
128    /// at least one entry is strictly less.
129    pub fn happened_before(&self, other: &VectorClock) -> bool {
130        let mut all_le = true;
131        let mut any_lt = false;
132        for (node, self_counter) in &self.entries {
133            let other_counter = other.entries.get(node).copied().unwrap_or(0);
134            if *self_counter > other_counter {
135                all_le = false;
136            }
137            if *self_counter < other_counter {
138                any_lt = true;
139            }
140        }
141        // Also ensure other has entries that self does not (so other is strictly after).
142        if other.entries.keys().any(|k| !self.entries.contains_key(k)) {
143            any_lt = true;
144        }
145        all_le && any_lt
146    }
147
148    pub fn is_concurrent_with(&self, other: &VectorClock) -> bool {
149        !self.happened_before(other) && !other.happened_before(self)
150    }
151}
152
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
154pub struct LearningEvent {
155    pub vcard_hash: String,
156    pub pcard_hash: String,
157    pub marking_delta: Marking,
158    pub agent_did: String,
159    pub timestamp: String,
160    pub vector_clock: VectorClock,
161}
162
163/// The mesh event AS A CARD PAYLOAD — the NORMATIVE field names, so the loader
164/// deserializes directly rather than translating `target` into `pcard_hash`.
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct TelemetryEventPayload {
167    pub vcard_hash: String,
168    pub pcard_hash: String,
169    pub agent_did: String,
170    pub timestamp: String,
171    pub vector_clock: VectorClock,
172    pub marking_delta: Marking,
173}
174
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
176pub struct CrdtLog {
177    pub events: Vec<LearningEvent>,
178    pub clock: VectorClock,
179    pub node_id: String,
180}
181
182impl CrdtLog {
183    pub fn new(node_id: &str) -> Self {
184        Self {
185            events: Vec::new(),
186            clock: VectorClock::new(),
187            node_id: node_id.to_string(),
188        }
189    }
190
191    /// Append a locally generated learning event.
192    pub fn append(&mut self, mut event: LearningEvent) {
193        self.clock.increment(&self.node_id);
194        event.vector_clock = self.clock.clone();
195        self.events.push(event);
196    }
197
198    /// Merge another node's CRDT log into this one.
199    pub fn merge(&mut self, other: &CrdtLog) {
200        self.clock = self.clock.merge(&other.clock);
201        for event in &other.events {
202            if !self.events.iter().any(|e| e.vcard_hash == event.vcard_hash) {
203                self.events.push(event.clone());
204            }
205        }
206        self.events
207            .sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
208    }
209
210    /// Detect concurrent events that require sheaf gluing resolution.
211    pub fn concurrent_pairs(&self) -> Vec<(&LearningEvent, &LearningEvent)> {
212        let mut pairs = Vec::new();
213        for i in 0..self.events.len() {
214            for j in (i + 1)..self.events.len() {
215                if self.events[i]
216                    .vector_clock
217                    .is_concurrent_with(&self.events[j].vector_clock)
218                {
219                    pairs.push((&self.events[i], &self.events[j]));
220                }
221            }
222        }
223        pairs
224    }
225}
226
227// ---------------------------------------------------------------------------
228// DB Persistence (Story 140.4.2) — native only (rusqlite not available on WASM)
229// ---------------------------------------------------------------------------
230
231/// Persist a single learning event to the execution_log DB.
232/// Uses INSERT OR IGNORE for idempotency (duplicate vcard_hash is a no-op).
233#[cfg(any(feature = "native", feature = "db"))]
234pub fn persist_learning_event(
235    conn: &rusqlite::Connection,
236    event: &LearningEvent,
237    node_id: &str,
238) -> Result<(), String> {
239    // ORC-18: THE EVENT IS A CARD, on the write side too. `learning_event` was dropped by
240    // ORC-23, so the producer writes what the loader reads. HALF A MIGRATION — a loader that
241    // reads cards and a writer that writes a table — passes the round-trip test and fails the
242    // three tests that exercise the producer. They land together.
243    let payload = TelemetryEventPayload {
244        vcard_hash: event.vcard_hash.clone(),
245        pcard_hash: event.pcard_hash.clone(),
246        agent_did: event.agent_did.clone(),
247        timestamp: event.timestamp.clone(),
248        vector_clock: event.vector_clock.clone(),
249        marking_delta: event.marking_delta.clone(),
250    };
251    let content = serde_json::to_vec(&payload)
252        .map_err(|e| format!("Failed to serialize the event card: {}", e))?;
253    let hash = {
254        use sha2::{Digest, Sha256};
255        let mut h = Sha256::new();
256        h.update(&content);
257        format!("{:x}", h.finalize())
258    };
259    conn.execute(
260        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
261        rusqlite::params![hash, content, event.timestamp],
262    )
263    .map_err(|e| format!("Failed to persist the event card: {}", e))?;
264    // THE HANDLE IS DERIVED FROM THE CONTENT, not from a counter. A sequence makes a
265    // duplicate persist create a NEW handle, so re-persisting the same event is not
266    // idempotent — the property the original `learning_event` PRIMARY KEY provided. It also
267    // means the handle recorded the CLOCK rather than the event, which ORC-28 forbids.
268    let handle = format!("urn:mcard:telemetry:event:{}:{}", node_id, &hash[..16]);
269    conn.execute(
270        "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
271        rusqlite::params![handle, hash, event.timestamp],
272    )
273    .map_err(|e| format!("Failed to register the event handle: {}", e))?;
274    conn.execute(
275        "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
276        rusqlite::params![handle, hash, event.timestamp],
277    )
278    .map_err(|e| format!("Failed to record the event history: {}", e))?;
279
280    Ok(())
281}
282
283/// Load learning events from the DB, optionally filtered by timestamp.
284/// Returns events sorted by timestamp (vector-clock order).
285#[cfg(any(feature = "native", feature = "db"))]
286pub fn load_learning_events(
287    conn: &rusqlite::Connection,
288    since: Option<&str>,
289) -> Result<Vec<LearningEvent>, String> {
290    let mut events = Vec::new();
291
292    // ORC-18: THE EVENT IS A CARD. A compatibility VIEW named `learning_event` was
293    // REJECTED — it would recreate the table the Triad forbids, under a new name.
294    let sql = if since.is_some() {
295        "SELECT c.content FROM handle_registry r JOIN card c ON c.hash = r.current_hash \
296         WHERE r.handle LIKE 'urn:mcard:telemetry:event:%' AND c.g_time > ?1 \
297         ORDER BY c.g_time ASC"
298    } else {
299        "SELECT c.content FROM handle_registry r JOIN card c ON c.hash = r.current_hash \
300         WHERE r.handle LIKE 'urn:mcard:telemetry:event:%' ORDER BY c.g_time ASC"
301    };
302    let mut stmt = conn
303        .prepare(sql)
304        .map_err(|e| format!("Failed to prepare query: {}", e))?;
305    // ONE closure, reused: two identical closures are two DISTINCT types in Rust.
306    let map_row = |row: &rusqlite::Row| -> rusqlite::Result<Vec<u8>> { row.get(0) };
307    let rows = if let Some(since_ts) = since {
308        stmt.query_map(rusqlite::params![since_ts], map_row)
309            .map_err(|e| format!("Failed to query learning events: {}", e))?
310    } else {
311        stmt.query_map(rusqlite::params![], map_row)
312            .map_err(|e| format!("Failed to query learning events: {}", e))?
313    };
314    for row in rows {
315        let content = row.map_err(|e| format!("Failed to read row: {}", e))?;
316        let payload: TelemetryEventPayload = serde_json::from_slice(&content)
317            .map_err(|e| format!("Failed to deserialize the event card: {}", e))?;
318        events.push(LearningEvent {
319            vcard_hash: payload.vcard_hash,
320            pcard_hash: payload.pcard_hash,
321            agent_did: payload.agent_did,
322            timestamp: payload.timestamp,
323            vector_clock: payload.vector_clock,
324            marking_delta: payload.marking_delta,
325        });
326    }
327
328    Ok(events)
329}
330
331// ---------------------------------------------------------------------------
332// Sync Report (Story 140.4.3)
333// ---------------------------------------------------------------------------
334
335/// Report from a CRDT sync operation between two nodes.
336#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
337pub struct SyncReport {
338    pub events_merged: usize,
339    pub events_appended: usize,
340    pub conflicts: Vec<String>,
341}
342
343/// Sync learning events between local and remote CRDT logs.
344/// Merges remote events into local log and persists all events to DB.
345#[cfg(any(feature = "native", feature = "db"))]
346pub fn sync_learning_events(
347    local: &mut CrdtLog,
348    remote: &CrdtLog,
349    conn: &rusqlite::Connection,
350) -> Result<SyncReport, String> {
351    let local_count_before = local.events.len();
352
353    // Merge remote into local
354    local.merge(remote);
355
356    let events_appended = local.events.len() - local_count_before;
357
358    // Detect conflicts (concurrent pairs)
359    let conflicts: Vec<String> = local
360        .concurrent_pairs()
361        .iter()
362        .map(|(a, b)| {
363            format!(
364                "concurrent events: {} vs {} (vclock: {:?} vs {:?})",
365                a.vcard_hash, b.vcard_hash, a.vector_clock, b.vector_clock
366            )
367        })
368        .collect();
369
370    let events_merged = remote.events.len();
371
372    // Persist all local events to DB
373    for event in &local.events {
374        persist_learning_event(conn, event, &local.node_id)?;
375    }
376
377    Ok(SyncReport {
378        events_merged,
379        events_appended,
380        conflicts,
381    })
382}
383
384/// THE CANONICAL DECLARATION, INCLUDED rather than restated. Six fixtures used to carry
385/// their own copy of the dropped `learning_event` schema; a fixture that RESTATES the schema
386/// can drift from it, and one that INCLUDES it cannot. This is `ORC-27`'s "four copies
387/// byte-identical" applied to the tests — and it removes the duplication rather than
388/// migrating it. Declared at module scope so every test module includes the SAME one.
389#[cfg(test)]
390const CANONICAL_DDL: &str = include_str!("../../../schema/mcard_schema.sql");
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396
397    #[cfg_attr(not(target_arch = "wasm32"), test)]
398    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
399    fn test_vector_clock_happened_before() {
400        let mut a = VectorClock::new();
401        a.increment("n1");
402        a.increment("n1");
403        let mut b = a.clone();
404        b.increment("n1");
405        assert!(a.happened_before(&b));
406        assert!(!b.happened_before(&a));
407    }
408
409    #[cfg_attr(not(target_arch = "wasm32"), test)]
410    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
411    fn test_vector_clock_concurrent() {
412        let mut a = VectorClock::new();
413        a.increment("n1");
414        let mut b = VectorClock::new();
415        b.increment("n2");
416        assert!(a.is_concurrent_with(&b));
417    }
418
419    #[cfg_attr(not(target_arch = "wasm32"), test)]
420    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
421    fn test_crdt_log_merge_idempotent() {
422        let mut log_a = CrdtLog::new("a");
423        log_a.append(LearningEvent {
424            vcard_hash: "h1".to_string(),
425            pcard_hash: "p1".to_string(),
426            marking_delta: Marking::new(),
427            agent_did: "did:key:a".to_string(),
428            timestamp: "t1".to_string(),
429            vector_clock: VectorClock::new(),
430        });
431        let mut log_b = CrdtLog::new("b");
432        log_b.merge(&log_a);
433        assert_eq!(log_b.events.len(), 1);
434        log_b.merge(&log_a);
435        assert_eq!(log_b.events.len(), 1);
436    }
437
438    #[cfg_attr(not(target_arch = "wasm32"), test)]
439    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
440    fn test_crdt_log_detects_concurrent_events() {
441        let mut log_a = CrdtLog::new("a");
442        log_a.append(LearningEvent {
443            vcard_hash: "h1".to_string(),
444            pcard_hash: "p1".to_string(),
445            marking_delta: Marking::new(),
446            agent_did: "did:key:a".to_string(),
447            timestamp: "t1".to_string(),
448            vector_clock: VectorClock::new(),
449        });
450        let mut log_b = CrdtLog::new("b");
451        log_b.append(LearningEvent {
452            vcard_hash: "h2".to_string(),
453            pcard_hash: "p2".to_string(),
454            marking_delta: Marking::new(),
455            agent_did: "did:key:b".to_string(),
456            timestamp: "t2".to_string(),
457            vector_clock: VectorClock::new(),
458        });
459        let mut merged = CrdtLog::new("local");
460        merged.merge(&log_a);
461        merged.merge(&log_b);
462        assert_eq!(merged.concurrent_pairs().len(), 1);
463    }
464
465    #[cfg(not(target_arch = "wasm32"))]
466    #[test]
467    fn test_crdt_db_schema_creates_the_canonical_three() {
468        // ORC-18: this test used to ASSERT THE EXISTENCE OF THE TABLE THE TRIAD FORBIDS.
469        // It is not a fixture to migrate — it is a test of the removed schema, and it now
470        // asserts the INVARIANT: the canonical three exist, and no `learning_event` does.
471        let conn = rusqlite::Connection::open_in_memory().unwrap();
472        conn.execute_batch(CANONICAL_DDL).unwrap();
473        for table in ["card", "handle_registry", "handle_history"] {
474            let exists: bool = conn
475                .query_row(
476                    "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?1",
477                    [table],
478                    |r| r.get::<_, i64>(0),
479                )
480                .map(|n| n > 0)
481                .unwrap();
482            assert!(exists, "{table} must exist");
483        }
484        let leaked: i64 = conn
485            .query_row(
486                "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='learning_event'",
487                [],
488                |r| r.get(0),
489            )
490            .unwrap();
491        assert_eq!(leaked, 0, "learning_event is the table ORC-23 dropped");
492    }
493
494    #[cfg(any(feature = "native", feature = "db"))]
495    #[test]
496    fn test_crdt_db_persist_and_load_learning_event() {
497        let conn = rusqlite::Connection::open_in_memory().unwrap();
498        conn.execute_batch(CANONICAL_DDL).unwrap();
499
500        let event = LearningEvent {
501            vcard_hash: "vcard-hash-1".to_string(),
502            pcard_hash: "pcard-hash-1".to_string(),
503            marking_delta: Marking::new(),
504            agent_did: "did:key:node-a".to_string(),
505            timestamp: "2026-07-16T10:00:00Z".to_string(),
506            vector_clock: VectorClock::new(),
507        };
508
509        persist_learning_event(&conn, &event, "node-a").unwrap();
510
511        let loaded = load_learning_events(&conn, None).unwrap();
512        assert_eq!(loaded.len(), 1);
513        assert_eq!(loaded[0].vcard_hash, "vcard-hash-1");
514        assert_eq!(loaded[0].pcard_hash, "pcard-hash-1");
515        assert_eq!(loaded[0].agent_did, "did:key:node-a");
516    }
517
518    #[cfg(any(feature = "native", feature = "db"))]
519    #[test]
520    fn test_crdt_db_persist_is_idempotent() {
521        let conn = rusqlite::Connection::open_in_memory().unwrap();
522        conn.execute_batch(CANONICAL_DDL).unwrap();
523
524        let event = LearningEvent {
525            vcard_hash: "vcard-dup".to_string(),
526            pcard_hash: "pcard-1".to_string(),
527            marking_delta: Marking::new(),
528            agent_did: "did:key:a".to_string(),
529            timestamp: "t1".to_string(),
530            vector_clock: VectorClock::new(),
531        };
532
533        persist_learning_event(&conn, &event, "node-a").unwrap();
534        persist_learning_event(&conn, &event, "node-a").unwrap();
535
536        let loaded = load_learning_events(&conn, None).unwrap();
537        assert_eq!(loaded.len(), 1, "duplicate persist should be idempotent");
538    }
539
540    #[cfg(any(feature = "native", feature = "db"))]
541    #[test]
542    fn test_crdt_db_load_returns_vector_clock_order() {
543        let conn = rusqlite::Connection::open_in_memory().unwrap();
544        conn.execute_batch(CANONICAL_DDL).unwrap();
545
546        // Insert events out of order
547        let event_b = LearningEvent {
548            vcard_hash: "vcard-b".to_string(),
549            pcard_hash: "pcard-b".to_string(),
550            marking_delta: Marking::new(),
551            agent_did: "did:key:b".to_string(),
552            timestamp: "2026-07-16T12:00:00Z".to_string(),
553            vector_clock: VectorClock::new(),
554        };
555        let event_a = LearningEvent {
556            vcard_hash: "vcard-a".to_string(),
557            pcard_hash: "pcard-a".to_string(),
558            marking_delta: Marking::new(),
559            agent_did: "did:key:a".to_string(),
560            timestamp: "2026-07-16T10:00:00Z".to_string(),
561            vector_clock: VectorClock::new(),
562        };
563
564        persist_learning_event(&conn, &event_b, "node-b").unwrap();
565        persist_learning_event(&conn, &event_a, "node-a").unwrap();
566
567        let loaded = load_learning_events(&conn, None).unwrap();
568        assert_eq!(loaded.len(), 2);
569        // Should be sorted by timestamp ascending
570        assert_eq!(loaded[0].vcard_hash, "vcard-a");
571        assert_eq!(loaded[1].vcard_hash, "vcard-b");
572    }
573
574    #[cfg(any(feature = "native", feature = "db"))]
575    #[test]
576    fn test_crdt_sync_merges_and_persists() {
577        let conn = rusqlite::Connection::open_in_memory().unwrap();
578        conn.execute_batch(CANONICAL_DDL).unwrap();
579
580        let mut local = CrdtLog::new("node-local");
581        local.append(LearningEvent {
582            vcard_hash: "vcard-local".to_string(),
583            pcard_hash: "pcard-1".to_string(),
584            marking_delta: Marking::new(),
585            agent_did: "did:key:local".to_string(),
586            timestamp: "t1".to_string(),
587            vector_clock: VectorClock::new(),
588        });
589
590        let mut remote = CrdtLog::new("node-remote");
591        remote.append(LearningEvent {
592            vcard_hash: "vcard-remote".to_string(),
593            pcard_hash: "pcard-2".to_string(),
594            marking_delta: Marking::new(),
595            agent_did: "did:key:remote".to_string(),
596            timestamp: "t2".to_string(),
597            vector_clock: VectorClock::new(),
598        });
599
600        let report = sync_learning_events(&mut local, &remote, &conn).unwrap();
601        assert_eq!(report.events_merged, 1);
602        assert_eq!(report.events_appended, 1);
603        assert_eq!(local.events.len(), 2);
604
605        // Verify persisted to DB
606        let loaded = load_learning_events(&conn, None).unwrap();
607        assert_eq!(loaded.len(), 2);
608    }
609
610    #[cfg(any(feature = "native", feature = "db"))]
611    #[test]
612    fn test_crdt_sync_survives_restart() {
613        // Simulate restart by using a file-based temp DB
614        let tmp_dir = std::env::temp_dir();
615        let db_path = tmp_dir.join("clm_crdt_restart_test.db");
616        let _ = std::fs::remove_file(&db_path);
617
618        // First "session": create table and persist
619        {
620            let conn = rusqlite::Connection::open(&db_path).unwrap();
621            conn.execute_batch(CANONICAL_DDL).unwrap();
622
623            let event = LearningEvent {
624                vcard_hash: "vcard-restart".to_string(),
625                pcard_hash: "pcard-1".to_string(),
626                marking_delta: Marking::new(),
627                agent_did: "did:key:restart".to_string(),
628                timestamp: "t-restart".to_string(),
629                vector_clock: VectorClock::new(),
630            };
631            persist_learning_event(&conn, &event, "node-restart").unwrap();
632        }
633
634        // Second "session": reopen and verify data survived
635        {
636            let conn = rusqlite::Connection::open(&db_path).unwrap();
637            let loaded = load_learning_events(&conn, None).unwrap();
638            assert_eq!(loaded.len(), 1);
639            assert_eq!(loaded[0].vcard_hash, "vcard-restart");
640        }
641
642        let _ = std::fs::remove_file(&db_path);
643    }
644
645    #[cfg(feature = "native")]
646    #[test]
647    fn test_manifest_delta_compute() {
648        let manifest_local = ArchiveManifest {
649            archive_id: "archive:local".to_string(),
650            g_time: "t1".to_string(),
651            files: vec![
652                ArchiveFileEntry { path: "f1.txt".to_string(), sha256: "hash1".to_string(), size: 10, mode: 0o644 },
653                ArchiveFileEntry { path: "f2.txt".to_string(), sha256: "hash2".to_string(), size: 20, mode: 0o644 },
654            ],
655            top_level_vcard_hash: None,
656            archiver_did: None,
657            compression: None,
658        };
659
660        let manifest_peer = ArchiveManifest {
661            archive_id: "archive:peer".to_string(),
662            g_time: "t2".to_string(),
663            files: vec![
664                ArchiveFileEntry { path: "f1.txt".to_string(), sha256: "hash1".to_string(), size: 10, mode: 0o644 },
665                ArchiveFileEntry { path: "f3.txt".to_string(), sha256: "hash3".to_string(), size: 30, mode: 0o644 },
666            ],
667            top_level_vcard_hash: None,
668            archiver_did: None,
669            compression: None,
670        };
671
672        let delta = compute_manifest_delta(&manifest_local, &manifest_peer);
673        assert_eq!(delta.len(), 1);
674        assert_eq!(delta[0].path, "f3.txt");
675        assert_eq!(delta[0].sha256, "hash3");
676    }
677}
678
679/// ORC-18 — THE PLATFORM WRITES, THE KERNEL READS. A DEVELOPMENT-SUBSTRATE test, labelled as
680/// such: it uses the NORMATIVE payload shape `scripts/orc/mesh_node.py` emits, so the two
681/// runtimes' wire formats are exercised against each other rather than against a fixture
682/// only this crate can produce.
683#[cfg(all(test, any(feature = "native", feature = "db")))]
684mod orc18_round_trip {
685    use super::*;
686
687    #[test]
688    fn the_platform_writes_and_the_kernel_reads() {
689        let conn = rusqlite::Connection::open_in_memory().unwrap();
690        conn.execute_batch(CANONICAL_DDL).unwrap();
691
692        // exactly the shape scripts/orc/mesh_node.py emits
693        let body = serde_json::json!({
694            "kind": "MESH_EVENT",
695            "sprint": "ORC-18",
696            "vcard_hash": "v-seal-1",
697            "pcard_hash": "clm",
698            "agent_did": "did:key:z6MkRoot",
699            "timestamp": "2026-10-08T00:00:00Z",
700            "vector_clock": {"root": 3},
701            "marking_delta": {"sealed": ["clm"]},
702        });
703        let content = serde_json::to_vec(&body).unwrap();
704        let hash = {
705            use sha2::{Digest, Sha256};
706            let mut h = Sha256::new();
707            h.update(&content);
708            format!("{:x}", h.finalize())
709        };
710        conn.execute(
711            "INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
712            rusqlite::params![hash, content, "2026-10-08T00:00:00Z"],
713        )
714        .unwrap();
715        conn.execute(
716            "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
717            rusqlite::params!["urn:mcard:telemetry:event:root:1", hash, "2026-10-08T00:00:00Z"],
718        )
719        .unwrap();
720
721        let events = load_learning_events(&conn, None).expect("the loader must read the tape");
722        assert_eq!(events.len(), 1, "exactly one event");
723        let e = &events[0];
724        assert_eq!(e.agent_did, "did:key:z6MkRoot");
725        assert_eq!(e.pcard_hash, "clm");
726        assert_eq!(e.timestamp, "2026-10-08T00:00:00Z");
727        assert_eq!(
728            serde_json::to_value(&e.vector_clock).unwrap()["root"], 3,
729            "the CLOCK round-trips intact"
730        );
731    }
732}
733