Skip to main content

clm_rust_core/layer0/
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    // Sprint 529: one canonicalizer. Parity with the previous implementation is
73    // pinned by tests/layer0_canonical_parity.rs.
74    crate::layer0::codec::canonical_json(val)
75        .map(|s| s.into_bytes())
76        .unwrap_or_default()
77}
78
79/// Serialize payload to deterministic canonical JSON bytes.
80pub 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
88/// Compute deterministic BLAKE3 content hash over canonical JSON preimage.
89pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
90    let bytes = serialize_canonical_payload(payload);
91    ContentHash::compute(&bytes)
92}
93
94impl MCard {
95    /// Constructs a new MCard, computing its BLAKE3 hash automatically from its serialized payload.
96    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    /// Constructs an MCard with explicit metadata.
109    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/// Cordis Coeffects: Declared dependencies required by a PCard before execution.
129#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
130pub struct CordisCoeffects {
131    /// Required services in context tree (e.g., ["database", "crypto", "http"]).
132    pub required_services: Vec<String>,
133    /// Expected input schema URI (MCard resting state).
134    pub input_schema_uri: Option<String>,
135    /// Output schema URI guaranteed by successful execution.
136    pub output_schema_uri: Option<String>,
137    /// Authorizing agent DIDs required to activate this step.
138    pub required_capabilities: Vec<String>,
139}
140
141/// Zero-coeffect constant function: 1 -> X
142/// Evaluates instantaneously as an identity morphism without context resolution overhead.
143#[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    /// Evaluates to its underlying resting state.
153    pub fn evaluate(&self) -> &MCard {
154        &self.mcard
155    }
156}
157
158/// Dynamic, effectful computation: A -> B
159/// Declares reactive coeffects (@Inject) and mounts inside a Cordis Fiber.
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161pub struct DynamicPCard {
162    pub id: String,
163    /// Behavioral executable payload (WASM, Python bytecode, or AST expression).
164    pub code_hash: ContentHash,
165    /// Source URI for human-readable audit trail.
166    pub source_uri: String,
167    /// Declared Cordis coeffects.
168    pub coeffects: CordisCoeffects,
169    /// Pure state transition function signature.
170    pub signature: String,
171}
172
173/// Verdict returned by a Boolean PCard.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub enum BailVerdict {
176    /// Predicate satisfied: proceed with pipeline.
177    Pass,
178    /// Predicate violated: abort pipeline and trigger LIFO rollback.
179    Bail {
180        reason: String,
181        invariant_code: String,
182        context_dump: serde_json::Value,
183    },
184}
185
186/// Invariant evaluation target.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
188pub enum InvariantPhase {
189    /// Evaluated in Fiber LOADING state before state mutation (P in {P} S {Q}).
190    Precondition,
191    /// Evaluated in Fiber ACTIVE state after state mutation (Q in {P} S {Q}).
192    Postcondition,
193    /// Evaluated continuously during loop iterations.
194    LoopInvariant,
195}
196
197/// Boolean PCard: Specialization of PCard returning Bool (X -> 2).
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct BooleanPCard {
200    pub id: String,
201    pub phase: InvariantPhase,
202    /// Formal invariant predicate logic (CEL or pure AST).
203    pub expression: String,
204    /// Target MCard URI pattern being guarded.
205    pub guarded_uri_pattern: String,
206    /// Coeffects needed to evaluate the predicate.
207    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        // Deterministic content addressing
243        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}