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)]
37#[serde(transparent)]
38pub struct MCard(MCardData);
39
40/// Read-only fields of a validated MCard; the owning card cannot be mutated.
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42pub struct MCardData {
43    /// Canonical URI (e.g., "mcard:workspace/config/settings" or "mcard:chat/message/msg_101").
44    pub uri: String,
45    /// Digest of the exact content bytes under the algorithm declared in g_time.
46    pub hash: ContentHash,
47    /// Underlying data payload.
48    pub payload: MCardPayload,
49    /// Immutable metadata attributes.
50    pub metadata: HashMap<String, serde_json::Value>,
51    /// Cryptographic author DID.
52    pub author: AgentDid,
53    /// Monotonic logical sequence or version counter.
54    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
62/// Serialize a serde_json::Value to deterministic canonical JSON bytes.
63pub 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
69/// Serialize payload to deterministic canonical JSON bytes.
70pub 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
78/// Compute deterministic BLAKE3 content hash over canonical JSON preimage.
79pub 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    /// Constructs a new MCard, computing its BLAKE3 hash automatically from its serialized payload.
99    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    /// Constructs an MCard with explicit metadata.
119    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/// Cordis Coeffects: Declared dependencies required by a PCard before execution.
141#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
142pub struct CordisCoeffects {
143    /// Required services in context tree (e.g., ["database", "crypto", "http"]).
144    pub required_services: Vec<String>,
145    /// Expected input schema URI (MCard resting state).
146    pub input_schema_uri: Option<String>,
147    /// Output schema URI guaranteed by successful execution.
148    pub output_schema_uri: Option<String>,
149    /// Authorizing agent DIDs required to activate this step.
150    pub required_capabilities: Vec<String>,
151}
152
153/// Zero-coeffect constant function: 1 -> X
154/// Evaluates instantaneously as an identity morphism without context resolution overhead.
155#[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    /// Evaluates to its underlying resting state.
165    pub fn evaluate(&self) -> &MCard {
166        &self.mcard
167    }
168}
169
170/// Dynamic, effectful computation: A -> B
171/// Declares reactive coeffects (@Inject) and mounts inside a Cordis Fiber.
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub struct DynamicPCard {
174    pub id: String,
175    /// Behavioral executable payload (WASM, Python bytecode, or AST expression).
176    pub code_hash: ContentHash,
177    /// Source URI for human-readable audit trail.
178    pub source_uri: String,
179    /// Declared Cordis coeffects.
180    pub coeffects: CordisCoeffects,
181    /// Pure state transition function signature.
182    pub signature: String,
183}
184
185/// Verdict returned by a Boolean PCard.
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub enum BailVerdict {
188    /// Predicate satisfied: proceed with pipeline.
189    Pass,
190    /// Predicate violated: abort pipeline and trigger LIFO rollback.
191    Bail {
192        reason: String,
193        invariant_code: String,
194        context_dump: serde_json::Value,
195    },
196}
197
198/// Invariant evaluation target.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
200pub enum InvariantPhase {
201    /// Evaluated in Fiber LOADING state before state mutation (P in {P} S {Q}).
202    Precondition,
203    /// Evaluated in Fiber ACTIVE state after state mutation (Q in {P} S {Q}).
204    Postcondition,
205    /// Evaluated continuously during loop iterations.
206    LoopInvariant,
207}
208
209/// Boolean PCard: Specialization of PCard returning Bool (X -> 2).
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct BooleanPCard {
212    pub id: String,
213    pub phase: InvariantPhase,
214    /// Formal invariant predicate logic (CEL or pure AST).
215    pub expression: String,
216    /// Target MCard URI pattern being guarded.
217    pub guarded_uri_pattern: String,
218    /// Coeffects needed to evaluate the predicate.
219    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        // Deterministic content addressing
255        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}