Skip to main content

clm_rust_core/
domain.rs

1//! Unified Spatiotemporal FND Domain Models (Sprint 190).
2//!
3//! Enforces:
4//! 1. MCard as the Single Root Type & Spatial Carrier (s ∈ S)
5//! 2. Function-Number Duality (FND): PrimitivePCard (1 -> X) vs DynamicPCard (A -> B)
6//! 3. BooleanPCard as Cordis Bail Predicate (X -> 2)
7//! 4. Reactive Coeffects (@Inject) and Content-Addressed BLAKE3 Hashes
8
9use crate::satori::element::SatoriMessage;
10pub use crate::types::{AgentDid, ContentHash, Handle};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14/// Content payload carried by an MCard resting state.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[serde(tag = "kind", content = "value")]
17pub enum MCardPayload {
18    /// Pure scalar or numeric primitive (Number in FND).
19    Scalar(serde_json::Value),
20    /// UTF-8 formatted text or markdown.
21    Text(String),
22    /// Normalized Satori message speech act from Koishi conversational substrate.
23    Satori(SatoriMessage),
24    /// Raw binary content addressed in SQLite CAS.
25    Binary {
26        mime_type: String,
27        data: Vec<u8>,
28    },
29    /// Structured JSON payload.
30    Structured(serde_json::Value),
31    /// Serialized executable PCard definition (Function in FND).
32    Executable(Box<PCardDefinition>),
33}
34
35/// The universal immutable data entity and file system primitive.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct MCard {
38    /// Canonical URI (e.g., "mcard:workspace/config/settings" or "mcard:chat/message/msg_101").
39    pub uri: String,
40    /// Cryptographic BLAKE3 hash of canonical serialized payload.
41    pub hash: ContentHash,
42    /// Underlying data payload.
43    pub payload: MCardPayload,
44    /// Immutable metadata attributes.
45    pub metadata: HashMap<String, serde_json::Value>,
46    /// Cryptographic author DID.
47    pub author: AgentDid,
48    /// Monotonic logical sequence or version counter.
49    pub sequence: u64,
50}
51
52/// Deterministic canonical JSON serialization helper that sorts object keys recursively.
53pub 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
70/// Serialize a serde_json::Value to deterministic canonical JSON bytes.
71pub 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
76/// Serialize payload to deterministic canonical JSON bytes.
77pub 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
85/// Compute deterministic BLAKE3 content hash over canonical JSON preimage.
86pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
87    let bytes = serialize_canonical_payload(payload);
88    ContentHash::compute(&bytes)
89}
90
91impl MCard {
92    /// Constructs a new MCard, computing its BLAKE3 hash automatically from its serialized payload.
93    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    /// Constructs an MCard with explicit metadata.
106    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/// Cordis Coeffects: Declared dependencies required by a PCard before execution.
126#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
127pub struct CordisCoeffects {
128    /// Required services in context tree (e.g., ["database", "crypto", "http"]).
129    pub required_services: Vec<String>,
130    /// Expected input schema URI (MCard resting state).
131    pub input_schema_uri: Option<String>,
132    /// Output schema URI guaranteed by successful execution.
133    pub output_schema_uri: Option<String>,
134    /// Authorizing agent DIDs required to activate this step.
135    pub required_capabilities: Vec<String>,
136}
137
138/// Zero-coeffect constant function: 1 -> X
139/// Evaluates instantaneously as an identity morphism without context resolution overhead.
140#[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    /// Evaluates to its underlying resting state.
150    pub fn evaluate(&self) -> &MCard {
151        &self.mcard
152    }
153}
154
155/// Dynamic, effectful computation: A -> B
156/// Declares reactive coeffects (@Inject) and mounts inside a Cordis Fiber.
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
158pub struct DynamicPCard {
159    pub id: String,
160    /// Behavioral executable payload (WASM, Python bytecode, or AST expression).
161    pub code_hash: ContentHash,
162    /// Source URI for human-readable audit trail.
163    pub source_uri: String,
164    /// Declared Cordis coeffects.
165    pub coeffects: CordisCoeffects,
166    /// Pure state transition function signature.
167    pub signature: String,
168}
169
170/// Verdict returned by a Boolean PCard.
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub enum BailVerdict {
173    /// Predicate satisfied: proceed with pipeline.
174    Pass,
175    /// Predicate violated: abort pipeline and trigger LIFO rollback.
176    Bail {
177        reason: String,
178        invariant_code: String,
179        context_dump: serde_json::Value,
180    },
181}
182
183/// Invariant evaluation target.
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
185pub enum InvariantPhase {
186    /// Evaluated in Fiber LOADING state before state mutation (P in {P} S {Q}).
187    Precondition,
188    /// Evaluated in Fiber ACTIVE state after state mutation (Q in {P} S {Q}).
189    Postcondition,
190    /// Evaluated continuously during loop iterations.
191    LoopInvariant,
192}
193
194/// Boolean PCard: Specialization of PCard returning Bool (X -> 2).
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct BooleanPCard {
197    pub id: String,
198    pub phase: InvariantPhase,
199    /// Formal invariant predicate logic (CEL or pure AST).
200    pub expression: String,
201    /// Target MCard URI pattern being guarded.
202    pub guarded_uri_pattern: String,
203    /// Coeffects needed to evaluate the predicate.
204    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        // Deterministic content addressing
240        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}