1use crate::satori::element::SatoriMessage;
10pub use crate::types::{AgentDid, ContentHash, Handle};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[serde(tag = "kind", content = "value")]
17pub enum MCardPayload {
18 Scalar(serde_json::Value),
20 Text(String),
22 Satori(SatoriMessage),
24 Binary {
26 mime_type: String,
27 data: Vec<u8>,
28 },
29 Structured(serde_json::Value),
31 Executable(Box<PCardDefinition>),
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize)]
37#[serde(transparent)]
38pub struct MCard(MCardData);
39
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42pub struct MCardData {
43 pub uri: String,
45 pub hash: ContentHash,
47 pub payload: MCardPayload,
49 pub metadata: HashMap<String, serde_json::Value>,
51 pub author: AgentDid,
53 pub sequence: u64,
55 pub g_time: String,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub mcard_preimage_v1: Option<crate::layer0::mcard_projection::MCardPreimage>,
58}
59
60pub use crate::layer0::codec::sort_json_value as canonicalize_json_value;
61
62pub fn to_canonical_json_bytes(val: &serde_json::Value) -> Vec<u8> {
64 crate::layer0::codec::canonical_json(val)
65 .map(|s| s.into_bytes())
66 .unwrap_or_default()
67}
68
69pub fn serialize_canonical_payload(payload: &MCardPayload) -> Vec<u8> {
71 if let Ok(val) = serde_json::to_value(payload) {
72 to_canonical_json_bytes(&val)
73 } else {
74 serde_json::to_vec(payload).unwrap_or_default()
75 }
76}
77
78pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
80 let bytes = serialize_canonical_payload(payload);
81 ContentHash::parse(crate::layer0::hash::compute_blake3(&bytes)).expect("BLAKE3 emits a valid digest")
82}
83
84impl std::ops::Deref for MCard {
85 type Target = MCardData;
86 fn deref(&self) -> &Self::Target { &self.0 }
87}
88
89impl<'de> Deserialize<'de> for MCard {
90 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
91 let card = Self(MCardData::deserialize(deserializer)?);
92 card.to_record().map_err(serde::de::Error::custom)?;
93 Ok(card)
94 }
95}
96
97impl MCard {
98 pub fn new(uri: impl Into<String>, payload: MCardPayload, author: AgentDid, sequence: u64) -> Self {
100 let hash = compute_canonical_hash(&payload);
101 Self(MCardData {
102 uri: uri.into(),
103 hash,
104 payload,
105 metadata: HashMap::new(),
106 author,
107 sequence,
108 g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
109 mcard_preimage_v1: None,
110 })
111 }
112
113 pub fn to_record(&self) -> Result<crate::layer0::mcard_record::MCardRecord, String> {
114 crate::layer0::mcard_projection::verified_record(self, self.hash.as_str(), &self.g_time,
115 serialize_canonical_payload(&self.payload), self.mcard_preimage_v1.as_ref())
116 }
117
118 pub fn with_metadata(
120 uri: impl Into<String>,
121 payload: MCardPayload,
122 metadata: HashMap<String, serde_json::Value>,
123 author: AgentDid,
124 sequence: u64,
125 ) -> Self {
126 let hash = compute_canonical_hash(&payload);
127 Self(MCardData {
128 uri: uri.into(),
129 hash,
130 payload,
131 metadata,
132 author,
133 sequence,
134 g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
135 mcard_preimage_v1: None,
136 })
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
142pub struct CordisCoeffects {
143 pub required_services: Vec<String>,
145 pub input_schema_uri: Option<String>,
147 pub output_schema_uri: Option<String>,
149 pub required_capabilities: Vec<String>,
151}
152
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct PrimitivePCard {
157 pub mcard: MCard,
158}
159
160impl PrimitivePCard {
161 pub fn new(mcard: MCard) -> Self {
162 Self { mcard }
163 }
164 pub fn evaluate(&self) -> &MCard {
166 &self.mcard
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub struct DynamicPCard {
174 pub id: String,
175 pub code_hash: ContentHash,
177 pub source_uri: String,
179 pub coeffects: CordisCoeffects,
181 pub signature: String,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub enum BailVerdict {
188 Pass,
190 Bail {
192 reason: String,
193 invariant_code: String,
194 context_dump: serde_json::Value,
195 },
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
200pub enum InvariantPhase {
201 Precondition,
203 Postcondition,
205 LoopInvariant,
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct BooleanPCard {
212 pub id: String,
213 pub phase: InvariantPhase,
214 pub expression: String,
216 pub guarded_uri_pattern: String,
218 pub coeffects: CordisCoeffects,
220}
221
222impl BooleanPCard {
223 pub fn is_precondition(&self) -> bool {
224 self.phase == InvariantPhase::Precondition
225 }
226 pub fn is_postcondition(&self) -> bool {
227 self.phase == InvariantPhase::Postcondition
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
232#[serde(tag = "pcard_type")]
233pub enum PCardDefinition {
234 Primitive(Box<PrimitivePCard>),
235 Dynamic(DynamicPCard),
236 Boolean(BooleanPCard),
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 #[test]
244 fn test_mcard_blake3_hash_generation() {
245 let author = AgentDid::new("did:clm:agent:tester").unwrap();
246 let payload = MCardPayload::Text("Hello Cordis Koishi FND".to_string());
247 let mcard = MCard::new("mcard:test/msg1", payload.clone(), author.clone(), 1);
248
249 assert_eq!(mcard.uri, "mcard:test/msg1");
250 assert_eq!(mcard.author, author);
251 assert_eq!(mcard.sequence, 1);
252 assert_eq!(mcard.hash.as_str().len(), 64);
253
254 let mcard2 = MCard::new("mcard:test/msg2", payload, author, 2);
256 assert_eq!(mcard.hash, mcard2.hash);
257 }
258
259 #[test]
260 fn test_primitive_pcard_evaluation() {
261 let author = AgentDid::new("did:clm:agent:tester").unwrap();
262 let payload = MCardPayload::Scalar(serde_json::json!(42));
263 let mcard = MCard::new("mcard:scalar/answer", payload, author, 1);
264 let primitive = PrimitivePCard::new(mcard.clone());
265
266 assert_eq!(primitive.evaluate(), &mcard);
267 }
268
269 #[test]
270 fn test_canonical_json_preimage_univalence() {
271 let v1 = serde_json::json!({"z": 1, "a": 2, "m": {"y": 3, "b": 4}});
272 let v2 = serde_json::json!({"a": 2, "m": {"b": 4, "y": 3}, "z": 1});
273 let bytes1 = to_canonical_json_bytes(&v1);
274 let bytes2 = to_canonical_json_bytes(&v2);
275 assert_eq!(bytes1, bytes2);
276 assert_eq!(std::str::from_utf8(&bytes1).unwrap(), "{\"a\":2,\"m\":{\"b\":4,\"y\":3},\"z\":1}");
277
278 let v_unicode = serde_json::json!({"greeting": "Hello, δΈη! π"});
279 let bytes_u = to_canonical_json_bytes(&v_unicode);
280 let str_u = std::str::from_utf8(&bytes_u).unwrap();
281 assert!(!str_u.contains("\\u"));
282 assert!(str_u.contains("Hello, δΈη! π"));
283
284 let hash = ContentHash::compute(&bytes1);
285 assert_eq!(hash.as_str().len(), 64);
286 }
287}