use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::domain::{
to_canonical_json_bytes, BailVerdict, BooleanPCard, CordisCoeffects, DynamicPCard,
InvariantPhase, MCard, MCardPayload, PrimitivePCard,
};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
use crate::types::{AgentDid, ContentHash};
pub const DEFAULT_TIMESTAMP: &str = "2026-04-16T00:00:00Z";
pub const DEFAULT_LOCALE: &str = "UTC";
pub fn record_from_canonical_json(
envelope: &Value,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<MCardRecord, String> {
let algo = algorithm.unwrap_or("blake3").trim().trim_end_matches(':').to_lowercase();
let ts = timestamp.unwrap_or(DEFAULT_TIMESTAMP);
let bytes = to_canonical_json_bytes(envelope);
let hash = crate::hash::raw_hash_bytes_for(&algo, &bytes)?;
let g_time = crate::fs_utils::compute_g_time_at(&algo, ts, DEFAULT_LOCALE)?;
Ok(MCardRecord { hash, content: bytes, g_time })
}
pub fn record_algorithm(record: &MCardRecord) -> String {
record.g_time.split('|').next().unwrap_or("blake3").trim().to_lowercase()
}
pub fn qualified_record_hash(record: &MCardRecord) -> String {
let algo = record_algorithm(record);
let raw = record.hash.split_once(':').map(|(_, h)| h).unwrap_or(record.hash.as_str());
format!("{algo}:{raw}")
}
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();
if matches!(expr.as_str(), "any" | "*" | "top" | "true" | "" | "clm://type/any") {
return true;
}
if matches!(expr.as_str(), "bottom" | "none" | "false" | "empty") {
return false;
}
if ctype == expr || (expr.starts_with("clm://") && !ctype.starts_with("clm://")) {
return true;
}
match expr.as_str() {
"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(),
_ => 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 verify(&self) -> bool {
matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
}
pub fn as_primitive_pcard(&self) -> PrimitivePCard {
let author = AgentDid::new("did:clm:layer1").unwrap_or_else(|_| AgentDid::new_unchecked("did:clm:layer1"));
let uri = format!("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, Serialize, Deserialize)]
pub struct PlaceMCard {
pub card: MCardRecord,
pub place_id: String,
pub type_expr: String,
pub capacity: Option<usize>,
pub role: String,
}
impl PlaceMCard {
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(),
})
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
qualified_record_hash(&self.card)
}
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!("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)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionMCard {
pub card: MCardRecord,
pub transition_id: String,
pub input_places: Vec<String>,
pub output_places: Vec<String>,
pub domain_type: String,
pub codomain_type: String,
pub coeffects: BTreeMap<String, String>,
pub operation_expr: String,
}
impl TransitionMCard {
pub fn default_coeffect_map() -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
for axis in ["filesystem", "network", "random", "sqlite", "time"] {
m.insert(axis.to_string(), "none".to_string());
}
m
}
pub fn create(
transition_id: &str,
input_places: Vec<String>,
output_places: Vec<String>,
domain_type: &str,
codomain_type: &str,
coeffects: Option<BTreeMap<String, String>>,
operation_expr: &str,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let coeff = coeffects.unwrap_or_else(Self::default_coeffect_map);
let envelope = json!({
"codomain_type": codomain_type,
"coeffects": coeff,
"domain_type": domain_type,
"input_places": input_places,
"kind": "transition_mcard",
"operation_expr": operation_expr,
"output_places": output_places,
"transition_id": transition_id,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self {
card,
transition_id: transition_id.to_string(),
input_places,
output_places,
domain_type: domain_type.to_string(),
codomain_type: codomain_type.to_string(),
coeffects: coeff,
operation_expr: operation_expr.to_string(),
})
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
qualified_record_hash(&self.card)
}
pub fn verify(&self) -> bool {
matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
}
pub fn as_dynamic_pcard(&self) -> DynamicPCard {
let services: Vec<String> = self
.coeffects
.iter()
.filter(|(_, mode)| mode.as_str() != "none")
.map(|(k, v)| format!("{k}:{v}"))
.collect();
DynamicPCard {
id: self.transition_id.clone(),
code_hash: ContentHash::parse(&self.card.hash)
.unwrap_or_else(|_| ContentHash::compute(&self.card.content)),
source_uri: format!("mcard://{}", self.qualified_hash()),
coeffects: CordisCoeffects {
required_services: services,
input_schema_uri: Some(self.domain_type.clone()),
output_schema_uri: Some(self.codomain_type.clone()),
required_capabilities: Vec::new(),
},
signature: format!("{} -> {}", self.domain_type, self.codomain_type),
}
}
pub fn fire<F>(
&self,
input_tokens: &[TokenMCard],
transform: F,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Vec<TokenMCard>, String>
where
F: Fn(&[Value]) -> Value,
{
let algo = algorithm.unwrap_or_else(|| {
if self.card.g_time.starts_with("sha256|") { "sha256" } else { "blake3" }
});
let raw_inputs: Vec<Value> = input_tokens.iter().map(|t| t.payload.clone()).collect();
let out_payload = transform(&raw_inputs);
let out_count = self.output_places.len().max(1);
let mut produced = Vec::with_capacity(out_count);
for idx in 0..out_count {
produced.push(TokenMCard::from_payload(
out_payload.clone(),
&self.codomain_type,
&format!("{}_out_{idx}", self.transition_id),
Some(algo),
timestamp,
)?);
}
Ok(produced)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetMCard {
pub card: MCardRecord,
pub net_id: String,
pub places: Vec<PlaceMCard>,
pub transitions: Vec<TransitionMCard>,
pub marking: BTreeMap<String, Vec<TokenMCard>>,
}
impl NetMCard {
pub fn create(
net_id: &str,
places: Vec<PlaceMCard>,
transitions: Vec<TransitionMCard>,
marking: BTreeMap<String, Vec<TokenMCard>>,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let mut marking_json = serde_json::Map::new();
for (pid, toks) in &marking {
let arr: Vec<Value> = toks
.iter()
.map(|t| json!({"color_type": t.color_type, "hash": t.card.hash, "payload": t.payload, "token_id": t.token_id}))
.collect();
marking_json.insert(pid.clone(), Value::Array(arr));
}
let places_json: Vec<Value> = places
.iter()
.map(|p| json!({"capacity": p.capacity, "hash": p.card.hash, "place_id": p.place_id, "role": p.role, "type_expr": p.type_expr}))
.collect();
let trans_json: Vec<Value> = transitions
.iter()
.map(|tr| json!({"codomain_type": tr.codomain_type, "coeffects": tr.coeffects, "domain_type": tr.domain_type, "hash": tr.card.hash, "input_places": tr.input_places, "operation_expr": tr.operation_expr, "output_places": tr.output_places, "transition_id": tr.transition_id}))
.collect();
let envelope = json!({
"kind": "net_mcard",
"marking": Value::Object(marking_json),
"net_id": net_id,
"places": places_json,
"transitions": trans_json,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self { card, net_id: net_id.to_string(), places, transitions, marking })
}
pub fn to_token_mcard(&self, algorithm: Option<&str>, timestamp: Option<&str>) -> Result<TokenMCard, String> {
let payload: Value = serde_json::from_slice(&self.card.content)
.map_err(|e| format!("Failed to decode NetMCard content: {e}"))?;
let algo_owned = record_algorithm(&self.card);
let algo = algorithm.unwrap_or(&algo_owned);
TokenMCard::from_payload(payload, "net_mcard", &format!("net_tok_{}", self.net_id), Some(algo), timestamp)
}
}
pub fn reify_pcard_descriptor(
descriptor: &Value,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<TokenMCard, String> {
let schema = descriptor.get("schema").and_then(|v| v.as_str()).unwrap_or("");
if schema != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported PCard descriptor schema: {schema}"));
}
if descriptor.get("closure").is_some() || descriptor.get("ambient_capability").is_some() {
return Err("Non-serializable closure or ambient capability rejected".to_string());
}
let id = descriptor.get("id").and_then(|v| v.as_str()).unwrap_or("pcard_0");
TokenMCard::from_payload(
descriptor.clone(),
"clm://layer1/pcard_descriptor/v1",
&format!("tok_desc_{id}"),
algorithm,
timestamp,
)
}
pub fn reflect_pcard_descriptor(token: &TokenMCard, registered_ops: &[&str]) -> Result<Value, String> {
if token.color_type != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported token color_type for descriptor reflection: {}", token.color_type));
}
let schema = token.payload.get("schema").and_then(|v| v.as_str()).unwrap_or("");
if schema != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported PCard descriptor schema: {schema}"));
}
let variant = token.payload.get("variant").and_then(|v| v.as_str()).unwrap_or("");
if variant == "dynamic" {
let op = token.payload.get("operation_id").and_then(|v| v.as_str()).unwrap_or("");
if !registered_ops.contains(&op) {
return Err(format!("Unregistered operation_id rejected: {op}"));
}
} else if variant != "primitive" && variant != "boolean" {
return Err(format!("Unsupported PCard variant: {variant}"));
}
Ok(token.payload.clone())
}