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 let canonical_val = canonicalize_json_value(val);
73 serde_json::to_vec(&canonical_val).unwrap_or_default()
74}
75
76pub fn serialize_canonical_payload(payload: &MCardPayload) -> Vec<u8> {
78 if let Ok(val) = serde_json::to_value(payload) {
79 to_canonical_json_bytes(&val)
80 } else {
81 serde_json::to_vec(payload).unwrap_or_default()
82 }
83}
84
85pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
87 let bytes = serialize_canonical_payload(payload);
88 ContentHash::compute(&bytes)
89}
90
91impl MCard {
92 pub fn new(uri: impl Into<String>, payload: MCardPayload, author: AgentDid, sequence: u64) -> Self {
94 let hash = compute_canonical_hash(&payload);
95 Self {
96 uri: uri.into(),
97 hash,
98 payload,
99 metadata: HashMap::new(),
100 author,
101 sequence,
102 }
103 }
104
105 pub fn with_metadata(
107 uri: impl Into<String>,
108 payload: MCardPayload,
109 metadata: HashMap<String, serde_json::Value>,
110 author: AgentDid,
111 sequence: u64,
112 ) -> Self {
113 let hash = compute_canonical_hash(&payload);
114 Self {
115 uri: uri.into(),
116 hash,
117 payload,
118 metadata,
119 author,
120 sequence,
121 }
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
127pub struct CordisCoeffects {
128 pub required_services: Vec<String>,
130 pub input_schema_uri: Option<String>,
132 pub output_schema_uri: Option<String>,
134 pub required_capabilities: Vec<String>,
136}
137
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct PrimitivePCard {
142 pub mcard: MCard,
143}
144
145impl PrimitivePCard {
146 pub fn new(mcard: MCard) -> Self {
147 Self { mcard }
148 }
149 pub fn evaluate(&self) -> &MCard {
151 &self.mcard
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
158pub struct DynamicPCard {
159 pub id: String,
160 pub code_hash: ContentHash,
162 pub source_uri: String,
164 pub coeffects: CordisCoeffects,
166 pub signature: String,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub enum BailVerdict {
173 Pass,
175 Bail {
177 reason: String,
178 invariant_code: String,
179 context_dump: serde_json::Value,
180 },
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
185pub enum InvariantPhase {
186 Precondition,
188 Postcondition,
190 LoopInvariant,
192}
193
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct BooleanPCard {
197 pub id: String,
198 pub phase: InvariantPhase,
199 pub expression: String,
201 pub guarded_uri_pattern: String,
203 pub coeffects: CordisCoeffects,
205}
206
207impl BooleanPCard {
208 pub fn is_precondition(&self) -> bool {
209 self.phase == InvariantPhase::Precondition
210 }
211 pub fn is_postcondition(&self) -> bool {
212 self.phase == InvariantPhase::Postcondition
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
217#[serde(tag = "pcard_type")]
218pub enum PCardDefinition {
219 Primitive(Box<PrimitivePCard>),
220 Dynamic(DynamicPCard),
221 Boolean(BooleanPCard),
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 #[test]
229 fn test_mcard_blake3_hash_generation() {
230 let author = AgentDid::new("did:clm:agent:tester").unwrap();
231 let payload = MCardPayload::Text("Hello Cordis Koishi FND".to_string());
232 let mcard = MCard::new("mcard:test/msg1", payload.clone(), author.clone(), 1);
233
234 assert_eq!(mcard.uri, "mcard:test/msg1");
235 assert_eq!(mcard.author, author);
236 assert_eq!(mcard.sequence, 1);
237 assert_eq!(mcard.hash.as_str().len(), 64);
238
239 let mcard2 = MCard::new("mcard:test/msg2", payload, author, 2);
241 assert_eq!(mcard.hash, mcard2.hash);
242 }
243
244 #[test]
245 fn test_primitive_pcard_evaluation() {
246 let author = AgentDid::new("did:clm:agent:tester").unwrap();
247 let payload = MCardPayload::Scalar(serde_json::json!(42));
248 let mcard = MCard::new("mcard:scalar/answer", payload, author, 1);
249 let primitive = PrimitivePCard::new(mcard.clone());
250
251 assert_eq!(primitive.evaluate(), &mcard);
252 }
253
254 #[test]
255 fn test_canonical_json_preimage_univalence() {
256 let v1 = serde_json::json!({"z": 1, "a": 2, "m": {"y": 3, "b": 4}});
257 let v2 = serde_json::json!({"a": 2, "m": {"b": 4, "y": 3}, "z": 1});
258 let bytes1 = to_canonical_json_bytes(&v1);
259 let bytes2 = to_canonical_json_bytes(&v2);
260 assert_eq!(bytes1, bytes2);
261 assert_eq!(std::str::from_utf8(&bytes1).unwrap(), "{\"a\":2,\"m\":{\"b\":4,\"y\":3},\"z\":1}");
262
263 let v_unicode = serde_json::json!({"greeting": "Hello, δΈη! π"});
264 let bytes_u = to_canonical_json_bytes(&v_unicode);
265 let str_u = std::str::from_utf8(&bytes_u).unwrap();
266 assert!(!str_u.contains("\\u"));
267 assert!(str_u.contains("Hello, δΈη! π"));
268
269 let hash = ContentHash::compute(&bytes1);
270 assert_eq!(hash.as_str().len(), 64);
271 }
272}