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, Deserialize)]
37pub struct MCard {
38 pub uri: String,
40 pub hash: ContentHash,
42 pub payload: MCardPayload,
44 pub metadata: HashMap<String, serde_json::Value>,
46 pub author: AgentDid,
48 pub sequence: u64,
50}
51
52pub fn canonicalize_json_value(val: &serde_json::Value) -> serde_json::Value {
54 match val {
55 serde_json::Value::Object(map) => {
56 let mut btree = std::collections::BTreeMap::new();
57 for (k, v) in map {
58 btree.insert(k.clone(), canonicalize_json_value(v));
59 }
60 serde_json::to_value(&btree).unwrap_or_else(|_| val.clone())
61 }
62 serde_json::Value::Array(arr) => {
63 let canon_arr: Vec<serde_json::Value> = arr.iter().map(canonicalize_json_value).collect();
64 serde_json::Value::Array(canon_arr)
65 }
66 _ => val.clone(),
67 }
68}
69
70pub fn to_canonical_json_bytes(val: &serde_json::Value) -> Vec<u8> {
72 crate::layer0::codec::canonical_json(val)
75 .map(|s| s.into_bytes())
76 .unwrap_or_default()
77}
78
79pub fn serialize_canonical_payload(payload: &MCardPayload) -> Vec<u8> {
81 if let Ok(val) = serde_json::to_value(payload) {
82 to_canonical_json_bytes(&val)
83 } else {
84 serde_json::to_vec(payload).unwrap_or_default()
85 }
86}
87
88pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
90 let bytes = serialize_canonical_payload(payload);
91 ContentHash::compute(&bytes)
92}
93
94impl MCard {
95 pub fn new(uri: impl Into<String>, payload: MCardPayload, author: AgentDid, sequence: u64) -> Self {
97 let hash = compute_canonical_hash(&payload);
98 Self {
99 uri: uri.into(),
100 hash,
101 payload,
102 metadata: HashMap::new(),
103 author,
104 sequence,
105 }
106 }
107
108 pub fn with_metadata(
110 uri: impl Into<String>,
111 payload: MCardPayload,
112 metadata: HashMap<String, serde_json::Value>,
113 author: AgentDid,
114 sequence: u64,
115 ) -> Self {
116 let hash = compute_canonical_hash(&payload);
117 Self {
118 uri: uri.into(),
119 hash,
120 payload,
121 metadata,
122 author,
123 sequence,
124 }
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
130pub struct CordisCoeffects {
131 pub required_services: Vec<String>,
133 pub input_schema_uri: Option<String>,
135 pub output_schema_uri: Option<String>,
137 pub required_capabilities: Vec<String>,
139}
140
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144pub struct PrimitivePCard {
145 pub mcard: MCard,
146}
147
148impl PrimitivePCard {
149 pub fn new(mcard: MCard) -> Self {
150 Self { mcard }
151 }
152 pub fn evaluate(&self) -> &MCard {
154 &self.mcard
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161pub struct DynamicPCard {
162 pub id: String,
163 pub code_hash: ContentHash,
165 pub source_uri: String,
167 pub coeffects: CordisCoeffects,
169 pub signature: String,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub enum BailVerdict {
176 Pass,
178 Bail {
180 reason: String,
181 invariant_code: String,
182 context_dump: serde_json::Value,
183 },
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
188pub enum InvariantPhase {
189 Precondition,
191 Postcondition,
193 LoopInvariant,
195}
196
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct BooleanPCard {
200 pub id: String,
201 pub phase: InvariantPhase,
202 pub expression: String,
204 pub guarded_uri_pattern: String,
206 pub coeffects: CordisCoeffects,
208}
209
210impl BooleanPCard {
211 pub fn is_precondition(&self) -> bool {
212 self.phase == InvariantPhase::Precondition
213 }
214 pub fn is_postcondition(&self) -> bool {
215 self.phase == InvariantPhase::Postcondition
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
220#[serde(tag = "pcard_type")]
221pub enum PCardDefinition {
222 Primitive(Box<PrimitivePCard>),
223 Dynamic(DynamicPCard),
224 Boolean(BooleanPCard),
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 #[test]
232 fn test_mcard_blake3_hash_generation() {
233 let author = AgentDid::new("did:clm:agent:tester").unwrap();
234 let payload = MCardPayload::Text("Hello Cordis Koishi FND".to_string());
235 let mcard = MCard::new("mcard:test/msg1", payload.clone(), author.clone(), 1);
236
237 assert_eq!(mcard.uri, "mcard:test/msg1");
238 assert_eq!(mcard.author, author);
239 assert_eq!(mcard.sequence, 1);
240 assert_eq!(mcard.hash.as_str().len(), 64);
241
242 let mcard2 = MCard::new("mcard:test/msg2", payload, author, 2);
244 assert_eq!(mcard.hash, mcard2.hash);
245 }
246
247 #[test]
248 fn test_primitive_pcard_evaluation() {
249 let author = AgentDid::new("did:clm:agent:tester").unwrap();
250 let payload = MCardPayload::Scalar(serde_json::json!(42));
251 let mcard = MCard::new("mcard:scalar/answer", payload, author, 1);
252 let primitive = PrimitivePCard::new(mcard.clone());
253
254 assert_eq!(primitive.evaluate(), &mcard);
255 }
256
257 #[test]
258 fn test_canonical_json_preimage_univalence() {
259 let v1 = serde_json::json!({"z": 1, "a": 2, "m": {"y": 3, "b": 4}});
260 let v2 = serde_json::json!({"a": 2, "m": {"b": 4, "y": 3}, "z": 1});
261 let bytes1 = to_canonical_json_bytes(&v1);
262 let bytes2 = to_canonical_json_bytes(&v2);
263 assert_eq!(bytes1, bytes2);
264 assert_eq!(std::str::from_utf8(&bytes1).unwrap(), "{\"a\":2,\"m\":{\"b\":4,\"y\":3},\"z\":1}");
265
266 let v_unicode = serde_json::json!({"greeting": "Hello, δΈη! π"});
267 let bytes_u = to_canonical_json_bytes(&v_unicode);
268 let str_u = std::str::from_utf8(&bytes_u).unwrap();
269 assert!(!str_u.contains("\\u"));
270 assert!(str_u.contains("Hello, δΈη! π"));
271
272 let hash = ContentHash::compute(&bytes1);
273 assert_eq!(hash.as_str().len(), 64);
274 }
275}