use crate::layer0::vocabulary::{DETERMINISTIC_EPOCH_TOKEN, HANDLE_MCARD_HASH_2, URI_SCHEME_MCARD};
#[allow(unused_imports)]
use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::domain::{
to_canonical_json_bytes, BailVerdict, BooleanPCard, CordisCoeffects,
InvariantPhase, MCard, MCardPayload, PrimitivePCard,
};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
#[allow(unused_imports)]
use crate::types::{AgentDid, ContentHash};
pub const DEFAULT_TIMESTAMP: &str = DETERMINISTIC_EPOCH_TOKEN;
pub const DEFAULT_LOCALE: &str = "UTC";
#[derive(Default)]
pub struct MemoizedQualifiedRef(OnceLock<String>);
impl MemoizedQualifiedRef {
#[inline]
pub fn get_or_init<F: FnOnce() -> String>(&self, f: F) -> &str {
self.0.get_or_init(f).as_str()
}
}
impl std::fmt::Debug for MemoizedQualifiedRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("MemoizedQualifiedRef").field(&self.0.get()).finish()
}
}
impl Clone for MemoizedQualifiedRef {
fn clone(&self) -> Self {
let lock = OnceLock::new();
if let Some(val) = self.0.get() {
let _ = lock.set(val.clone());
}
Self(lock)
}
}
impl PartialEq for MemoizedQualifiedRef {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for MemoizedQualifiedRef {}
impl PartialOrd for MemoizedQualifiedRef {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MemoizedQualifiedRef {
fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
}
}
impl std::hash::Hash for MemoizedQualifiedRef {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
pub fn record_from_canonical_json(
envelope: &Value,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<MCardRecord, String> {
let algo = algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3).trim().trim_end_matches(':').to_lowercase();
let ts = timestamp.unwrap_or(DEFAULT_TIMESTAMP);
let bytes = to_canonical_json_bytes(envelope);
MCardRecord::create_at(&bytes, Some(&algo), Some(ts), DEFAULT_LOCALE)
}
pub fn record_algorithm(record: &MCardRecord) -> Result<String, String> {
match verify_record(record) {
RecordVerification::DeclaredOk { algorithm } => Ok(algorithm),
verdict => Err(format!("unverified MCard reference: {verdict:?}")),
}
}
pub fn qualified_record_hash(record: &MCardRecord) -> Result<String, String> {
let algorithm = record_algorithm(record)?;
let raw = record.hash.split_once(':').map_or(record.hash.as_str(), |(_, hash)| hash);
Ok(format!("{algorithm}:{raw}"))
}
pub fn verify_envelope<T: Serialize>(record: &MCardRecord, model: &T, kind: &str) -> bool {
if record_algorithm(record).is_err() { return false; }
let Ok(mut view) = model_fields(model) else { return false; };
view.insert("kind".into(), Value::String(kind.into()));
serde_json::from_slice::<Value>(&record.content).is_ok_and(|stored| stored == Value::Object(view))
}
fn model_fields<T: Serialize>(model: &T) -> Result<serde_json::Map<String, Value>, String> {
let Value::Object(mut fields) = serde_json::to_value(model).map_err(|error| error.to_string())? else {
return Err("MCard model must serialize as an object".into());
};
fields.remove("card");
Ok(fields)
}
pub(super) fn reference_envelope<T: Serialize>(model: &T, record: &MCardRecord) -> Result<Value, String> {
record_algorithm(record)?;
let mut fields = model_fields(model)?;
fields.insert("hash".into(), record.hash.clone().into());
Ok(Value::Object(fields))
}
pub fn check_type_expr(payload: &Value, color_type: &str, type_expr: &str) -> bool {
let expr = type_expr.trim().to_lowercase();
let ctype = color_type.trim().to_lowercase();
let norm_ctype = ctype
.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
.or_else(|| ctype.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE))
.unwrap_or(&ctype);
let norm_expr = expr
.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
.or_else(|| expr.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE))
.unwrap_or(&expr);
if matches!(norm_expr, "any" | "*" | "top" | "true" | "") {
return true;
}
if matches!(norm_expr, "bottom" | "none" | "false" | "empty") {
return false;
}
if norm_ctype == norm_expr {
return true;
}
if norm_expr.ends_with("/*") || norm_expr.ends_with('/') {
let prefix = norm_expr.trim_end_matches('*');
return norm_ctype.starts_with(prefix);
}
match norm_expr {
"int" | "integer" | "number" => payload.is_i64() || payload.is_u64() || payload.is_f64(),
"str" | "string" | "text" => payload.is_string(),
"dict" | "map" | "object" | "structured" => payload.is_object(),
"list" | "array" => payload.is_array(),
"bool" | "boolean" => payload.is_boolean(),
_ if (norm_expr.starts_with("view/") || norm_expr.starts_with(crate::layer0::vocabulary::HANDLE_CLM_VIEW)) && norm_ctype == "session/active" => payload.is_object(),
_ => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct TokenMCard(TokenMCardData);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMCardData {
pub card: MCardRecord,
pub token_id: String,
pub color_type: String,
pub payload: Value,
}
impl std::ops::Deref for TokenMCard {
type Target = TokenMCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for TokenMCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let model = Self(TokenMCardData::deserialize(deserializer)?);
if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
}
}
impl TokenMCard {
const KIND: &'static str = "token_mcard";
pub fn from_payload(
payload: Value,
color_type: &str,
token_id: &str,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let envelope = json!({
"color_type": color_type,
"kind": Self::KIND,
"payload": payload,
"token_id": token_id,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self(TokenMCardData {
card,
token_id: token_id.to_string(),
color_type: color_type.to_string(),
payload,
}))
}
pub fn from_json(payload: &Value, color_type: &str, algorithm: Option<&str>) -> Result<Self, String> {
Self::from_payload(payload.clone(), color_type, "tok_json", algorithm, None)
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
qualified_record_hash(&self.card).expect("immutable verified MCard")
}
pub fn qualified_ref(&self) -> String {
self.qualified_hash()
}
pub fn to_hash_uri(&self) -> String {
format!("{HANDLE_MCARD_HASH_2}{}", self.qualified_hash())
}
pub fn to_uri(&self) -> String {
format!("{URI_SCHEME_MCARD}{}", self.qualified_hash())
}
pub fn verify(&self) -> bool {
verify_envelope(&self.card, self, Self::KIND)
}
pub fn as_primitive_pcard(&self) -> PrimitivePCard {
let author = AgentDid::new(crate::layer0::vocabulary_identities::DID_CLM_LAYER1).unwrap_or_else(|_| AgentDid::new_unchecked(crate::layer0::vocabulary_identities::DID_CLM_LAYER1));
let uri = format!("{URI_SCHEME_MCARD}{}", self.qualified_hash());
let mcard = MCard::new(uri, MCardPayload::Structured(self.payload.clone()), author, 0);
PrimitivePCard::new(mcard)
}
pub fn evaluate(&self) -> &Value {
&self.payload
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct PlaceMCard(PlaceMCardData);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PlaceMCardData {
pub card: MCardRecord,
pub place_id: String,
pub type_expr: String,
pub capacity: Option<usize>,
pub role: String,
#[serde(skip, default)]
cached_qualified_ref: MemoizedQualifiedRef,
}
impl std::ops::Deref for PlaceMCard {
type Target = PlaceMCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for PlaceMCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let model = Self(PlaceMCardData::deserialize(deserializer)?);
if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
}
}
impl PlaceMCard {
const KIND: &'static str = "place_mcard";
pub fn new(id: impl Into<String>) -> Self {
Self::create(&id.into(), "any", None, "Intermediate", None, None).expect("default place envelope")
}
pub fn id(&self) -> &str {
&self.place_id
}
pub fn create(
place_id: &str,
type_expr: &str,
capacity: Option<usize>,
role: &str,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let cap_val = capacity.map(|c| json!(c)).unwrap_or(Value::Null);
let envelope = json!({
"capacity": cap_val,
"kind": Self::KIND,
"place_id": place_id,
"role": role,
"type_expr": type_expr,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self(PlaceMCardData {
card,
place_id: place_id.to_string(),
type_expr: type_expr.to_string(),
capacity,
role: role.to_string(),
cached_qualified_ref: MemoizedQualifiedRef::default(),
}))
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
self.cached_qualified_ref
.get_or_init(|| qualified_record_hash(&self.card).expect("immutable verified MCard"))
.to_string()
}
pub fn qualified_ref(&self) -> String {
self.qualified_hash()
}
pub fn verify(&self) -> bool {
verify_envelope(&self.card, self, Self::KIND)
}
pub fn as_boolean_pcard(&self) -> BooleanPCard {
BooleanPCard {
id: self.place_id.clone(),
phase: InvariantPhase::Precondition,
expression: self.type_expr.clone(),
guarded_uri_pattern: format!("{URI_SCHEME_MCARD}{}", self.qualified_hash()),
coeffects: CordisCoeffects::default(),
}
}
pub fn evaluate_guard(&self, token: &TokenMCard, current_occupancy: usize) -> BailVerdict {
if let Some(cap) = self.capacity {
if current_occupancy >= cap {
return BailVerdict::Bail {
reason: format!("Place '{}' capacity {} exceeded", self.place_id, cap),
invariant_code: "INV-508-CAP".to_string(),
context_dump: json!({ "place_id": self.place_id, "capacity": cap }),
};
}
}
if check_type_expr(&token.payload, &token.color_type, &self.type_expr) {
BailVerdict::Pass
} else {
BailVerdict::Bail {
reason: format!(
"Token '{}' (color '{}') rejected by place '{}' guard '{}'",
token.token_id, token.color_type, self.place_id, self.type_expr
),
invariant_code: "INV-508-TYPE".to_string(),
context_dump: json!({
"place_id": self.place_id,
"expected": self.type_expr,
"actual": token.color_type,
}),
}
}
}
pub fn admits(&self, token: &TokenMCard, current_occupancy: usize) -> bool {
matches!(self.evaluate_guard(token, current_occupancy), BailVerdict::Pass)
}
}