use chrono::{DateTime, NaiveDateTime};
use rusqlite::Connection;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
pub const CLM_SCHEMA_PCARD_DESCRIPTOR_V1: &str = "clm://layer1/pcard_descriptor/v1";
pub const CLM_SCHEMA_DIRECTORY_MANIFEST_V1: &str = "clm://layer2/directory_manifest/v1";
pub const CLM_SCHEMA_CHUNK_MANIFEST_V1: &str = "clm://layer2/chunk_manifest/v1";
pub const CLM_SCHEMA_PRUNING_ANCHOR_V1: &str = "clm://layer2/pruning_anchor/v1";
pub const CLM_SCHEMA_CONVERSATIONAL_TURN_V1: &str = "clm://layer4/conversational_turn/v1";
pub fn normalize_schema_uri(uri: &str) -> String {
match uri {
"mcard://schemas/conversational-turn/v1" => CLM_SCHEMA_CONVERSATIONAL_TURN_V1.to_string(),
_ => uri.to_string(),
}
}
pub fn is_valid_clm_schema_uri(uri: &str) -> bool {
let Some(rest) = uri.strip_prefix("clm://layer") else { return false; };
let Some((layer, rest)) = rest.split_once('/') else { return false; };
if layer.len() != 1 || !layer.as_bytes()[0].is_ascii_digit() || layer.as_bytes()[0] > b'5' {
return false;
}
let Some((artifact, version)) = rest.rsplit_once("/v") else { return false; };
!artifact.is_empty()
&& artifact.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
&& !version.is_empty()
&& version.chars().all(|c| c.is_ascii_digit())
}
pub fn validate_schema_fields(schema: Option<&str>, schema_uri: Option<&str>) -> Result<(), String> {
if let (Some(schema), Some(schema_uri)) = (schema, schema_uri) {
if normalize_schema_uri(schema) != normalize_schema_uri(schema_uri) {
return Err(format!("Schema mismatch: {schema} vs {schema_uri}"));
}
}
Ok(())
}
#[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;
}
if timestamp.len() >= 5 {
let offset_start = timestamp.len() - 5;
let offset = ×tamp[offset_start..];
if (offset.starts_with('+') || offset.starts_with('-'))
&& offset[1..].chars().all(|ch| ch.is_ascii_digit())
{
let normalized = format!("{}{}:{}", ×tamp[..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 {
pub fn create(content: &[u8], algorithm: Option<&str>) -> Result<Self, String> {
Self::create_at(content, algorithm, None, "UTC")
}
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)
}
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,
}
};
}
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,
}
};
}
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,
}
}
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:?}")),
}
}