use crate::satori::element::SatoriMessage;
pub use crate::types::{AgentDid, ContentHash, Handle};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value")]
pub enum MCardPayload {
Scalar(serde_json::Value),
Text(String),
Satori(SatoriMessage),
Binary {
mime_type: String,
data: Vec<u8>,
},
Structured(serde_json::Value),
Executable(Box<PCardDefinition>),
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(transparent)]
pub struct MCard(MCardData);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MCardData {
pub uri: String,
pub hash: ContentHash,
pub payload: MCardPayload,
pub metadata: HashMap<String, serde_json::Value>,
pub author: AgentDid,
pub sequence: u64,
pub g_time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcard_preimage_v1: Option<crate::layer0::mcard_projection::MCardPreimage>,
}
pub fn canonicalize_json_value(val: &serde_json::Value) -> serde_json::Value {
match val {
serde_json::Value::Object(map) => {
let mut btree = std::collections::BTreeMap::new();
for (k, v) in map {
btree.insert(k.clone(), canonicalize_json_value(v));
}
serde_json::to_value(&btree).unwrap_or_else(|_| val.clone())
}
serde_json::Value::Array(arr) => {
let canon_arr: Vec<serde_json::Value> = arr.iter().map(canonicalize_json_value).collect();
serde_json::Value::Array(canon_arr)
}
_ => val.clone(),
}
}
pub fn to_canonical_json_bytes(val: &serde_json::Value) -> Vec<u8> {
crate::layer0::codec::canonical_json(val)
.map(|s| s.into_bytes())
.unwrap_or_default()
}
pub fn serialize_canonical_payload(payload: &MCardPayload) -> Vec<u8> {
if let Ok(val) = serde_json::to_value(payload) {
to_canonical_json_bytes(&val)
} else {
serde_json::to_vec(payload).unwrap_or_default()
}
}
pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
let bytes = serialize_canonical_payload(payload);
ContentHash::parse(crate::layer0::hash::compute_blake3(&bytes)).expect("BLAKE3 emits a valid digest")
}
impl std::ops::Deref for MCard {
type Target = MCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for MCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let card = Self(MCardData::deserialize(deserializer)?);
card.to_record().map_err(serde::de::Error::custom)?;
Ok(card)
}
}
impl MCard {
pub fn new(uri: impl Into<String>, payload: MCardPayload, author: AgentDid, sequence: u64) -> Self {
let hash = compute_canonical_hash(&payload);
Self(MCardData {
uri: uri.into(),
hash,
payload,
metadata: HashMap::new(),
author,
sequence,
g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
mcard_preimage_v1: None,
})
}
pub fn to_record(&self) -> Result<crate::layer0::mcard_record::MCardRecord, String> {
crate::layer0::mcard_projection::verified_record(self, self.hash.as_str(), &self.g_time,
serialize_canonical_payload(&self.payload), self.mcard_preimage_v1.as_ref())
}
pub fn with_metadata(
uri: impl Into<String>,
payload: MCardPayload,
metadata: HashMap<String, serde_json::Value>,
author: AgentDid,
sequence: u64,
) -> Self {
let hash = compute_canonical_hash(&payload);
Self(MCardData {
uri: uri.into(),
hash,
payload,
metadata,
author,
sequence,
g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
mcard_preimage_v1: None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CordisCoeffects {
pub required_services: Vec<String>,
pub input_schema_uri: Option<String>,
pub output_schema_uri: Option<String>,
pub required_capabilities: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrimitivePCard {
pub mcard: MCard,
}
impl PrimitivePCard {
pub fn new(mcard: MCard) -> Self {
Self { mcard }
}
pub fn evaluate(&self) -> &MCard {
&self.mcard
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DynamicPCard {
pub id: String,
pub code_hash: ContentHash,
pub source_uri: String,
pub coeffects: CordisCoeffects,
pub signature: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BailVerdict {
Pass,
Bail {
reason: String,
invariant_code: String,
context_dump: serde_json::Value,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvariantPhase {
Precondition,
Postcondition,
LoopInvariant,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BooleanPCard {
pub id: String,
pub phase: InvariantPhase,
pub expression: String,
pub guarded_uri_pattern: String,
pub coeffects: CordisCoeffects,
}
impl BooleanPCard {
pub fn is_precondition(&self) -> bool {
self.phase == InvariantPhase::Precondition
}
pub fn is_postcondition(&self) -> bool {
self.phase == InvariantPhase::Postcondition
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "pcard_type")]
pub enum PCardDefinition {
Primitive(Box<PrimitivePCard>),
Dynamic(DynamicPCard),
Boolean(BooleanPCard),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mcard_blake3_hash_generation() {
let author = AgentDid::new("did:clm:agent:tester").unwrap();
let payload = MCardPayload::Text("Hello Cordis Koishi FND".to_string());
let mcard = MCard::new("mcard:test/msg1", payload.clone(), author.clone(), 1);
assert_eq!(mcard.uri, "mcard:test/msg1");
assert_eq!(mcard.author, author);
assert_eq!(mcard.sequence, 1);
assert_eq!(mcard.hash.as_str().len(), 64);
let mcard2 = MCard::new("mcard:test/msg2", payload, author, 2);
assert_eq!(mcard.hash, mcard2.hash);
}
#[test]
fn test_primitive_pcard_evaluation() {
let author = AgentDid::new("did:clm:agent:tester").unwrap();
let payload = MCardPayload::Scalar(serde_json::json!(42));
let mcard = MCard::new("mcard:scalar/answer", payload, author, 1);
let primitive = PrimitivePCard::new(mcard.clone());
assert_eq!(primitive.evaluate(), &mcard);
}
#[test]
fn test_canonical_json_preimage_univalence() {
let v1 = serde_json::json!({"z": 1, "a": 2, "m": {"y": 3, "b": 4}});
let v2 = serde_json::json!({"a": 2, "m": {"b": 4, "y": 3}, "z": 1});
let bytes1 = to_canonical_json_bytes(&v1);
let bytes2 = to_canonical_json_bytes(&v2);
assert_eq!(bytes1, bytes2);
assert_eq!(std::str::from_utf8(&bytes1).unwrap(), "{\"a\":2,\"m\":{\"b\":4,\"y\":3},\"z\":1}");
let v_unicode = serde_json::json!({"greeting": "Hello, δΈη! π"});
let bytes_u = to_canonical_json_bytes(&v_unicode);
let str_u = std::str::from_utf8(&bytes_u).unwrap();
assert!(!str_u.contains("\\u"));
assert!(str_u.contains("Hello, δΈη! π"));
let hash = ContentHash::compute(&bytes1);
assert_eq!(hash.as_str().len(), 64);
}
}