use crate::sheaf::Marking;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[cfg(feature = "native")]
use crate::archive::{ArchiveManifest, ArchiveFileEntry};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum PartialSharingMode {
ContentOnly,
ContentAndExecution,
#[default]
FullSovereign,
}
impl PartialSharingMode {
pub fn from_str(s: &str) -> Self {
match s {
"content_only" => PartialSharingMode::ContentOnly,
"content_and_execution" => PartialSharingMode::ContentAndExecution,
_ => PartialSharingMode::FullSovereign,
}
}
}
#[cfg(feature = "native")]
pub fn compute_manifest_delta(
local_manifest: &ArchiveManifest,
peer_manifest: &ArchiveManifest,
) -> Vec<ArchiveFileEntry> {
let local_hashes: std::collections::HashSet<&str> = local_manifest
.files
.iter()
.map(|f| f.sha256.as_str())
.collect();
peer_manifest
.files
.iter()
.filter(|f| !local_hashes.contains(f.sha256.as_str()))
.cloned()
.collect()
}
#[cfg(feature = "native")]
pub fn merge_gset_cards(
target_db: &str,
clm_root: &str,
incoming_cards: &[(String, String, String)], sharing_mode: PartialSharingMode,
) -> Result<usize, String> {
let mut count = 0;
for (hash, content, g_time) in incoming_cards {
let db_clean = target_db.to_lowercase();
if sharing_mode == PartialSharingMode::ContentOnly && !db_clean.contains("content_memory") {
continue;
}
if sharing_mode == PartialSharingMode::ContentAndExecution
&& !db_clean.contains("content_memory")
&& !db_clean.contains("execution_log")
{
continue;
}
if target_db.contains('/') || target_db.ends_with(".db") {
let path = std::path::Path::new(target_db);
if let Ok(conn) = rusqlite::Connection::open(path) {
let _ = conn.execute(
"CREATE TABLE IF NOT EXISTS card (hash TEXT PRIMARY KEY, content TEXT, g_time TEXT);",
[],
);
if let Ok(inserted) = conn.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
rusqlite::params![hash, content, g_time],
) {
count += inserted;
}
}
} else {
let _ = crate::db::setter_card_batch(target_db, clm_root, hash, content, g_time);
count += 1;
}
}
Ok(count)
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct VectorClock {
pub entries: HashMap<String, u64>,
}
impl VectorClock {
pub fn new() -> Self {
Self::default()
}
pub fn increment(&mut self, node_id: &str) {
let counter = self.entries.entry(node_id.to_string()).or_insert(0);
*counter += 1;
}
pub fn merge(&self, other: &VectorClock) -> VectorClock {
let mut entries = self.entries.clone();
for (node, counter) in &other.entries {
let current = entries.entry(node.clone()).or_insert(0);
*current = (*current).max(*counter);
}
VectorClock { entries }
}
pub fn happened_before(&self, other: &VectorClock) -> bool {
let mut all_le = true;
let mut any_lt = false;
for (node, self_counter) in &self.entries {
let other_counter = other.entries.get(node).copied().unwrap_or(0);
if *self_counter > other_counter {
all_le = false;
}
if *self_counter < other_counter {
any_lt = true;
}
}
if other.entries.keys().any(|k| !self.entries.contains_key(k)) {
any_lt = true;
}
all_le && any_lt
}
pub fn is_concurrent_with(&self, other: &VectorClock) -> bool {
!self.happened_before(other) && !other.happened_before(self)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LearningEvent {
pub vcard_hash: String,
pub pcard_hash: String,
pub marking_delta: Marking,
pub agent_did: String,
pub timestamp: String,
pub vector_clock: VectorClock,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryEventPayload {
pub vcard_hash: String,
pub pcard_hash: String,
pub agent_did: String,
pub timestamp: String,
pub vector_clock: VectorClock,
pub marking_delta: Marking,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrdtLog {
pub events: Vec<LearningEvent>,
pub clock: VectorClock,
pub node_id: String,
}
impl CrdtLog {
pub fn new(node_id: &str) -> Self {
Self {
events: Vec::new(),
clock: VectorClock::new(),
node_id: node_id.to_string(),
}
}
pub fn append(&mut self, mut event: LearningEvent) {
self.clock.increment(&self.node_id);
event.vector_clock = self.clock.clone();
self.events.push(event);
}
pub fn merge(&mut self, other: &CrdtLog) {
self.clock = self.clock.merge(&other.clock);
for event in &other.events {
if !self.events.iter().any(|e| e.vcard_hash == event.vcard_hash) {
self.events.push(event.clone());
}
}
self.events
.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
}
pub fn concurrent_pairs(&self) -> Vec<(&LearningEvent, &LearningEvent)> {
let mut pairs = Vec::new();
for i in 0..self.events.len() {
for j in (i + 1)..self.events.len() {
if self.events[i]
.vector_clock
.is_concurrent_with(&self.events[j].vector_clock)
{
pairs.push((&self.events[i], &self.events[j]));
}
}
}
pairs
}
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn persist_learning_event(
conn: &rusqlite::Connection,
event: &LearningEvent,
node_id: &str,
) -> Result<(), String> {
let payload = TelemetryEventPayload {
vcard_hash: event.vcard_hash.clone(),
pcard_hash: event.pcard_hash.clone(),
agent_did: event.agent_did.clone(),
timestamp: event.timestamp.clone(),
vector_clock: event.vector_clock.clone(),
marking_delta: event.marking_delta.clone(),
};
let content = serde_json::to_vec(&payload)
.map_err(|e| format!("Failed to serialize the event card: {}", e))?;
let hash = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(&content);
format!("{:x}", h.finalize())
};
conn.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
rusqlite::params![hash, content, event.timestamp],
)
.map_err(|e| format!("Failed to persist the event card: {}", e))?;
let handle = format!("urn:mcard:telemetry:event:{}:{}", node_id, &hash[..16]);
conn.execute(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
rusqlite::params![handle, hash, event.timestamp],
)
.map_err(|e| format!("Failed to register the event handle: {}", e))?;
conn.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
rusqlite::params![handle, hash, event.timestamp],
)
.map_err(|e| format!("Failed to record the event history: {}", e))?;
Ok(())
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn load_learning_events(
conn: &rusqlite::Connection,
since: Option<&str>,
) -> Result<Vec<LearningEvent>, String> {
let mut events = Vec::new();
let sql = if since.is_some() {
"SELECT c.content FROM handle_registry r JOIN card c ON c.hash = r.current_hash \
WHERE r.handle LIKE 'urn:mcard:telemetry:event:%' AND c.g_time > ?1 \
ORDER BY c.g_time ASC"
} else {
"SELECT c.content FROM handle_registry r JOIN card c ON c.hash = r.current_hash \
WHERE r.handle LIKE 'urn:mcard:telemetry:event:%' ORDER BY c.g_time ASC"
};
let mut stmt = conn
.prepare(sql)
.map_err(|e| format!("Failed to prepare query: {}", e))?;
let map_row = |row: &rusqlite::Row| -> rusqlite::Result<Vec<u8>> { row.get(0) };
let rows = if let Some(since_ts) = since {
stmt.query_map(rusqlite::params![since_ts], map_row)
.map_err(|e| format!("Failed to query learning events: {}", e))?
} else {
stmt.query_map(rusqlite::params![], map_row)
.map_err(|e| format!("Failed to query learning events: {}", e))?
};
for row in rows {
let content = row.map_err(|e| format!("Failed to read row: {}", e))?;
let payload: TelemetryEventPayload = serde_json::from_slice(&content)
.map_err(|e| format!("Failed to deserialize the event card: {}", e))?;
events.push(LearningEvent {
vcard_hash: payload.vcard_hash,
pcard_hash: payload.pcard_hash,
agent_did: payload.agent_did,
timestamp: payload.timestamp,
vector_clock: payload.vector_clock,
marking_delta: payload.marking_delta,
});
}
Ok(events)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncReport {
pub events_merged: usize,
pub events_appended: usize,
pub conflicts: Vec<String>,
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn sync_learning_events(
local: &mut CrdtLog,
remote: &CrdtLog,
conn: &rusqlite::Connection,
) -> Result<SyncReport, String> {
let local_count_before = local.events.len();
local.merge(remote);
let events_appended = local.events.len() - local_count_before;
let conflicts: Vec<String> = local
.concurrent_pairs()
.iter()
.map(|(a, b)| {
format!(
"concurrent events: {} vs {} (vclock: {:?} vs {:?})",
a.vcard_hash, b.vcard_hash, a.vector_clock, b.vector_clock
)
})
.collect();
let events_merged = remote.events.len();
for event in &local.events {
persist_learning_event(conn, event, &local.node_id)?;
}
Ok(SyncReport {
events_merged,
events_appended,
conflicts,
})
}
#[cfg(test)]
const CANONICAL_DDL: &str = include_str!("../../../../schema/mcard_schema.sql");
#[cfg(test)]
#[path = "crdt_tests.rs"]
mod tests;
#[cfg(all(test, any(feature = "native", feature = "db")))]
mod orc18_round_trip {
use super::*;
#[test]
fn the_platform_writes_and_the_kernel_reads() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute_batch(CANONICAL_DDL).unwrap();
let body = serde_json::json!({
"kind": "MESH_EVENT",
"sprint": "ORC-18",
"vcard_hash": "v-seal-1",
"pcard_hash": "clm",
"agent_did": "did:key:z6MkRoot",
"timestamp": "2026-10-08T00:00:00Z",
"vector_clock": {"root": 3},
"marking_delta": {"sealed": ["clm"]},
});
let content = serde_json::to_vec(&body).unwrap();
let hash = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(&content);
format!("{:x}", h.finalize())
};
conn.execute(
"INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
rusqlite::params![hash, content, "2026-10-08T00:00:00Z"],
)
.unwrap();
conn.execute(
"INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
rusqlite::params!["urn:mcard:telemetry:event:root:1", hash, "2026-10-08T00:00:00Z"],
)
.unwrap();
let events = load_learning_events(&conn, None).expect("the loader must read the tape");
assert_eq!(events.len(), 1, "exactly one event");
let e = &events[0];
assert_eq!(e.agent_did, "did:key:z6MkRoot");
assert_eq!(e.pcard_hash, "clm");
assert_eq!(e.timestamp, "2026-10-08T00:00:00Z");
assert_eq!(
serde_json::to_value(&e.vector_clock).unwrap()["root"], 3,
"the CLOCK round-trips intact"
);
}
}