clm-kernel 0.0.6

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Self-verifying CAS records, distinct from the legacy bare-BLAKE3 `MCard` domain type.
//!
//! The algorithm is resolved once at write time and used for both the digest and the canonical
//! `g_time` coordinate. Readers derive the declared algorithm from stored `g_time`; an ISO-only
//! legacy coordinate is classified only by digest recomputation and is never defaulted.

use chrono::{DateTime, NaiveDateTime};
use rusqlite::Connection;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardRecord {
    pub hash: String,
    pub content: Vec<u8>,
    #[serde(alias = "gTime")]
    pub g_time: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordVerification {
    DeclaredOk { algorithm: String },
    DeclaredMismatch { algorithm: String, computed_hash: String },
    LegacyClassified { algorithm: String },
    LegacyUnclassified,
    LegacyAmbiguous,
    Malformed { reason: String },
}

fn valid_timestamp(timestamp: &str) -> bool {
    if !timestamp.is_ascii() {
        return false;
    }
    if DateTime::parse_from_rfc3339(timestamp).is_ok() {
        return true;
    }
    // Historical Python/Rust emitters used RFC3339-style offsets without the colon (`+0000`).
    if timestamp.len() >= 5 {
        let offset_start = timestamp.len() - 5;
        let offset = &timestamp[offset_start..];
        if (offset.starts_with('+') || offset.starts_with('-'))
            && offset[1..].chars().all(|ch| ch.is_ascii_digit())
        {
            let normalized = format!("{}{}:{}", &timestamp[..offset_start], &offset[..3], &offset[3..]);
            if DateTime::parse_from_rfc3339(&normalized).is_ok() {
                return true;
            }
        }
    }
    NaiveDateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S%.f").is_ok()
}

impl MCardRecord {
    /// Create a fresh record using an explicit algorithm or the runtime configuration.
    pub fn create(content: &[u8], algorithm: Option<&str>) -> Result<Self, String> {
        Self::create_at(content, algorithm, None, "UTC")
    }

    /// Create a record with a caller-supplied timestamp and locale, canonicalized through the shared codec.
    pub fn create_at(
        content: &[u8],
        algorithm: Option<&str>,
        timestamp: Option<&str>,
        locale: &str,
    ) -> Result<Self, String> {
        let selected = algorithm
            .unwrap_or(crate::hash::config().active_algorithm)
            .trim()
            .trim_end_matches(':')
            .to_lowercase();
        let hash = crate::hash::raw_hash_bytes_for(&selected, content)?;
        let g_time = match timestamp {
            Some(value) => crate::fs_utils::compute_g_time_at(&selected, value, locale)?,
            None => crate::fs_utils::compute_g_time_for(&selected),
        };
        Ok(Self {
            hash,
            content: content.to_vec(),
            g_time,
        })
    }
}

pub fn create_record(content: &[u8], algorithm: Option<&str>) -> Result<MCardRecord, String> {
    MCardRecord::create(content, algorithm)
}

/// Verify an existing record using only its stored hash, content, and `g_time`.
pub fn verify_record(record: &MCardRecord) -> RecordVerification {
    if record.hash.trim().is_empty() || record.g_time.trim().is_empty() {
        return RecordVerification::Malformed {
            reason: "empty hash or g_time".to_string(),
        };
    }

    let (hash_prefix, target_hash) = match record.hash.split_once(':') {
        Some((prefix, raw)) => (Some(prefix.to_lowercase()), raw.to_lowercase()),
        None => (None, record.hash.to_lowercase()),
    };

    if record.g_time.contains('|') {
        let mut parts = record.g_time.split('|');
        let algorithm = parts.next().unwrap_or_default().trim().to_lowercase();
        let timestamp = parts.next().unwrap_or_default().trim();
        let locale = parts.next();
        if algorithm.is_empty() || locale.is_none() || !valid_timestamp(timestamp) {
            return RecordVerification::Malformed {
                reason: "invalid canonical pipe g_time".to_string(),
            };
        }
        if hash_prefix.as_deref().is_some_and(|prefix| prefix != algorithm) {
            return RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: String::new(),
            };
        }
        let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
            Ok(value) => value,
            Err(reason) => return RecordVerification::Malformed { reason },
        };
        return if computed == target_hash {
            RecordVerification::DeclaredOk { algorithm }
        } else {
            RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: computed,
            }
        };
    }

    // Read-only compatibility for the pre-convergence TypeScript coordinate. It declares its own
    // algorithm and is verified under that value; the writer below never emits this grammar.
    if record.g_time.starts_with("a:") {
        let mut fields = HashMap::new();
        for segment in record.g_time.split(';') {
            let Some((key, value)) = segment.split_once(':') else {
                return RecordVerification::Malformed {
                    reason: "invalid legacy TypeScript g_time segment".to_string(),
                };
            };
            if fields.insert(key, value).is_some() {
                return RecordVerification::Malformed {
                    reason: "duplicate legacy TypeScript g_time key".to_string(),
                };
            }
        }
        let algorithm = fields.get("a").copied().unwrap_or_default().to_lowercase();
        let timestamp = fields.get("t").copied().unwrap_or_default();
        if algorithm.is_empty() || !valid_timestamp(timestamp) {
            return RecordVerification::Malformed {
                reason: "invalid legacy TypeScript g_time coordinates".to_string(),
            };
        }
        if hash_prefix.as_deref().is_some_and(|prefix| prefix != algorithm) {
            return RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: String::new(),
            };
        }
        let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
            Ok(value) => value,
            Err(reason) => return RecordVerification::Malformed { reason },
        };
        return if computed == target_hash {
            RecordVerification::DeclaredOk { algorithm }
        } else {
            RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: computed,
            }
        };
    }

    // Bare ISO timestamp carries no algorithm. Do not consult the configured default here.
    if !valid_timestamp(record.g_time.trim()) {
        return RecordVerification::Malformed {
            reason: "unrecognized g_time shape".to_string(),
        };
    }
    let mut matches = Vec::new();
    for prefix in crate::hash::list_algorithms() {
        let algorithm = prefix.trim_end_matches(':');
        if let Ok(computed) = crate::hash::raw_hash_bytes_for(algorithm, &record.content) {
            if computed == target_hash {
                matches.push(algorithm.to_string());
            }
        }
    }
    match matches.len() {
        1 => RecordVerification::LegacyClassified {
            algorithm: matches.remove(0),
        },
        n if n > 1 => RecordVerification::LegacyAmbiguous,
        _ => RecordVerification::LegacyUnclassified,
    }
}

/// Persist a declared record to an existing `card` table and verify the database read-back.
pub fn write_record(
    connection: &Connection,
    content: &[u8],
    algorithm: Option<&str>,
) -> Result<MCardRecord, String> {
    let record = create_record(content, algorithm)?;
    if !matches!(verify_record(&record), RecordVerification::DeclaredOk { .. }) {
        return Err("new Rust record did not verify before persistence".to_string());
    }

    let persisted_hash = crate::tape::put(connection, &record.content, &record.g_time)?;
    if persisted_hash != record.hash {
        return Err("tape writer changed the selected MCardRecord digest".to_string());
    }

    let read_back = connection
        .query_row(
            "SELECT hash, content, g_time FROM card WHERE hash = ?1",
            [&record.hash],
            |row| {
                Ok(MCardRecord {
                    hash: row.get(0)?,
                    content: row.get(1)?,
                    g_time: row.get(2)?,
                })
            },
        )
        .map_err(|error| format!("failed to read back MCardRecord: {error}"))?;

    match verify_record(&read_back) {
        RecordVerification::DeclaredOk { .. } => Ok(read_back),
        verdict => Err(format!("persisted MCardRecord failed verification: {verdict:?}")),
    }
}