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)
}
#[inline]
fn record_algorithm_trimmed(record: &MCardRecord) -> &str {
let seg = record.g_time.split('|').next().unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3).trim();
if seg.is_empty() { crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3 } else { seg }
}
pub fn record_algorithm(record: &MCardRecord) -> String {
let seg = record_algorithm_trimmed(record);
if seg.is_ascii() && seg.bytes().all(|b| !b.is_ascii_uppercase()) {
seg.to_string()
} else {
seg.to_lowercase()
}
}
pub fn qualified_record_hash(record: &MCardRecord) -> String {
let algo = record_algorithm_trimmed(record);
let raw = record.hash.split_once(':').map(|(_, h)| h).unwrap_or(record.hash.as_str());
if algo.is_ascii() && algo.bytes().all(|b| !b.is_ascii_uppercase()) {
let mut out = String::with_capacity(algo.len() + 1 + raw.len());
out.push_str(algo);
out.push(':');
out.push_str(raw);
out
} else {
format!("{}:{raw}", algo.to_lowercase())
}
}
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, Deserialize)]
pub struct TokenMCard {
pub card: MCardRecord,
pub token_id: String,
pub color_type: String,
pub payload: Value,
}
impl TokenMCard {
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": "token_mcard",
"payload": payload,
"token_id": token_id,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self {
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)
}
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 {
matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
}
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, Deserialize)]
pub struct PlaceMCard {
pub card: MCardRecord,
pub place_id: String,
pub type_expr: String,
pub capacity: Option<usize>,
pub role: String,
#[serde(skip, default)]
pub cached_qualified_ref: MemoizedQualifiedRef,
}
impl PlaceMCard {
pub fn new(id: impl Into<String>) -> Self {
let place_id = id.into();
Self::create(&place_id, "any", None, "Intermediate", None, None).unwrap_or_else(|_| {
let envelope = json!({
"capacity": Value::Null,
"kind": "place_mcard",
"place_id": place_id,
"role": "Intermediate",
"type_expr": "any",
});
let card = record_from_canonical_json(&envelope, None, None).unwrap();
Self {
card,
place_id,
type_expr: "any".to_string(),
capacity: None,
role: "Intermediate".to_string(),
cached_qualified_ref: MemoizedQualifiedRef::default(),
}
})
}
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": "place_mcard",
"place_id": place_id,
"role": role,
"type_expr": type_expr,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self {
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))
.to_string()
}
pub fn qualified_ref(&self) -> String {
self.qualified_hash()
}
pub fn verify(&self) -> bool {
matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
}
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)
}
}