Skip to main content

acl_core/
cl.rs

1//! Content Language (CL) — spec §6.2.
2//!
3//! The shared grammar agents use *inside* envelope bodies: facts about the
4//! world, typed actions, queries, and commitments. This is what makes ACL a
5//! communication language (agent-agnostic semantics) rather than only a
6//! transport protocol.
7//!
8//! Design notes:
9//! - `Fact.args` is a BTreeMap so serialization is canonical (identical
10//!   bytes regardless of insertion order) — required for stable signatures.
11//! - `well_formed` is the normative grammar matrix (§6.2): which CL ops a
12//!   performative may carry. Receivers SHOULD validate; encoders MUST emit
13//!   well-formed bodies.
14
15use serde::{Deserialize, Serialize};
16use std::collections::BTreeMap;
17
18/// Typed content value (§27): the CL's own type system. Wire-compatible
19/// with plain msgpack/JSON values (Str→string, Int→integer, …) so existing
20/// encoders keep working — but Rust-level code now knows the TYPE.
21/// `Var` is the exception: it serializes as a single-key map `{"$var":
22/// name}` to stay unambiguous with `Str`.
23#[derive(Debug, Clone, PartialEq)]
24pub enum ClValue {
25    Str(String),
26    Int(i64),
27    Float(f64),
28    Bool(bool),
29    /// §28: reference to a `Bind` binding or a quantified variable.
30    Var(String),
31    List(Vec<ClValue>),
32    Map(BTreeMap<String, ClValue>),
33    Bytes(Vec<u8>),
34    /// §32: value with unit of measure — `{"$measured": {"value": v,
35    /// "unit": "ms"}}`. Prevents the classic inter-agent unit confusion.
36    Measured { value: Box<ClValue>, unit: String },
37}
38
39impl ClValue {
40    pub fn type_name(&self) -> &'static str {
41        match self {
42            ClValue::Str(_) => "string",
43            ClValue::Int(_) => "int",
44            ClValue::Float(_) => "float",
45            ClValue::Bool(_) => "bool",
46            ClValue::Var(_) => "var",
47            ClValue::List(_) => "list",
48            ClValue::Map(_) => "map",
49            ClValue::Bytes(_) => "bytes",
50            ClValue::Measured { .. } => "measured",
51        }
52    }
53
54    pub fn as_str(&self) -> Option<&str> {
55        match self { ClValue::Str(s) => Some(s), _ => None }
56    }
57
58    pub fn as_int(&self) -> Option<i64> {
59        match self { ClValue::Int(i) => Some(*i), _ => None }
60    }
61
62    /// Strict conversion from untyped JSON: int rejects floats, float
63    /// accepts any number, objects/arrays recurse. `null` is rejected —
64    /// CL values must be typed.
65    pub fn from_json(v: serde_json::Value) -> Result<Self, String> {
66        Ok(match v {
67            serde_json::Value::String(s) => ClValue::Str(s),
68            serde_json::Value::Number(n) => {
69                if let Some(i) = n.as_i64() {
70                    ClValue::Int(i)
71                } else {
72                    ClValue::Float(n.as_f64().ok_or("unrepresentable number")?)
73                }
74            }
75            serde_json::Value::Bool(b) => ClValue::Bool(b),
76            serde_json::Value::Array(a) => {
77                ClValue::List(a.into_iter().map(ClValue::from_json).collect::<Result<Vec<_>, _>>()?)
78            }
79            serde_json::Value::Object(o) => ClValue::Map(
80                o.into_iter()
81                    .map(|(k, v)| ClValue::from_json(v).map(|cv| (k, cv)))
82                    .collect::<Result<BTreeMap<_, _>, _>>()?,
83            ),
84            serde_json::Value::Null => return Err("null is not a CL value".into()),
85        })
86    }
87}
88
89impl Serialize for ClValue {
90    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
91        match self {
92            ClValue::Str(s) => serializer.serialize_str(s),
93            ClValue::Int(i) => serializer.serialize_i64(*i),
94            ClValue::Float(f) => serializer.serialize_f64(*f),
95            ClValue::Bool(b) => serializer.serialize_bool(*b),
96            ClValue::Var(name) => {
97                use serde::ser::SerializeMap;
98                let mut m = serializer.serialize_map(Some(1))?;
99                m.serialize_entry("$var", name)?;
100                m.end()
101            }
102            ClValue::List(l) => serializer.serialize_some(l),
103            ClValue::Map(m) => {
104                use serde::ser::SerializeMap;
105                let mut sm = serializer.serialize_map(Some(m.len()))?;
106                for (k, v) in m {
107                    sm.serialize_entry(k, v)?;
108                }
109                sm.end()
110            }
111            ClValue::Bytes(b) => serializer.serialize_bytes(b),
112            ClValue::Measured { value, unit } => {
113                use serde::ser::SerializeMap;
114                let mut m = serializer.serialize_map(Some(1))?;
115                m.serialize_entry(
116                    "$measured",
117                    &serde_json::json!({"value": value, "unit": unit}),
118                )?;
119                m.end()
120            }
121        }
122    }
123}
124
125impl<'de> Deserialize<'de> for ClValue {
126    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
127        let v = serde_json::Value::deserialize(d)?;
128        // map with single key "$var" → Var (checked before Map)
129        if let serde_json::Value::Object(ref o) = v {
130            if o.len() == 1 {
131                if let Some(name) = o.get("$var").and_then(|x| x.as_str()) {
132                    return Ok(ClValue::Var(name.to_string()));
133                }
134                if let Some(m) = o.get("$measured").and_then(|x| x.as_object()) {
135                    let raw_value = m.get("value").cloned().unwrap_or(serde_json::Value::Null);
136                    let value = ClValue::from_json(raw_value)
137                        .map_err(serde::de::Error::custom)?;
138                    let unit = m
139                        .get("unit")
140                        .and_then(|x| x.as_str())
141                        .ok_or_else(|| serde::de::Error::custom("missing unit"))?
142                        .to_string();
143                    return Ok(ClValue::Measured { value: Box::new(value), unit });
144                }
145            }
146        }
147        ClValue::from_json(v).map_err(serde::de::Error::custom)
148    }
149}
150
151/// Status of a commitment (§6.2 lifecycle).
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
153#[serde(rename_all = "lowercase")]
154pub enum CommitmentStatus {
155    Proposed,
156    Active,
157    Fulfilled,
158    Breached,
159    Cancelled,
160}
161
162impl CommitmentStatus {
163    /// Legal transitions of the commitment lifecycle.
164    pub fn can_transition(&self, to: CommitmentStatus) -> bool {
165        use CommitmentStatus::*;
166        matches!(
167            (self, to),
168            (Proposed, Active)
169                | (Proposed, Cancelled)
170                | (Active, Fulfilled)
171                | (Active, Breached)
172                | (Active, Cancelled)
173        )
174    }
175}
176
177/// Epistemic modality of a fact (spec §6.4): how the sender holds it.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
179#[serde(rename_all = "lowercase")]
180pub enum Epistemic {
181    /// Sender asserts this as its own observation/authority.
182    Asserted,
183    /// Sender believes it (second-hand, not verified).
184    Believed,
185    /// Sender verified it directly.
186    Known,
187}
188
189/// An action expression: `name(params) -> result_schema?`.
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub struct ClAction {
192    pub name: String,
193    #[serde(default)]
194    pub params: serde_json::Value,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub result_schema: Option<serde_json::Value>,
197    /// §28: params deliberately left unfilled — the action is a template
198    /// awaiting completion. Schema validation skips these.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub partial: Option<Vec<String>>,
201}
202
203/// One content-language expression.
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205#[serde(tag = "op")]
206pub enum ClExpr {
207    /// Assert that `predicate(args)` holds (or not, `truth: false`).
208    #[serde(rename = "fact")]
209    Fact {
210        predicate: String,
211        #[serde(default)]
212        args: BTreeMap<String, ClValue>,
213        #[serde(default = "default_true")]
214        truth: bool,
215        /// §29: this fact was derived from the referenced message; its
216        /// validity is bounded by the source's validity.
217        #[serde(default, skip_serializing_if = "Option::is_none")]
218        derived_from: Option<String>,
219        /// §32: belief revision — this fact SUPERSEDES the fact asserted
220        /// in the referenced message (retraction with traceability).
221        #[serde(default, skip_serializing_if = "Option::is_none")]
222        supersedes: Option<String>,
223        /// §6.4 epistemic modality (default: Asserted).
224        #[serde(default, skip_serializing_if = "Option::is_none")]
225        modality: Option<Epistemic>,
226        /// §6.4 provenance chain: AIDs of who asserted/forwarded, oldest first.
227        #[serde(default, skip_serializing_if = "Option::is_none")]
228        provenance: Option<Vec<String>>,
229        /// §6.4 confidence in [0,1].
230        #[serde(default, skip_serializing_if = "Option::is_none")]
231        confidence: Option<f32>,
232        /// §6.4 temporal validity: fact expires at this unix ms.
233        #[serde(default, skip_serializing_if = "Option::is_none")]
234        valid_until_ms: Option<i64>,
235    },
236    /// §6.3 conjunction — all leaves must hold.
237    #[serde(rename = "and")]
238    And { exprs: Vec<ClExpr> },
239    /// §6.3 disjunction — at least one leaf must hold.
240    #[serde(rename = "or")]
241    Or { exprs: Vec<ClExpr> },
242    /// §6.3 negation (fact leaves only).
243    #[serde(rename = "not")]
244    Not { expr: Box<ClExpr> },
245    /// §6.3 reference to an expression produced in another message.
246    #[serde(rename = "ref")]
247    RefExpr { msg_id: String },
248    /// §28: bind a name to an expression's value, usable in `body` via
249    /// `$bind:<name>` references. `expr` must be a fact/action leaf.
250    #[serde(rename = "bind")]
251    Bind { name: String, expr: Box<ClExpr>, body: Box<ClExpr> },
252    /// §28: universal quantification — for every element of `over`'s
253    /// result (a query), `such_that` holds with the element bound to `var`.
254    #[serde(rename = "for_all")]
255    ForAll { var: String, over: Box<ClExpr>, such_that: Box<ClExpr> },
256    /// §28: existential quantification.
257    #[serde(rename = "exists")]
258    Exists { var: String, over: Box<ClExpr>, such_that: Box<ClExpr> },
259    /// §28: metanível — the sender asserts that `agent` holds `fact`.
260    #[serde(rename = "believes")]
261    Believes { agent: String, fact: Box<ClExpr> },
262    /// §32: conditional commitment — activates only when `condition` holds
263    /// (as observed by the debtor). Condition is a fact composition.
264    #[serde(rename = "conditional_commitment")]
265    ConditionalCommitment {
266        debtor: String,
267        creditor: String,
268        condition: Box<ClExpr>,
269        act: ClAction,
270        deadline_ms: Option<i64>,
271        status: CommitmentStatus,
272    },
273    /// §32: evaluation policy — declares the criteria used to rank bids
274    /// (carried under propose/accept in contract-net, §21).
275    #[serde(rename = "prefer")]
276    Prefer { criteria: Vec<ClExpr> },
277    /// §29: extend an active commitment's deadline (carried under request).
278    #[serde(rename = "renew")]
279    Renew { target_msg_id: String, new_deadline_ms: i64 },
280    /// Express an action to be performed.
281    #[serde(rename = "action")]
282    Action {
283        name: String,
284        #[serde(default)]
285        params: serde_json::Value,
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        result_schema: Option<serde_json::Value>,
288    },
289    /// Ask whether `predicate(args)` holds; the reply is a `Fact`.
290    #[serde(rename = "query")]
291    Query {
292        predicate: String,
293        #[serde(default)]
294        args: serde_json::Value,
295        /// §29: the asker accepts answers valid until this unix ms.
296        #[serde(default, skip_serializing_if = "Option::is_none")]
297        valid_until_ms: Option<i64>,
298    },
299    /// Debtor commits to creditor to perform `act` by `deadline_ms`.
300    #[serde(rename = "commitment")]
301    Commitment {
302        debtor: String,
303        creditor: String,
304        act: ClAction,
305        #[serde(default, skip_serializing_if = "Option::is_none")]
306        deadline_ms: Option<i64>,
307        status: CommitmentStatus,
308    },
309}
310
311fn default_true() -> bool {
312    true
313}
314
315impl ClExpr {
316    pub fn fact(predicate: &str, args: serde_json::Value) -> Self {
317        ClExpr::Fact {
318            predicate: predicate.into(),
319            args: json_object_to_btree(args),
320            truth: true,
321            derived_from: None,
322            supersedes: None,
323            modality: None,
324            provenance: None,
325            confidence: None,
326            valid_until_ms: None,
327        }
328    }
329
330    pub fn fact_false(predicate: &str, args: serde_json::Value) -> Self {
331        ClExpr::Fact {
332            predicate: predicate.into(),
333            args: json_object_to_btree(args),
334            truth: false,
335            derived_from: None,
336            supersedes: None,
337            modality: None,
338            provenance: None,
339            confidence: None,
340            valid_until_ms: None,
341        }
342    }
343
344    pub fn action(name: &str, params: serde_json::Value) -> Self {
345        ClExpr::Action {
346            name: name.into(),
347            params,
348            result_schema: None,
349        }
350    }
351
352    pub fn and(exprs: Vec<ClExpr>) -> Self {
353        ClExpr::And { exprs }
354    }
355
356    pub fn not(expr: ClExpr) -> Self {
357        ClExpr::Not { expr: Box::new(expr) }
358    }
359
360    pub fn ref_to(msg_id: &str) -> Self {
361        ClExpr::RefExpr { msg_id: msg_id.into() }
362    }
363
364    pub fn bind(name: &str, expr: ClExpr, body: ClExpr) -> Self {
365        ClExpr::Bind { name: name.into(), expr: Box::new(expr), body: Box::new(body) }
366    }
367
368    pub fn for_all(var: &str, over: ClExpr, such_that: ClExpr) -> Self {
369        ClExpr::ForAll { var: var.into(), over: Box::new(over), such_that: Box::new(such_that) }
370    }
371
372    pub fn exists(var: &str, over: ClExpr, such_that: ClExpr) -> Self {
373        ClExpr::Exists { var: var.into(), over: Box::new(over), such_that: Box::new(such_that) }
374    }
375
376    pub fn believes(agent: &str, fact: ClExpr) -> Self {
377        ClExpr::Believes { agent: agent.into(), fact: Box::new(fact) }
378    }
379
380    pub fn renew(target_msg_id: &str, new_deadline_ms: i64) -> Self {
381        ClExpr::Renew { target_msg_id: target_msg_id.into(), new_deadline_ms }
382    }
383
384    pub fn query(predicate: &str, args: serde_json::Value) -> Self {
385        ClExpr::Query {
386            predicate: predicate.into(),
387            args,
388            valid_until_ms: None,
389        }
390    }
391
392    pub fn commitment(
393        debtor: &str,
394        creditor: &str,
395        act: ClAction,
396        deadline_ms: Option<i64>,
397        status: CommitmentStatus,
398    ) -> Self {
399        ClExpr::Commitment {
400            debtor: debtor.into(),
401            creditor: creditor.into(),
402            act,
403            deadline_ms,
404            status,
405        }
406    }
407
408    /// §32: conditional commitment — activates only when `condition` holds.
409    pub fn conditional_commitment(
410        debtor: &str,
411        creditor: &str,
412        condition: ClExpr,
413        act: ClAction,
414        deadline_ms: Option<i64>,
415        status: CommitmentStatus,
416    ) -> Self {
417        ClExpr::ConditionalCommitment {
418            debtor: debtor.into(),
419            creditor: creditor.into(),
420            condition: Box::new(condition),
421            act,
422            deadline_ms,
423            status,
424        }
425    }
426
427    /// §32: preference policy (CNP evaluation criteria).
428    pub fn prefer(criteria: Vec<ClExpr>) -> Self {
429        ClExpr::Prefer { criteria }
430    }
431}
432
433fn json_object_to_btree(v: serde_json::Value) -> BTreeMap<String, ClValue> {
434    v.as_object()
435        .map(|m| {
436            m.iter()
437                .map(|(k, val)| ClValue::from_json(val.clone()).map(|cv| (k.clone(), cv)))
438                .collect::<Result<BTreeMap<_, _>, _>>()
439                .unwrap_or_default()
440        })
441        .unwrap_or_default()
442}
443
444use crate::Performative;
445
446/// Normative grammar (spec §6.2): which CL ops each performative may carry.
447/// Returns Err with a human-readable reason on ill-formed combinations.
448pub fn well_formed(performative: Performative, exprs: &[ClExpr]) -> Result<(), String> {
449    if exprs.is_empty() {
450        return Err("Cl body with zero expressions".into());
451    }
452    let allowed = match performative {
453        Performative::Inform => "fact",
454        Performative::Request => "action",
455        Performative::Query => "query",
456        Performative::Propose => "commitment",
457        Performative::Accept => "commitment",
458        Performative::Delegate => "action",
459        other => {
460            return Err(format!(
461                "performative {other:?} does not carry a Cl body (has its own variant)"
462            ))
463        }
464    };
465    let mut bound = Vec::new();
466    for e in exprs {
467        check_leaf(performative, allowed, e, &mut bound)?;
468    }
469    Ok(())
470}
471
472/// Recursively validate one expression (§6.3/§6.5): composition composes
473/// the constraint down to leaves; `not` wraps fact leaves; `ref` is
474/// neutral; `bind` extends the lexical scope; quantifiers bind their var.
475fn check_leaf(
476    performative: Performative,
477    allowed: &str,
478    e: &ClExpr,
479    bound: &mut Vec<String>,
480) -> Result<(), String> {
481    match e {
482        ClExpr::And { exprs } | ClExpr::Or { exprs } => {
483            if exprs.is_empty() {
484                return Err("empty composition".into());
485            }
486            for sub in exprs {
487                check_leaf(performative, allowed, sub, bound)?;
488            }
489            Ok(())
490        }
491        ClExpr::Not { expr } => match expr.as_ref() {
492            ClExpr::Fact { .. } => Ok(()),
493            other => Err(format!("'not' may only wrap a fact, got {other:?}")),
494        },
495        // (scope flows through all composition arms below via check_leaf calls)
496        ClExpr::RefExpr { msg_id } => {
497            if msg_id.is_empty() {
498                return Err("ref with empty msg_id".into());
499            }
500            // $bind:<name> references must have an enclosing binding (§28)
501            if let Some(name) = msg_id.strip_prefix("$bind:") {
502                if !bound.iter().any(|b| b == name) {
503                    return Err(format!("$bind:{name} references an unbound name"));
504                }
505            }
506            Ok(())
507        }
508        ClExpr::Bind { name, expr, body } => {
509            // §28: the bound expression must be a leaf (fact or action)
510            match expr.as_ref() {
511                ClExpr::Fact { .. } | ClExpr::Action { .. } => {}
512                other => return Err(format!("bind '{name}' must bind a fact or action leaf, got {other:?}")),
513            }
514            check_leaf(performative, allowed, expr, bound)?;
515            bound.push(name.clone());
516            let r = check_leaf(performative, allowed, body, bound);
517            bound.pop();
518            r
519        }
520        ClExpr::ForAll { var, over, such_that }
521        | ClExpr::Exists { var, over, such_that } => {
522            // §28: the domain must be a query (its result is the collection)
523            if !matches!(over.as_ref(), ClExpr::Query { .. }) {
524                return Err(format!("quantifier 'over' must be a query, got {over:?}"));
525            }
526            check_leaf(performative, "query", over, bound)?;
527            bound.push(var.clone());
528            let r = check_leaf(performative, allowed, such_that, bound);
529            bound.pop();
530            r
531        }
532        ClExpr::Believes { agent, fact } => {
533            // §28: metanível — only under inform; the inner fact is validated
534            if performative != Performative::Inform {
535                return Err(format!("believes is only legal under inform, got {performative:?}"));
536            }
537            if agent.is_empty() {
538                return Err("believes with empty agent".into());
539            }
540            check_leaf(performative, allowed, fact, bound)
541        }
542        ClExpr::Renew { target_msg_id, new_deadline_ms } => {
543            // §29: only under request; target must be set, deadline in future
544            if performative != Performative::Request {
545                return Err(format!("renew is only legal under request, got {performative:?}"));
546            }
547            if target_msg_id.is_empty() {
548                return Err("renew with empty target".into());
549            }
550            if *new_deadline_ms <= 0 {
551                return Err("renew deadline must be positive".into());
552            }
553            Ok(())
554        }
555        ClExpr::Fact { .. } => {
556            if allowed != "fact" {
557                return Err(format!(
558                    "performative {performative:?} carries CL op 'fact' but allows only '{allowed}'"
559                ));
560            }
561            Ok(())
562        }
563        ClExpr::Action { .. } => {
564            if allowed != "action" {
565                return Err(format!(
566                    "performative {performative:?} carries CL op 'action' but allows only '{allowed}'"
567                ));
568            }
569            Ok(())
570        }
571        ClExpr::Query { .. } => {
572            if allowed != "query" {
573                return Err(format!(
574                    "performative {performative:?} carries CL op 'query' but allows only '{allowed}'"
575                ));
576            }
577            Ok(())
578        }
579        ClExpr::Commitment { status, .. } => {
580            let ok = match performative {
581                Performative::Propose => *status == CommitmentStatus::Proposed,
582                Performative::Accept => *status == CommitmentStatus::Active,
583                _ => false,
584            };
585            if !ok {
586                return Err(format!(
587                    "performative {performative:?} cannot carry commitment with status {status:?}"
588                ));
589            }
590            Ok(())
591        }
592        ClExpr::ConditionalCommitment { condition, status, .. } => {
593            // §32: the condition is a fact composition — validated with
594            // inform's grammar (facts only), independent of the carrier
595            check_leaf(Performative::Inform, "fact", condition, bound)?;
596            let ok = match performative {
597                Performative::Propose => *status == CommitmentStatus::Proposed,
598                Performative::Accept => *status == CommitmentStatus::Active,
599                _ => false,
600            };
601            if !ok {
602                return Err(format!(
603                    "performative {performative:?} cannot carry conditional commitment with status {status:?}"
604                ));
605            }
606            Ok(())
607        }
608        ClExpr::Prefer { criteria } => {
609            // §32: evaluation policy — legal under propose (bid policy) and
610            // accept (award policy); criteria are fact compositions
611            if performative != Performative::Propose && performative != Performative::Accept {
612                return Err(format!("prefer is only legal under propose/accept, got {performative:?}"));
613            }
614            if criteria.is_empty() {
615                return Err("prefer with zero criteria".into());
616            }
617            for c in criteria {
618                check_leaf(Performative::Inform, "fact", c, bound)?;
619            }
620            Ok(())
621        }
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628    use crate::{Aid, Body, Envelope};
629
630    fn env(perf: Performative, body: Body) -> Envelope {
631        Envelope::new(Aid::local(1, "t"), Aid::new("did:x:y"), perf, body)
632    }
633
634    fn cl_body(exprs: Vec<ClExpr>) -> Body {
635        Body::Cl { expressions: exprs }
636    }
637
638    #[test]
639    fn roundtrip_all_ops() {
640        let exprs = vec![
641            ClExpr::fact("file_exists", serde_json::json!({"path": "/tmp/x"})),
642            ClExpr::fact_false("agent_healthy", serde_json::json!({"agent": "argus"})),
643            ClExpr::action("text.reverse", serde_json::json!({"text": "abc"})),
644            ClExpr::query("task_status", serde_json::json!({"msg_id": "abc"})),
645            ClExpr::commitment(
646                "local:1:kenji",
647                "local:1:argus",
648                ClAction {
649                    name: "text.reverse".into(),
650                    params: serde_json::json!({"text": "abc"}),
651                    result_schema: None,
652                    partial: None,
653                },
654                Some(1_700_000_000_000),
655                CommitmentStatus::Proposed,
656            ),
657        ];
658        let env = env(Performative::Inform, cl_body(exprs.clone()));
659        let bytes = env.encode().unwrap();
660        let back = Envelope::decode(&bytes).unwrap();
661        match &back.body {
662            Body::Cl { expressions } => assert_eq!(expressions, &exprs),
663            other => panic!("expected Cl, got {other:?}"),
664        }
665    }
666
667    #[test]
668    fn canonical_serialization_order_independent() {
669        // same fact, different insertion order -> identical bytes
670        let mut e1 = env(Performative::Inform, cl_body(vec![ClExpr::Fact {
671            predicate: "f".into(),
672            args: BTreeMap::from([
673                ("a".into(), ClValue::Int(1)),
674                ("b".into(), ClValue::Int(2)),
675            ]),
676            truth: true,
677            derived_from: None,
678            supersedes: None,
679            modality: None,
680            provenance: None,
681            confidence: None,
682            valid_until_ms: None,
683        }]));
684        let mut e2 = env(Performative::Inform, cl_body(vec![ClExpr::Fact {
685            predicate: "f".into(),
686            args: BTreeMap::from([
687                ("b".into(), ClValue::Int(2)),
688                ("a".into(), ClValue::Int(1)),
689            ]),
690            truth: true,
691            derived_from: None,
692            supersedes: None,
693            modality: None,
694            provenance: None,
695            confidence: None,
696            valid_until_ms: None,
697        }]));
698        // pin msg_id so the only difference under test is arg ordering
699        e1.msg_id = "canonical-test-id-0001".into();
700        e2.msg_id = "canonical-test-id-0001".into();
701        e1.ts = 0;
702        e2.ts = 0;
703        assert_eq!(e1.encode().unwrap(), e2.encode().unwrap());
704    }
705
706    #[test]
707    fn grammar_matrix() {
708        // well-formed combinations
709        assert!(well_formed(Performative::Inform, &[ClExpr::fact("f", serde_json::json!({}))]).is_ok());
710        assert!(well_formed(Performative::Inform, &[ClExpr::fact_false("f", serde_json::json!({}))]).is_ok());
711        assert!(well_formed(Performative::Request, &[ClExpr::action("t.reverse", serde_json::json!({}))]).is_ok());
712        assert!(well_formed(Performative::Query, &[ClExpr::query("f", serde_json::json!({}))]).is_ok());
713        assert!(well_formed(Performative::Delegate, &[ClExpr::action("t", serde_json::json!({}))]).is_ok());
714        assert!(well_formed(
715            Performative::Propose,
716            &[ClExpr::commitment("a", "b", ClAction { name: "t".into(), params: serde_json::json!({}), result_schema: None, partial: None }, None, CommitmentStatus::Proposed)]
717        ).is_ok());
718        assert!(well_formed(
719            Performative::Accept,
720            &[ClExpr::commitment("a", "b", ClAction { name: "t".into(), params: serde_json::json!({}), result_schema: None, partial: None }, None, CommitmentStatus::Active)]
721        ).is_ok());
722
723        // ill-formed combinations
724        assert!(well_formed(Performative::Inform, &[ClExpr::action("t", serde_json::json!({}))]).is_err());
725        assert!(well_formed(Performative::Request, &[ClExpr::fact("f", serde_json::json!({}))]).is_err());
726        assert!(well_formed(Performative::Query, &[ClExpr::action("t", serde_json::json!({}))]).is_err());
727        // commitment status must match performative
728        assert!(well_formed(
729            Performative::Propose,
730            &[ClExpr::commitment("a", "b", ClAction { name: "t".into(), params: serde_json::json!({}), result_schema: None, partial: None }, None, CommitmentStatus::Active)]
731        ).is_err());
732        // performatives with their own body variants never carry CL
733        assert!(well_formed(Performative::Progress, &[ClExpr::fact("f", serde_json::json!({}))]).is_err());
734        // empty CL body
735        assert!(well_formed(Performative::Inform, &[]).is_err());
736    }
737
738    #[test]
739    fn commitment_lifecycle() {
740        use CommitmentStatus::*;
741        assert!(Proposed.can_transition(Active));
742        assert!(Proposed.can_transition(Cancelled));
743        assert!(Active.can_transition(Fulfilled));
744        assert!(Active.can_transition(Breached));
745        assert!(Active.can_transition(Cancelled));
746        // illegal
747        assert!(!Proposed.can_transition(Fulfilled));
748        assert!(!Proposed.can_transition(Breached));
749        assert!(!Fulfilled.can_transition(Active));
750        assert!(!Breached.can_transition(Active));
751        assert!(!Cancelled.can_transition(Active));
752        assert!(!Fulfilled.can_transition(Fulfilled)); // terminal
753    }
754
755    #[test]
756    fn composition_and_epistemic() {
757        use Epistemic::*;
758        // and/or of facts under inform: well-formed
759        assert!(well_formed(
760            Performative::Inform,
761            &[ClExpr::and(vec![
762                ClExpr::fact("a", serde_json::json!({})),
763                ClExpr::fact("b", serde_json::json!({})),
764            ])]
765        ).is_ok());
766        // nested composition
767        assert!(well_formed(
768            Performative::Inform,
769            &[ClExpr::Or { exprs: vec![
770                ClExpr::and(vec![ClExpr::fact("a", serde_json::json!({}))]),
771                ClExpr::not(ClExpr::fact("b", serde_json::json!({}))),
772            ]}]
773        ).is_ok());
774        // composition must still respect the matrix: and(action) under inform
775        assert!(well_formed(
776            Performative::Inform,
777            &[ClExpr::and(vec![ClExpr::action("t", serde_json::json!({}))])]
778        ).is_err());
779        // not() only wraps facts
780        assert!(well_formed(
781            Performative::Inform,
782            &[ClExpr::not(ClExpr::action("t", serde_json::json!({})))]
783        ).is_err());
784        // ref is neutral, even under request... no: ref allowed as leaf
785        assert!(well_formed(
786            Performative::Inform,
787            &[ClExpr::ref_to("msg123"), ClExpr::fact("f", serde_json::json!({}))]
788        ).is_ok());
789        assert!(well_formed(
790            Performative::Inform,
791            &[ClExpr::ref_to("")]
792        ).is_err());
793
794        // epistemic fact roundtrip
795        let f = ClExpr::Fact {
796            predicate: "file_exists".into(),
797            args: BTreeMap::from([("path".into(), ClValue::Str("/tmp/x".into()))]),
798            truth: true,
799            derived_from: None,
800            supersedes: None,
801            modality: Some(Believed),
802            provenance: Some(vec!["did:example:a".into(), "did:example:b".into()]),
803            confidence: Some(0.8),
804            valid_until_ms: Some(1_700_000_000_000),
805        };
806        let fenv = env(Performative::Inform, cl_body(vec![f]));
807        let back = Envelope::decode(&fenv.encode().unwrap()).unwrap();
808        match &back.body {
809            Body::Cl { expressions } => match &expressions[0] {
810                ClExpr::Fact { modality, provenance, confidence, valid_until_ms, .. } => {
811                    assert_eq!(*modality, Some(Believed));
812                    assert_eq!(provenance.as_ref().unwrap().len(), 2);
813                    assert_eq!(*confidence, Some(0.8));
814                    assert_eq!(*valid_until_ms, Some(1_700_000_000_000));
815                }
816                other => panic!("expected Fact, got {other:?}"),
817            },
818            other => panic!("expected Cl, got {other:?}"),
819        }
820        // absent fields decode as None (backward compatible with v0.2 facts)
821        let plain = env(Performative::Inform, cl_body(vec![ClExpr::fact("f", serde_json::json!({}))]));
822        match Envelope::decode(&plain.encode().unwrap()).unwrap().body {
823            Body::Cl { expressions } => match expressions[0] {
824                ClExpr::Fact { modality: None, provenance: None, confidence: None, valid_until_ms: None, .. } => {}
825                _ => panic!("defaults must be None"),
826            },
827            _ => panic!(),
828        }
829    }
830
831    #[test]
832    fn clvalue_types_and_wire_compat() {
833        use ClValue::*;
834        // wire compatibility: typed values serialize identically to plain
835        let f_typed = ClExpr::Fact {
836            predicate: "p".into(),
837            args: BTreeMap::from([
838                ("s".into(), Str("x".into())),
839                ("i".into(), Int(42)),
840                ("f".into(), Float(1.5)),
841                ("b".into(), Bool(true)),
842                ("l".into(), List(vec![Int(1), Int(2)])),
843            ]),
844            truth: true,
845            derived_from: None,
846            supersedes: None,
847            modality: None,
848            provenance: None,
849            confidence: None,
850            valid_until_ms: None,
851        };
852        let f_plain = ClExpr::fact("p", serde_json::json!({
853            "s": "x", "i": 42, "f": 1.5, "b": true, "l": [1, 2]
854        }));
855        let mut e_typed = env(Performative::Inform, cl_body(vec![f_typed]));
856        let mut e_plain = env(Performative::Inform, cl_body(vec![f_plain]));
857        e_typed.msg_id = "typed-plain-0001".into();
858        e_plain.msg_id = "typed-plain-0001".into();
859        e_typed.ts = 0;
860        e_plain.ts = 0;
861        assert_eq!(e_typed.encode().unwrap(), e_plain.encode().unwrap(),
862            "typed and plain must be wire-identical");
863
864        // strict typing: from_json rejects int-as-float
865        assert!(ClValue::from_json(serde_json::json!(5.5)).is_ok()); // Float
866        assert!(matches!(ClValue::from_json(serde_json::json!(5)), Ok(ClValue::Int(5))));
867        assert!(ClValue::from_json(serde_json::json!(null)).is_err());
868        // type_name
869        assert_eq!(ClValue::Str("x".into()).type_name(), "string");
870        assert_eq!(ClValue::Int(1).type_name(), "int");
871    }
872
873    #[test]
874    fn bind_scope_and_partial() {
875        // $bind reference inside body: legal
876        let bound = ClExpr::bind(
877            "f",
878            ClExpr::fact("file_exists", serde_json::json!({"path": "/x"})),
879            ClExpr::ref_to("$bind:f"),
880        );
881        assert!(well_formed(Performative::Inform, &[bound]).is_ok());
882        // $bind reference WITHOUT enclosing bind: illegal
883        assert!(well_formed(
884            Performative::Inform,
885            &[ClExpr::ref_to("$bind:missing")]
886        ).is_err());
887        // bind must wrap a leaf
888        assert!(well_formed(
889            Performative::Inform,
890            &[ClExpr::bind(
891                "f",
892                ClExpr::and(vec![ClExpr::fact("a", serde_json::json!({}))]),
893                ClExpr::ref_to("$bind:f"),
894            )]
895        ).is_err());
896    }
897
898    #[test]
899    fn quantification_and_metanivel() {
900        // for_all with query domain: legal under inform
901        let fa = ClExpr::for_all(
902            "f",
903            ClExpr::query("dir_entries", serde_json::json!({"path": "/x"})),
904            ClExpr::fact("file_exists", serde_json::json!({"path": "$var:f"})),
905        );
906        assert!(well_formed(Performative::Inform, &[fa]).is_ok());
907        // over must be a query
908        assert!(well_formed(
909            Performative::Inform,
910            &[ClExpr::for_all(
911                "f",
912                ClExpr::fact("x", serde_json::json!({})),
913                ClExpr::fact("y", serde_json::json!({})),
914            )]
915        ).is_err());
916        // believes: only under inform, wraps fact
917        assert!(well_formed(
918            Performative::Inform,
919            &[ClExpr::believes(
920                "did:key:zabc",
921                ClExpr::fact("healthy", serde_json::json!({"agent": "x"})),
922            )]
923        ).is_ok());
924        assert!(well_formed(
925            Performative::Request,
926            &[ClExpr::believes("a", ClExpr::fact("f", serde_json::json!({})))]
927        ).is_err());
928        // renew: only under request
929        assert!(well_formed(
930            Performative::Request,
931            &[ClExpr::renew("commitment-1", 1700000000000)]
932        ).is_ok());
933        assert!(well_formed(
934            Performative::Inform,
935            &[ClExpr::renew("c", 1700000000000)]
936        ).is_err());
937    }
938
939    #[test]
940    fn retract_and_supersedes() {
941        use crate::dialogue::dialogue_legal;
942        // retract is a legal reply after inform (belief revision)
943        assert!(dialogue_legal(Performative::Inform, Performative::Retract));
944        assert!(dialogue_legal(Performative::Retract, Performative::Inform));
945        // supersedes roundtrip: the new fact references the old one
946        let revised = ClExpr::Fact {
947            predicate: "task_status".into(),
948            args: BTreeMap::from([("msg_id".into(), ClValue::Str("m1".into()))]),
949            truth: false,
950            derived_from: None,
951            supersedes: Some("original-msg-id".into()),
952            modality: None,
953            provenance: None,
954            confidence: None,
955            valid_until_ms: None,
956        };
957        let env = env(Performative::Inform, cl_body(vec![revised]));
958        match Envelope::decode(&env.encode().unwrap()).unwrap().body {
959            Body::Cl { expressions } => match &expressions[0] {
960                ClExpr::Fact { supersedes, truth, .. } => {
961                    assert_eq!(supersedes.as_deref(), Some("original-msg-id"));
962                    assert!(!truth); // the superseded claim is now false
963                }
964                other => panic!("expected Fact, got {other:?}"),
965            },
966            other => panic!("expected Cl, got {other:?}"),
967        }
968    }
969
970    #[test]
971    fn conditional_commitments() {
972        // IF file_exists THEN I commit to file_read
973        let cc = ClExpr::conditional_commitment(
974            "local:1:kenji",
975            "local:2:argus",
976            ClExpr::fact("file_exists", serde_json::json!({"path": "/tmp/in"})),
977            ClAction { name: "acl.std.fs.file_read".into(), params: serde_json::json!({"path": "/tmp/in"}), result_schema: None, partial: None },
978            None,
979            CommitmentStatus::Proposed,
980        );
981        assert!(well_formed(Performative::Propose, &[cc]).is_ok());
982        // condition must be a fact composition — action as condition is illegal
983        assert!(well_formed(
984            Performative::Propose,
985            &[ClExpr::conditional_commitment(
986                "a", "b",
987                ClExpr::action("t", serde_json::json!({})),
988                ClAction { name: "t".into(), params: serde_json::json!({}), result_schema: None, partial: None },
989                None, CommitmentStatus::Proposed,
990            )]
991        ).is_err());
992    }
993
994    #[test]
995    fn prefer_policy() {
996        let policy = ClExpr::prefer(vec![
997            ClExpr::fact("cheap", serde_json::json!({})),
998            ClExpr::fact("within_deadline", serde_json::json!({})),
999        ]);
1000        assert!(well_formed(Performative::Propose, &[policy]).is_ok());
1001        // not under inform
1002        assert!(well_formed(
1003            Performative::Inform,
1004            &[ClExpr::prefer(vec![ClExpr::fact("f", serde_json::json!({}))])]
1005        ).is_err());
1006        // empty criteria illegal
1007        assert!(well_formed(Performative::Accept, &[ClExpr::prefer(vec![])]).is_err());
1008    }
1009
1010    #[test]
1011    fn error_taxonomy_roundtrip() {
1012        use crate::ErrorKind;
1013        let env = env(
1014            Performative::Error,
1015            Body::Error {
1016                code: 422,
1017                message: "schema violation".into(),
1018                taxonomy: Some(ErrorKind::SchemaViolation),
1019                details: Some(serde_json::json!({"param": "path"})),
1020            },
1021        );
1022        match Envelope::decode(&env.encode().unwrap()).unwrap().body {
1023            Body::Error { taxonomy, .. } => {
1024                assert_eq!(taxonomy, Some(ErrorKind::SchemaViolation));
1025            }
1026            other => panic!("expected Error, got {other:?}"),
1027        }
1028        // taxonomy serializes as snake_case string on the wire
1029        let wire = serde_json::to_value(&env.body).unwrap();
1030        assert_eq!(wire["v"]["taxonomy"], "schema_violation");
1031    }
1032
1033    #[test]
1034    fn measured_values_roundtrip() {
1035        // 5000 ms is unambiguous: {"$measured": {"value": 5000, "unit": "ms"}}
1036        let env = env(
1037            Performative::Inform,
1038            cl_body(vec![ClExpr::Fact {
1039                predicate: "elapsed_longer".into(),
1040                args: BTreeMap::from([(
1041                    "min_ms".into(),
1042                    ClValue::Measured { value: Box::new(ClValue::Int(5000)), unit: "ms".into() },
1043                )]),
1044                truth: true,
1045                derived_from: None,
1046                supersedes: None,
1047                modality: None,
1048                provenance: None,
1049                confidence: None,
1050                valid_until_ms: None,
1051            }]),
1052        );
1053        match Envelope::decode(&env.encode().unwrap()).unwrap().body {
1054            Body::Cl { expressions } => match &expressions[0] {
1055                ClExpr::Fact { args, .. } => match &args["min_ms"] {
1056                    ClValue::Measured { value, unit } => {
1057                        assert_eq!(**value, ClValue::Int(5000));
1058                        assert_eq!(unit, "ms");
1059                    }
1060                    other => panic!("expected Measured, got {other:?}"),
1061                },
1062                other => panic!("expected Fact, got {other:?}"),
1063            },
1064            other => panic!("expected Cl, got {other:?}"),
1065        }
1066        // type_name
1067        let m = ClValue::Measured { value: Box::new(ClValue::Int(1)), unit: "kg".into() };
1068        assert_eq!(m.type_name(), "measured");
1069    }
1070
1071    #[test]
1072    fn mixed_ops_rejected() {
1073        // one message carrying fact + action is ill-formed under inform
1074        assert!(well_formed(
1075            Performative::Inform,
1076            &[ClExpr::fact("f", serde_json::json!({})), ClExpr::action("t", serde_json::json!({}))]
1077        )
1078        .is_err());
1079    }
1080}