Skip to main content

cbcl_core/
state.rs

1//! State layer (SPEC-019 R.1–R.3): the `(state …)` clause, fixed kernel
2//! selections and reductions (including protocol-position maximum), the fold, and the
3//! canonical JSON rendering.
4//!
5//! Every function here is a pure set function of a thread's accepted acts:
6//! permuting or duplicating the input leaves the output unchanged (R7).
7//! No clock, no randomness, no other thread.
8
9#![forbid(unsafe_code)]
10
11use crate::equivocation::message_content_hash;
12use crate::message::{CausedBy, Message};
13use crate::protocol::{CausalProtocol, NodeRef, BEGIN_KEYWORD};
14use crate::sexpr::{Atom, SExpr};
15use crate::shape::{ShapeRule, TypeConstraint};
16use alloc::collections::{BTreeMap, BTreeSet};
17use alloc::format;
18use alloc::string::{String, ToString};
19use alloc::vec::Vec;
20
21/// The reserved bookkeeping keyword (SPEC-019 ADR-1901). Inserted into the
22/// shapes of every writer, delete, and remove verb by the compiler; never
23/// declared by an author; never read as data by any rule.
24pub const RESERVED_REPLACES: &str = "replaces";
25
26/// Routing keywords that a closed shape admits beside the declared fields.
27pub const ROUTING_KEYWORDS: &[&str] = &["caused-by", "thread", "from", "to", "sender"];
28
29// ---------------------------------------------------------------------------
30// Clause types
31// ---------------------------------------------------------------------------
32
33/// `(:state-bounds …)` (SPEC-019 R.1, ADR-1911). Defaults apply when absent.
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub struct StateBounds {
37    pub max_string: u32,
38    pub max_list: u32,
39    pub max_number: i64,
40    pub max_fields: u32,
41}
42
43impl Default for StateBounds {
44    fn default() -> Self {
45        Self {
46            max_string: 2048,
47            max_list: 64,
48            max_number: 1_000_000_000_000,
49            max_fields: 32,
50        }
51    }
52}
53
54/// One author-facing rule (SPEC-019 R.1). Defined by desugaring to the
55/// kernel (R.2); see [`fold`].
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
58pub enum Rule {
59    Context {
60        path: Vec<String>,
61        definition: Option<alloc::boxed::Box<crate::context::Definition>>,
62    },
63    /// A finite lattice and contribution table verified at installation.
64    Lift(alloc::boxed::Box<crate::finite::Lift>),
65    BoundedCounter(alloc::boxed::Box<crate::escrow::CounterRule>),
66    /// Clock-trusting last-writer-wins over domain-admitted writes.
67    LwwRegister {
68        verb: String,
69        key: String,
70        clock: String,
71    },
72    /// Own observed replacement, then clock arbitration among survivors.
73    LwwPerSigner {
74        verb: String,
75        key: String,
76        clock: String,
77    },
78    /// Keyed observed replacement/deletion, then clock arbitration.
79    LwwMap {
80        verb: String,
81        key: String,
82        value: String,
83        clock: String,
84        delete: Option<String>,
85    },
86    /// Immutable field of the unique accepted opener; no arbitration.
87    Initial {
88        verb: String,
89        key: String,
90    },
91    Exists {
92        verb: String,
93    },
94    Count {
95        verb: String,
96    },
97    /// Greatest established position of a verb in its ordered protocol chain.
98    Progress {
99        verb: String,
100    },
101    Events {
102        verb: String,
103        key: String,
104    },
105    SetUnion {
106        verb: String,
107        key: String,
108    },
109    Values {
110        verb: String,
111        key: String,
112    },
113    ValuesPerKey {
114        verb: String,
115        key: String,
116        value: String,
117        delete: Option<String>,
118    },
119    ObservedSet {
120        add: String,
121        remove: String,
122        key: String,
123    },
124    Counter {
125        inc: String,
126        dec: String,
127        key: String,
128    },
129    Histogram {
130        field: String,
131    },
132    Sum {
133        field: String,
134    },
135}
136
137impl Rule {
138    /// The head symbol of this rule in the clause grammar.
139    pub fn head(&self) -> &'static str {
140        match self {
141            Rule::Context { .. } => "context",
142            Rule::Lift(_) => "lift",
143            Rule::BoundedCounter(_) => "bounded-counter",
144            Rule::LwwRegister { .. } => "lww-register",
145            Rule::LwwPerSigner { .. } => "lww-per-signer",
146            Rule::LwwMap { .. } => "lww-map",
147            Rule::Initial { .. } => "initial",
148
149            Rule::Exists { .. } => "exists",
150            Rule::Count { .. } => "count",
151            Rule::Progress { .. } => "progress",
152            Rule::Events { .. } => "events",
153            Rule::SetUnion { .. } => "set-union",
154            Rule::Values { .. } => "values",
155            Rule::ValuesPerKey { .. } => "values-per-key",
156
157            Rule::ObservedSet { .. } => "observed-set",
158            Rule::Counter { .. } => "counter",
159            Rule::Histogram { .. } => "histogram",
160            Rule::Sum { .. } => "sum",
161        }
162    }
163
164    /// Every performative this rule names.
165    pub fn verbs(&self) -> Vec<&str> {
166        match self {
167            Rule::Context { .. } => Vec::new(),
168            Rule::Lift(lift) => alloc::vec![lift.verb.as_str()],
169            Rule::BoundedCounter(c) => c.verbs(),
170            Rule::LwwRegister { verb, .. }
171            | Rule::LwwPerSigner { verb, .. }
172            | Rule::Initial { verb, .. }
173            | Rule::Exists { verb }
174            | Rule::Count { verb }
175            | Rule::Progress { verb }
176            | Rule::Events { verb, .. }
177            | Rule::SetUnion { verb, .. }
178            | Rule::Values { verb, .. } => alloc::vec![verb.as_str()],
179            Rule::ValuesPerKey { verb, delete, .. } | Rule::LwwMap { verb, delete, .. } => {
180                let mut v = alloc::vec![verb.as_str()];
181                if let Some(d) = delete {
182                    v.push(d.as_str());
183                }
184                v
185            }
186            Rule::ObservedSet { add, remove, .. } => alloc::vec![add.as_str(), remove.as_str()],
187            Rule::Counter { inc, dec, .. } => alloc::vec![inc.as_str(), dec.as_str()],
188            Rule::Histogram { .. } | Rule::Sum { .. } => Vec::new(),
189        }
190    }
191
192    /// Declared clock evidence of an explicit LWW rule, if any.
193    pub fn clock_field(&self) -> Option<(&str, &str)> {
194        match self {
195            Rule::LwwRegister { verb, clock, .. }
196            | Rule::LwwPerSigner { verb, clock, .. }
197            | Rule::LwwMap { verb, clock, .. } => Some((verb, clock)),
198            _ => None,
199        }
200    }
201
202    /// Every `(verb, key)` pair this rule reads as data.
203    pub fn data_fields(&self) -> Vec<(&str, &str)> {
204        match self {
205            Rule::Context { .. } => Vec::new(),
206            Rule::Lift(lift) => lift
207                .rows
208                .iter()
209                .map(|row| (lift.verb.as_str(), row.key.as_str()))
210                .collect(),
211            Rule::BoundedCounter(c) => c.data_fields(),
212            Rule::LwwRegister { verb, key, clock } | Rule::LwwPerSigner { verb, key, clock } => {
213                alloc::vec![(verb, key), (verb, clock)]
214            }
215            Rule::LwwMap {
216                verb,
217                key,
218                value,
219                clock,
220                delete,
221            } => {
222                let mut fields = alloc::vec![
223                    (verb.as_str(), key.as_str()),
224                    (verb.as_str(), value.as_str()),
225                    (verb.as_str(), clock.as_str())
226                ];
227                if let Some(d) = delete {
228                    fields.push((d, key));
229                }
230                fields
231            }
232            Rule::Initial { verb, key }
233            | Rule::Events { verb, key }
234            | Rule::SetUnion { verb, key }
235            | Rule::Values { verb, key } => alloc::vec![(verb.as_str(), key.as_str())],
236
237            Rule::ValuesPerKey {
238                verb,
239                key,
240                value,
241                delete,
242            } => {
243                let mut v = alloc::vec![
244                    (verb.as_str(), key.as_str()),
245                    (verb.as_str(), value.as_str())
246                ];
247                if let Some(d) = delete {
248                    v.push((d.as_str(), key.as_str()));
249                }
250                v
251            }
252            Rule::ObservedSet { add, remove, key } => {
253                alloc::vec![
254                    (add.as_str(), key.as_str()),
255                    (remove.as_str(), key.as_str())
256                ]
257            }
258            Rule::Counter { inc, dec, key } => {
259                alloc::vec![(inc.as_str(), key.as_str()), (dec.as_str(), key.as_str())]
260            }
261            Rule::Exists { .. }
262            | Rule::Count { .. }
263            | Rule::Progress { .. }
264            | Rule::Histogram { .. }
265            | Rule::Sum { .. } => Vec::new(),
266        }
267    }
268
269    /// The verbs whose shape must carry the reserved `:replaces` field:
270    /// writers and delete verbs of registers, signer writers, and observed-set removals.
271    pub fn replaces_verbs(&self) -> Vec<&str> {
272        match self {
273            Rule::Values { verb, .. } | Rule::LwwPerSigner { verb, .. } => {
274                alloc::vec![verb.as_str()]
275            }
276            Rule::ValuesPerKey { verb, delete, .. } | Rule::LwwMap { verb, delete, .. } => {
277                let mut v = alloc::vec![verb.as_str()];
278                if let Some(d) = delete {
279                    v.push(d.as_str());
280                }
281                v
282            }
283            Rule::ObservedSet { remove, .. } => alloc::vec![remove.as_str()],
284            _ => Vec::new(),
285        }
286    }
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
291pub enum FreezePolicy {
292    Supersede,
293    Fault,
294}
295
296impl FreezePolicy {
297    pub fn as_str(self) -> &'static str {
298        match self {
299            Self::Supersede => "supersede",
300            Self::Fault => "fault",
301        }
302    }
303}
304
305/// One entry of the state clause.
306#[derive(Debug, Clone, PartialEq, Eq)]
307#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
308pub enum Entry {
309    Lattice(crate::finite::Definition),
310    Field {
311        name: String,
312        rule: Rule,
313    },
314    /// `(domain verb key field)`: acts of `verb` whose `key` is not an
315    /// element of the list-valued `field` contribute nothing.
316    Domain {
317        verb: String,
318        key: String,
319        field: String,
320    },
321    /// `(threshold name field element+)`: a threshold read over `field`'s
322    /// carrier (SPEC-038 REQ-3802, CON-3801), rendered as a field named
323    /// `name` in clause order: `reached` with the unique element at or below
324    /// the carrier's current element, or `pending`.
325    Threshold {
326        name: String,
327        field: String,
328        elements: Vec<crate::lattice::Element>,
329    },
330    /// Authored Boolean conjunction/read observation (CON-3805).
331    Condition {
332        name: String,
333        condition: Condition,
334    },
335    Freeze {
336        field: String,
337        verb: String,
338        policy: FreezePolicy,
339    },
340}
341
342/// Closed authored threshold expressions (SPEC-038 CON-3805).
343#[derive(Debug, Clone, PartialEq, Eq)]
344#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
345pub enum Condition {
346    Read {
347        field: String,
348        element: crate::lattice::Element,
349    },
350    And(Vec<Condition>),
351}
352
353impl Condition {
354    pub fn size(&self) -> usize {
355        match self {
356            Self::Read { .. } => 1,
357            Self::And(children) => 1 + children.iter().map(Self::size).sum::<usize>(),
358        }
359    }
360    pub fn leaves<'a>(&'a self, out: &mut Vec<(&'a str, &'a crate::lattice::Element)>) {
361        match self {
362            Self::Read { field, element } => out.push((field, element)),
363            Self::And(children) => {
364                for child in children {
365                    child.leaves(out);
366                }
367            }
368        }
369    }
370    pub fn to_sexpr(&self) -> SExpr {
371        let sym = |s: &str| SExpr::Atom(Atom::Symbol(s.into()));
372        match self {
373            Self::Read { field, element } => {
374                SExpr::List(alloc::vec![sym("read"), sym(field), element.to_sexpr()])
375            }
376            Self::And(children) => SExpr::List(
377                core::iter::once(sym("and"))
378                    .chain(children.iter().map(Self::to_sexpr))
379                    .collect(),
380            ),
381        }
382    }
383    pub fn schema(&self) -> Value {
384        let text = |s: &str| Value::Str(s.into());
385        match self {
386            Self::Read { field, element } => Value::Map(alloc::vec![
387                (text("op"), text("read")),
388                (text("field"), text(field)),
389                (text("element"), element.render())
390            ]),
391            Self::And(children) => Value::Map(alloc::vec![
392                (text("op"), text("and")),
393                (
394                    text("conditions"),
395                    Value::List(children.iter().map(Self::schema).collect())
396                )
397            ]),
398        }
399    }
400    // Evaluate every leaf before deciding: pending never hides a sibling fault.
401    pub(crate) fn evaluate(
402        &self,
403        read: &mut impl FnMut(&str, &crate::lattice::Element) -> Value,
404    ) -> Value {
405        let mut leaves = Vec::new();
406        self.leaves(&mut leaves);
407        let mut reached = true;
408        let mut fault = false;
409        let mut evidence = Vec::new();
410        for (field, element) in leaves {
411            let value = read(field, element);
412            if let Some(found) = value.fault_evidence() {
413                fault = true;
414                evidence.extend(found);
415            }
416            reached &= matches!(&value, Value::Map(entries) if entries.iter().any(|(k,v)| matches!((k,v), (Value::Str(k),Value::Str(v)) if k == "status" && v == "reached")));
417        }
418        if fault {
419            return conflict_top("state conflicts", evidence);
420        }
421        let mut entries = alloc::vec![(
422            Value::Str("status".into()),
423            Value::Str(if reached { "reached" } else { "pending" }.into())
424        )];
425        if reached {
426            entries.push((Value::Str("element".into()), Value::Bool(true)));
427        }
428        Value::Map(entries)
429    }
430}
431
432/// The parsed `(state …)` clause (SPEC-019 R.1).
433#[derive(Debug, Clone, PartialEq, Eq, Default)]
434#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
435pub struct StateClause {
436    pub entries: Vec<Entry>,
437}
438
439impl StateClause {
440    pub fn lattices(&self) -> impl Iterator<Item = &crate::finite::Definition> {
441        self.entries.iter().filter_map(|entry| match entry {
442            Entry::Lattice(d) => Some(d),
443            _ => None,
444        })
445    }
446
447    /// Rebuild implementation-only table indexes from recognized declarations.
448    pub fn resolve_lattices(&mut self) {
449        let definitions: BTreeMap<String, crate::finite::Definition> = self
450            .lattices()
451            .map(|d| (d.name.clone(), d.clone()))
452            .collect();
453        for entry in &mut self.entries {
454            if let Entry::Field {
455                rule: Rule::Lift(lift),
456                ..
457            } = entry
458            {
459                lift.table = definitions
460                    .get(&lift.lattice)
461                    .and_then(|d| d.compile().ok())
462                    .map(alloc::boxed::Box::new);
463            }
464        }
465    }
466    /// Field entries in clause order.
467    pub fn fields(&self) -> impl Iterator<Item = (&str, &Rule)> {
468        self.entries.iter().filter_map(|e| match e {
469            Entry::Field { name, rule } => Some((name.as_str(), rule)),
470            _ => None,
471        })
472    }
473
474    /// Domain entries in clause order.
475    pub fn domains(&self) -> impl Iterator<Item = (&str, &str, &str)> {
476        self.entries.iter().filter_map(|e| match e {
477            Entry::Domain { verb, key, field } => {
478                Some((verb.as_str(), key.as_str(), field.as_str()))
479            }
480            _ => None,
481        })
482    }
483
484    /// Threshold entries in clause order: `(name, field, elements)`
485    /// (SPEC-038 CON-3801).
486    pub fn thresholds(&self) -> impl Iterator<Item = (&str, &str, &[crate::lattice::Element])> {
487        self.entries.iter().filter_map(|e| match e {
488            Entry::Threshold {
489                name,
490                field,
491                elements,
492            } => Some((name.as_str(), field.as_str(), elements.as_slice())),
493            _ => None,
494        })
495    }
496
497    pub fn freezes(&self) -> impl Iterator<Item = (&str, &str, FreezePolicy)> {
498        self.entries.iter().filter_map(|e| match e {
499            Entry::Freeze {
500                field,
501                verb,
502                policy,
503            } => Some((field.as_str(), verb.as_str(), *policy)),
504            _ => None,
505        })
506    }
507
508    /// Every performative the clause names (state-bearing verbs).
509    pub fn state_bearing_verbs(&self) -> BTreeSet<&str> {
510        let mut out = BTreeSet::new();
511        for (_, rule) in self.fields() {
512            out.extend(rule.verbs());
513        }
514        for (verb, _, _) in self.domains() {
515            out.insert(verb);
516        }
517        for (_, verb, _) in self.freezes() {
518            out.insert(verb);
519        }
520        out
521    }
522
523    /// Verbs whose shape carries the reserved `:replaces` field.
524    pub fn replaces_verbs(&self) -> BTreeSet<&str> {
525        let mut out = BTreeSet::new();
526        for (_, rule) in self.fields() {
527            out.extend(rule.replaces_verbs());
528        }
529        out
530    }
531
532    /// Every `(verb, key)` pair any rule or domain reads.
533    pub fn data_fields(&self) -> BTreeSet<(&str, &str)> {
534        let mut out = BTreeSet::new();
535        for (_, rule) in self.fields() {
536            out.extend(rule.data_fields());
537        }
538        for (verb, key, _) in self.domains() {
539            out.insert((verb, key));
540        }
541        out
542    }
543
544    /// The rule of a named field, if any.
545    pub fn rule_of(&self, field: &str) -> Option<&Rule> {
546        self.fields().find(|(n, _)| *n == field).map(|(_, r)| r)
547    }
548}
549
550/// The opener of a protocol: the one performative whose only predecessor
551/// is `begin`, when exactly one exists.
552pub fn opener_verb(protocol: &CausalProtocol) -> Option<&str> {
553    let mut found = None;
554    for (name, step) in &protocol.steps {
555        if name == BEGIN_KEYWORD {
556            continue;
557        }
558        let only_begin = step.predecessors.len() == 1
559            && matches!(&step.predecessors[0], NodeRef::Single(s) if s == BEGIN_KEYWORD);
560        if only_begin {
561            if found.is_some() {
562                return None;
563            }
564            found = Some(crate::protocol::repeat_base_name(name));
565        }
566    }
567    found
568}
569
570// ---------------------------------------------------------------------------
571// Acts
572// ---------------------------------------------------------------------------
573
574/// An accepted message as the fold sees it (SPEC-019 Reference, "act").
575///
576/// The signer is supplied by the host's authentication gate, never read
577/// from the payload. `message` is the complete received message, wrappers
578/// included, so a store can be rebuilt from acts for the binder's
579/// verification step and the cast can be read from the root wrapper.
580#[derive(Debug, Clone, PartialEq, Eq)]
581#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
582pub struct Act {
583    /// Canonical sealed-wrapper hash for causal role roots; simple-message hash otherwise.
584    pub address: String,
585    pub verb: String,
586    pub signer: String,
587    pub predecessors: Vec<String>,
588    pub recipients: BTreeSet<String>,
589    /// Keyword fields of the innermost simple message, routing keywords
590    /// excluded.
591    pub fields: BTreeMap<String, SExpr>,
592    pub message: Message,
593}
594
595impl Act {
596    /// View a received message as an act. `signer` is the authenticated
597    /// sender established by the host.
598    pub fn from_message(message: Message, signer: &str) -> Result<Act, String> {
599        let simple = message
600            .innermost_simple()
601            .ok_or_else(|| String::from("an act must contain a simple message"))?;
602        let verb = simple
603            .performative()
604            .ok_or_else(|| String::from("an act must have a performative"))?
605            .name()
606            .to_string();
607        let predecessors = match simple.caused_by() {
608            None | Some(CausedBy::Begin) => Vec::new(),
609            Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
610            Some(CausedBy::Multiple(hs)) => hs.clone(),
611        };
612        let recipients = simple
613            .recipient_set()
614            .into_iter()
615            .map(String::from)
616            .collect();
617        let fields = keyword_fields(simple);
618        let address = wire_address(state_identity_message(&message, simple));
619        Ok(Act {
620            address,
621            verb,
622            signer: String::from(signer),
623            predecessors,
624            recipients,
625            fields,
626            message,
627        })
628    }
629
630    /// Check derived metadata against the message without cloning an owned Act.
631    /// The signer remains host-supplied; this check does not authenticate it.
632    pub fn validate_identity(&self) -> Result<(), String> {
633        let simple = self
634            .message
635            .innermost_simple()
636            .ok_or_else(|| String::from("an act must contain a simple message"))?;
637        let verb = simple
638            .performative()
639            .ok_or_else(|| String::from("an act must have a performative"))?;
640        let predecessors_match = match simple.caused_by() {
641            None | Some(CausedBy::Begin) => self.predecessors.is_empty(),
642            Some(CausedBy::Single(h)) => self.predecessors.as_slice() == core::slice::from_ref(h),
643            Some(CausedBy::Multiple(hs)) => self.predecessors == *hs,
644        };
645        // Mirror keyword_fields exactly, including last-value-wins and its
646        // permissive scan of malformed lists. Structural admission checks the
647        // complete parameter grammar afterward, at the original rejection point.
648        let mut fields = BTreeMap::new();
649        if let Message::Simple { params, .. } = simple {
650            let mut i = 0;
651            while i + 1 < params.len() {
652                if let SExpr::Atom(Atom::Keyword(k)) = &params[i] {
653                    if !ROUTING_KEYWORDS.contains(&k.as_str()) {
654                        fields.insert(k.as_str(), &params[i + 1]);
655                    }
656                    i += 2;
657                } else {
658                    i += 1;
659                }
660            }
661        }
662        let fields_match = fields.len() == self.fields.len()
663            && fields
664                .into_iter()
665                .all(|(k, v)| self.fields.get(k) == Some(v));
666        let recipients = simple.recipient_set();
667        let recipients_match = self.recipients.iter().map(String::as_str).eq(recipients);
668        let address = wire_address(state_identity_message(&self.message, simple));
669        if self.address != address
670            || self.verb != verb.name()
671            || !predecessors_match
672            || !recipients_match
673            || !fields_match
674        {
675            return Err(String::from("inconsistent act identity"));
676        }
677        Ok(())
678    }
679
680    /// The innermost simple message.
681    pub fn simple(&self) -> &Message {
682        self.message
683            .innermost_simple()
684            .expect("an Act always wraps a simple message")
685    }
686}
687
688// SPEC-038 ADR-3807: identity commits exactly the cast subtree interpreted by
689// the context kernel. Root classification mirrors reconstructed predecessors,
690// including typed empty Multiple; never consult unverified cached Act metadata.
691fn state_identity_message<'a>(message: &'a Message, simple: &'a Message) -> &'a Message {
692    let root = match simple.caused_by() {
693        None | Some(CausedBy::Begin) => true,
694        Some(CausedBy::Multiple(predecessors)) => predecessors.is_empty(),
695        Some(CausedBy::Single(_)) => false,
696    };
697    if !root {
698        return simple;
699    }
700    let mut current = message;
701    loop {
702        match current {
703            Message::Wrapped {
704                wrapper: crate::message::WrapperType::WithRoles,
705                ..
706            } => return current,
707            Message::Wrapped { content, .. } => current = content,
708            Message::Dialect { inner, .. } => current = inner,
709            _ => return simple,
710        }
711    }
712}
713
714/// The content address of an act as a canonical multibase SHA2-256 multihash.
715/// The same symbol-safe spelling is used for native and state references.
716/// Act construction selects its identity subtree under SPEC-038 ADR-3807.
717pub fn wire_address(message: &Message) -> String {
718    message_content_hash(message)
719}
720
721/// The keyword parameters of a simple message as a map, routing keywords
722/// excluded.
723pub fn keyword_fields(simple: &Message) -> BTreeMap<String, SExpr> {
724    let mut out = BTreeMap::new();
725    if let Message::Simple { params, .. } = simple {
726        let mut i = 0;
727        while i + 1 < params.len() {
728            if let SExpr::Atom(Atom::Keyword(k)) = &params[i] {
729                if !ROUTING_KEYWORDS.contains(&k.as_str()) {
730                    out.insert(k.clone(), params[i + 1].clone());
731                }
732                i += 2;
733            } else {
734                i += 1;
735            }
736        }
737    }
738    out
739}
740
741/// The accepted opener, if present: the act of the protocol's opener verb.
742/// Role-free, its predecessor is `begin`; under R6 it names the thread's
743/// cast-bearing root ([[SPEC-014]] REQ-623), which is not an act of the
744/// dialect. Several openers in one thread cannot verify, so the least
745/// address is a deterministic tie-break, never a semantic one.
746pub fn opener<'a>(protocol: &CausalProtocol, acts: &'a [Act]) -> Option<&'a Act> {
747    let verb = opener_verb(protocol)?;
748    let repeated = protocol.steps.keys().any(|name| {
749        name.contains(crate::protocol::REPEAT_SEPARATOR)
750            && crate::protocol::repeat_base_name(name) == verb
751    });
752    let root = root(acts);
753    acts.iter()
754        .filter(|a| {
755            a.verb == verb
756                && (!repeated
757                    || matches!(
758                        a.simple().caused_by(),
759                        Some(crate::message::CausedBy::Begin)
760                    )
761                    || root.is_some_and(|r| a.predecessors == alloc::vec![r.address.clone()]))
762        })
763        .min_by(|a, b| a.address.cmp(&b.address))
764}
765
766/// The thread's R6 root: the act whose message carries the `with-roles`
767/// wrapper (the cast) and no predecessor. `None` for a role-free thread.
768pub fn root(acts: &[Act]) -> Option<&Act> {
769    acts.iter()
770        .filter(|a| is_role_root(a))
771        .min_by(|a, b| a.address.cmp(&b.address))
772}
773
774// Root discovery follows the same transparent-wrapper policy as identity and
775// cast extraction, including when a transport wrapper encloses the sealed cast.
776pub(crate) fn is_role_root(act: &Act) -> bool {
777    act.predecessors.is_empty()
778        && matches!(
779            state_identity_message(&act.message, act.simple()),
780            Message::Wrapped {
781                wrapper: crate::message::WrapperType::WithRoles,
782                ..
783            }
784        )
785}
786
787/// The frontier: addresses no accepted act names in `:caused-by`, sorted.
788pub fn frontier(acts: &[Act]) -> Vec<String> {
789    let named: BTreeSet<&str> = acts
790        .iter()
791        .flat_map(|a| a.predecessors.iter().map(|p| p.as_str()))
792        .collect();
793    let mut out: Vec<String> = acts
794        .iter()
795        .filter(|a| !named.contains(a.address.as_str()))
796        .map(|a| a.address.clone())
797        .collect();
798    out.sort();
799    out.dedup();
800    out
801}
802
803// ---------------------------------------------------------------------------
804// Values
805// ---------------------------------------------------------------------------
806
807/// A state value (SPEC-019 R.3).
808#[derive(Debug, Clone, PartialEq, Eq)]
809#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
810pub enum Value {
811    Absent,
812    Str(String),
813    Int(i128),
814    Float(crate::numeric::Float),
815    Decimal(crate::numeric::Decimal),
816    Bool(bool),
817    /// A scalar list as a field value (never sorted; it is data).
818    List(Vec<Value>),
819    /// A set: distinct elements sorted by rendering.
820    Set(Vec<Value>),
821    /// A map: distinct keys sorted by rendering.
822    Map(Vec<(Value, Value)>),
823    /// A contribution of `events`: who supplied a value.
824    Pair {
825        by: String,
826        value: alloc::boxed::Box<Value>,
827    },
828}
829
830impl Value {
831    pub(crate) fn unfrozen(&self) -> &Value {
832        if let Value::Map(entries) = self {
833            if entries
834                .iter()
835                .any(|(k, v)| matches!((k,v), (Value::Str(k),Value::Str(_)) if k == "frozen"))
836                && entries.iter().any(
837                    |(k, v)| matches!((k,v), (Value::Str(k),Value::List(_)) if k == "superseded"),
838                )
839            {
840                if let Some((_, value)) = entries
841                    .iter()
842                    .find(|(k, _)| matches!(k, Value::Str(k) if k == "value"))
843                {
844                    return value;
845                }
846            }
847        }
848        self
849    }
850    /// Evidence of a kernel fault. Installed scalar-map types cannot mimic
851    /// the mixed scalar/list structure of this marker.
852    pub fn fault_evidence(&self) -> Option<Vec<String>> {
853        let Value::Map(entries) = self else {
854            return None;
855        };
856        if !entries.iter().any(|(k, v)| {
857            matches!((k, v),
858            (Value::Str(k), Value::Str(v)) if k == "status" && v == "fault")
859        }) {
860            return None;
861        }
862        let (_, Value::List(addresses)) = entries
863            .iter()
864            .find(|(k, _)| matches!(k, Value::Str(k) if k == "evidence"))?
865        else {
866            return None;
867        };
868        addresses
869            .iter()
870            .map(|v| match v {
871                Value::Str(address) => Some(address.clone()),
872                _ => None,
873            })
874            .collect()
875    }
876
877    /// Convert a field value. Symbols and keywords, which typing forbids on
878    /// state-bearing fields, render as their text so the fold stays total.
879    pub fn from_sexpr(s: &SExpr) -> Value {
880        match s {
881            SExpr::Atom(Atom::Str(x)) => Value::Str(x.clone()),
882            SExpr::Atom(Atom::Float(n)) => Value::Float(*n),
883            SExpr::Atom(Atom::Decimal(n)) => Value::Decimal(n.clone()),
884            SExpr::Atom(Atom::Num(n)) => Value::Int(*n as i128),
885            SExpr::Atom(Atom::Bool(b)) => Value::Bool(*b),
886            SExpr::Atom(Atom::Symbol(x)) => Value::Str(x.clone()),
887            SExpr::Atom(Atom::Keyword(x)) => Value::Str(format!(":{x}")),
888            SExpr::List(items) => Value::List(items.iter().map(Value::from_sexpr).collect()),
889        }
890    }
891
892    /// The canonical JSON rendering (R.3).
893    pub fn render(&self) -> String {
894        let mut out = String::new();
895        self.render_into(&mut out);
896        out
897    }
898
899    fn render_into(&self, out: &mut String) {
900        match self {
901            Value::Absent => out.push_str("null"),
902            Value::Str(s) => json_string(s, out),
903            Value::Float(n) => out.push_str(&n.to_string()),
904            Value::Decimal(n) => {
905                out.push_str("{\"decimal\":");
906                json_string(n.as_str(), out);
907                out.push('}');
908            }
909            Value::Int(n) => out.push_str(&n.to_string()),
910            Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
911            Value::List(items) => {
912                out.push('[');
913                for (i, v) in items.iter().enumerate() {
914                    if i > 0 {
915                        out.push(',');
916                    }
917                    v.render_into(out);
918                }
919                out.push(']');
920            }
921            Value::Set(items) => {
922                out.push('[');
923                for (i, v) in items.iter().enumerate() {
924                    if i > 0 {
925                        out.push(',');
926                    }
927                    v.render_into(out);
928                }
929                out.push(']');
930            }
931            Value::Map(entries) => {
932                out.push('{');
933                for (i, (k, v)) in entries.iter().enumerate() {
934                    if i > 0 {
935                        out.push(',');
936                    }
937                    json_string(&map_key_text(k), out);
938                    out.push(':');
939                    v.render_into(out);
940                }
941                out.push('}');
942            }
943            Value::Pair { by, value } => {
944                out.push_str("{\"by\":");
945                json_string(by, out);
946                out.push_str(",\"value\":");
947                value.render_into(out);
948                out.push('}');
949            }
950        }
951    }
952
953    pub fn as_int(&self) -> Option<i128> {
954        match self {
955            Value::Int(n) => Some(*n),
956            Value::Pair { value, .. } => value.as_int(),
957            _ => None,
958        }
959    }
960}
961
962/// The text a scalar contributes as a map key: a string as itself, a
963/// number or boolean as its rendering. A key field has one declared type,
964/// so no collision arises.
965fn map_key_text(k: &Value) -> String {
966    match k {
967        Value::Str(s) => s.clone(),
968        other => other.render(),
969    }
970}
971
972/// RFC 8259 string escaping: the two-character forms where they exist,
973/// `\u00XX` (lowercase hex) for other control characters.
974fn json_string(s: &str, out: &mut String) {
975    out.push('"');
976    for c in s.chars() {
977        match c {
978            '"' => out.push_str("\\\""),
979            '\\' => out.push_str("\\\\"),
980            '\n' => out.push_str("\\n"),
981            '\r' => out.push_str("\\r"),
982            '\t' => out.push_str("\\t"),
983            '\u{8}' => out.push_str("\\b"),
984            '\u{c}' => out.push_str("\\f"),
985            c if (c as u32) < 0x20 => {
986                out.push_str(&format!("\\u{:04x}", c as u32));
987            }
988            c => out.push(c),
989        }
990    }
991    out.push('"');
992}
993
994/// Distinct values sorted by the UTF-8 bytes of their rendering.
995fn sorted_distinct(values: Vec<Value>) -> Vec<Value> {
996    let mut keyed: Vec<(String, Value)> = values.into_iter().map(|v| (v.render(), v)).collect();
997    keyed.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
998    keyed.dedup_by(|a, b| a.0 == b.0);
999    keyed.into_iter().map(|(_, v)| v).collect()
1000}
1001
1002/// The conflict top ⊤ of a field, rendered uniformly across heads as
1003/// `{"evidence":[addresses],"reason":…,"status":"fault"}` with the members
1004/// in key order and the evidence sorted (SPEC-038 REQ-3804, ADR-3803): the
1005/// same member set a `bounded-counter` resource fault carries.
1006pub(crate) fn conflict_top(reason: &str, mut evidence: Vec<String>) -> Value {
1007    sort_addresses(&mut evidence);
1008    evidence.dedup();
1009    Value::Map(alloc::vec![
1010        (
1011            Value::Str(String::from("evidence")),
1012            Value::List(evidence.into_iter().map(Value::Str).collect()),
1013        ),
1014        (
1015            Value::Str(String::from("reason")),
1016            Value::Str(String::from(reason)),
1017        ),
1018        (
1019            Value::Str(String::from("status")),
1020            Value::Str(String::from("fault"))
1021        ),
1022    ])
1023}
1024
1025/// Byte-order radix sort for bounded content addresses (SPEC-038 NFR-3800).
1026/// Sorting indices avoids cloning addresses on every digit pass. A missing
1027/// byte sorts before any byte, preserving ordinary lexicographic prefix order.
1028pub(crate) fn sort_addresses(addresses: &mut Vec<String>) {
1029    if addresses.len() < 2 {
1030        return;
1031    }
1032    let width = addresses.iter().map(|s| s.len()).max().unwrap_or(0);
1033    let mut order: Vec<usize> = (0..addresses.len()).collect();
1034    let mut scratch = alloc::vec![0usize; addresses.len()];
1035    for digit in (0..width).rev() {
1036        let key = |i: usize| {
1037            addresses[i]
1038                .as_bytes()
1039                .get(digit)
1040                .map(|b| *b as usize + 1)
1041                .unwrap_or(0)
1042        };
1043        let mut counts = [0usize; 257];
1044        for &i in &order {
1045            counts[key(i)] += 1;
1046        }
1047        let mut next = [0usize; 257];
1048        for k in 1..257 {
1049            next[k] = next[k - 1] + counts[k - 1];
1050        }
1051        for &i in &order {
1052            let k = key(i);
1053            scratch[next[k]] = i;
1054            next[k] += 1;
1055        }
1056        core::mem::swap(&mut order, &mut scratch);
1057    }
1058    let mut values: Vec<Option<String>> =
1059        core::mem::take(addresses).into_iter().map(Some).collect();
1060    addresses.extend(order.into_iter().map(|i| values[i].take().unwrap()));
1061}
1062
1063#[cfg(test)]
1064mod address_sort_tests {
1065    use super::*;
1066    use proptest::prelude::*;
1067
1068    proptest! {
1069        #[test]
1070        fn radix_address_order_matches_byte_lexicographic_order(
1071            mut addresses in proptest::collection::vec(prop_oneof![
1072                "[a-f0-9]{0,71}",
1073                proptest::collection::vec(any::<char>(), 0..24)
1074                    .prop_map(|chars| chars.into_iter().collect::<String>()),
1075                Just(String::new()), Just(String::from("\0")), Just(String::from("a\0")),
1076            ], 0..64)
1077        ) {
1078            let mut expected = addresses.clone();
1079            expected.sort();
1080            sort_addresses(&mut addresses);
1081            prop_assert_eq!(addresses, expected);
1082        }
1083    }
1084}
1085
1086/// Render a whole state (R.3): an object in clause order.
1087pub fn render_json(state: &[(String, Value)]) -> String {
1088    let mut out = String::from("{");
1089    for (i, (name, value)) in state.iter().enumerate() {
1090        if i > 0 {
1091            out.push(',');
1092        }
1093        json_string(name, &mut out);
1094        out.push(':');
1095        value.render_into(&mut out);
1096    }
1097    out.push('}');
1098    out
1099}
1100
1101// ---------------------------------------------------------------------------
1102// The kernel (R.2)
1103// ---------------------------------------------------------------------------
1104
1105struct Kernel<'a> {
1106    /// The accepted set: one act per address, in slice order.
1107    acts: Vec<&'a Act>,
1108    /// Domain filters resolved against the opener: `(verb, key) → allowed`.
1109    domains: Vec<(String, String, Vec<Value>)>,
1110}
1111
1112/// The accepted set as a slice presents it: one act per content address,
1113/// first occurrence kept. A store keyed by address never holds two, so
1114/// this is the identity on a store's contents; on an arbitrary slice it
1115/// is what makes `fold` a set function of the slice itself (SPEC-019 R7,
1116/// REQ-1930 `fold_dedup_invariant`).
1117fn dedup_by_address(acts: &[Act]) -> Vec<&Act> {
1118    let mut seen: hashbrown::HashSet<&str> = hashbrown::HashSet::new();
1119    acts.iter()
1120        .filter(|a| seen.insert(a.address.as_str()))
1121        .collect()
1122}
1123
1124/// The signer's live writes, using the fold's accepted set and domains.
1125/// SPEC-019 REQ-1933/1934: supersession requires the same verb and signer.
1126pub(crate) fn current_by_signer<'a>(
1127    clause: &StateClause,
1128    acts: &'a [Act],
1129    verb: &str,
1130) -> Vec<&'a Act> {
1131    kernel_for(clause, acts).current_by_signer(verb)
1132}
1133
1134/// The binder and fold share domain-aware keyed replacement selection.
1135/// Excluded acts contribute neither values nor retirement references.
1136pub(crate) fn current_writes<'a>(
1137    clause: &StateClause,
1138    acts: &'a [Act],
1139    verb: &str,
1140    key: Option<&str>,
1141    delete: Option<&str>,
1142) -> Vec<&'a Act> {
1143    kernel_for(clause, acts).current(verb, key, delete)
1144}
1145
1146fn kernel_for<'a>(clause: &StateClause, acts: &'a [Act]) -> Kernel<'a> {
1147    // Domains read a list-valued field defined over the opener only, so
1148    // resolve them first with no domain in force.
1149    let set = dedup_by_address(acts);
1150    let bare = Kernel {
1151        acts: set.clone(),
1152        domains: Vec::new(),
1153    };
1154    let mut domains = Vec::new();
1155    for (verb, key, field) in clause.domains() {
1156        let allowed = match clause.rule_of(field) {
1157            Some(rule) => match bare.eval(rule, &[], None) {
1158                Value::List(items) => items,
1159                Value::Set(items) => items,
1160                _ => Vec::new(),
1161            },
1162            None => Vec::new(),
1163        };
1164        domains.push((String::from(verb), String::from(key), allowed));
1165    }
1166    Kernel { acts: set, domains }
1167}
1168
1169impl<'a> Kernel<'a> {
1170    fn field(&self, act: &Act, key: &str) -> Option<Value> {
1171        act.fields.get(key).map(Value::from_sexpr)
1172    }
1173
1174    /// `acts v`: the accepted acts of a verb, minus those a domain excludes.
1175    fn acts(&self, verb: &str) -> Vec<&'a Act> {
1176        self.acts
1177            .iter()
1178            .copied()
1179            .filter(|a| a.verb == verb)
1180            .filter(|a| {
1181                self.domains.iter().all(|(v, key, allowed)| {
1182                    if v != verb {
1183                        return true;
1184                    }
1185                    match self.field(a, key) {
1186                        Some(val) => {
1187                            let r = val.render();
1188                            allowed.iter().any(|x| x.render() == r)
1189                        }
1190                        None => false,
1191                    }
1192                })
1193            })
1194            .collect()
1195    }
1196
1197    /// `current v kk d`: the writes of `v` no accepted write or deletion of
1198    /// the same key names in `:replaces`.
1199    fn current(&self, verb: &str, key: Option<&str>, delete: Option<&str>) -> Vec<&'a Act> {
1200        let writes = self.acts(verb);
1201        let mut replacers: Vec<&Act> = writes.clone();
1202        if let Some(d) = delete {
1203            replacers.extend(self.acts(d));
1204        }
1205        let key_of = |a: &Act| -> String {
1206            match key {
1207                Some(k) => self.field(a, k).map(|v| v.render()).unwrap_or_default(),
1208                None => String::new(),
1209            }
1210        };
1211        let mut replaced: BTreeSet<(String, String)> = BTreeSet::new();
1212        for r in &replacers {
1213            if let Some(SExpr::List(items)) = r.fields.get(RESERVED_REPLACES) {
1214                let k = key_of(r);
1215                for item in items {
1216                    if let SExpr::Atom(Atom::Symbol(a)) | SExpr::Atom(Atom::Str(a)) = item {
1217                        replaced.insert((k.clone(), a.clone()));
1218                    }
1219                }
1220            }
1221        }
1222        writes
1223            .into_iter()
1224            .filter(|w| !replaced.contains(&(key_of(w), w.address.clone())))
1225            .collect()
1226    }
1227
1228    /// Current writes under signer-owned replacement addresses.
1229    fn current_by_signer(&self, verb: &str) -> Vec<&'a Act> {
1230        let writes = self.acts(verb);
1231        let mut replaced: BTreeSet<(&str, &str)> = BTreeSet::new();
1232        for r in &writes {
1233            if let Some(SExpr::List(items)) = r.fields.get(RESERVED_REPLACES) {
1234                for item in items {
1235                    if let SExpr::Atom(Atom::Symbol(address)) | SExpr::Atom(Atom::Str(address)) =
1236                        item
1237                    {
1238                        replaced.insert((r.signer.as_str(), address.as_str()));
1239                    }
1240                }
1241            }
1242        }
1243        writes
1244            .into_iter()
1245            .filter(|w| !replaced.contains(&(w.signer.as_str(), w.address.as_str())))
1246            .collect()
1247    }
1248
1249    /// Read the sole initializer. No opener has no value; two or more
1250    /// distinct openers are the conflict top, rendered as a fault naming
1251    /// them (SPEC-038 REQ-3804, ADR-3803). The display is therefore
1252    /// monotone: absent, then a value, then fault, never back.
1253    fn initial(&self, table: &[&Act], key: &str) -> Value {
1254        match table {
1255            [] => Value::Absent,
1256            [act] => self.field(act, key).unwrap_or(Value::Absent),
1257            many => conflict_top(
1258                "opener fork",
1259                many.iter().map(|a| a.address.clone()).collect(),
1260            ),
1261        }
1262    }
1263
1264    /// `group T g` by signer.
1265    fn group_by_signer<'b>(&self, table: &[&'b Act]) -> BTreeMap<String, Vec<&'b Act>> {
1266        let mut out: BTreeMap<String, Vec<&Act>> = BTreeMap::new();
1267        for a in table {
1268            out.entry(a.signer.clone()).or_default().push(a);
1269        }
1270        out
1271    }
1272
1273    /// `group T g` by a key field: rendering → (key value, acts).
1274    fn group_by_key<'b>(&self, table: &[&'b Act], key: &str) -> Vec<(Value, Vec<&'b Act>)> {
1275        let mut out: BTreeMap<Vec<u8>, (Value, Vec<&Act>)> = BTreeMap::new();
1276        for a in table {
1277            if let Some(k) = self.field(a, key) {
1278                out.entry(k.render().into_bytes())
1279                    .or_insert_with(|| (k.clone(), Vec::new()))
1280                    .1
1281                    .push(a);
1282            }
1283        }
1284        out.into_values().collect()
1285    }
1286
1287    /// `distinct T k`.
1288    fn distinct(&self, table: &[&Act], key: &str) -> Value {
1289        Value::Set(sorted_distinct(
1290            table.iter().filter_map(|a| self.field(a, key)).collect(),
1291        ))
1292    }
1293
1294    /// `sum T k` over integer fields.
1295    fn sum(&self, table: &[&Act], key: &str) -> i128 {
1296        table
1297            .iter()
1298            .filter_map(|a| self.field(a, key))
1299            .filter_map(|v| v.as_int())
1300            .sum()
1301    }
1302
1303    /// One rule, by the sugar table of R.2.
1304    /// Select only canonical HLC candidates. Ties are signer, then address.
1305    /// Low-level fold stays total; receipt/intent enforce clock shape separately.
1306    fn pick_lww(&self, acts: &[&Act], key: &str, clock: &str) -> Value {
1307        acts.iter()
1308            .filter_map(|a| {
1309                let SExpr::Atom(Atom::Str(text)) = a.fields.get(clock)? else {
1310                    return None;
1311                };
1312                let timestamp = crate::hlc::Hlc::parse(text)?;
1313                Some(((timestamp, a.signer.as_str(), a.address.as_str()), *a))
1314            })
1315            .max_by(|(x, _), (y, _)| x.cmp(y))
1316            .map(|(_, a)| self.field(a, key).unwrap_or(Value::Absent))
1317            .unwrap_or(Value::Absent)
1318    }
1319
1320    fn eval(
1321        &self,
1322        rule: &Rule,
1323        done: &[(String, Value)],
1324        protocol: Option<&CausalProtocol>,
1325    ) -> Value {
1326        match rule {
1327            Rule::Context { path, definition } => definition
1328                .as_ref()
1329                .map(|d| {
1330                    d.read(
1331                        path,
1332                        &self.acts.iter().map(|a| (*a).clone()).collect::<Vec<_>>(),
1333                    )
1334                })
1335                .unwrap_or(Value::Absent),
1336            Rule::Lift(lift) => lift.evaluate(self.acts(&lift.verb)),
1337            Rule::BoundedCounter(c) => crate::escrow::observe(
1338                c,
1339                &self.acts.iter().map(|a| (*a).clone()).collect::<Vec<_>>(),
1340            )
1341            .value(),
1342            Rule::LwwRegister { verb, key, clock } => self.pick_lww(&self.acts(verb), key, clock),
1343            Rule::LwwPerSigner { verb, key, clock } => Value::Map(
1344                self.group_by_signer(&self.current_by_signer(verb))
1345                    .into_iter()
1346                    .map(|(s, t)| (Value::Str(s), self.pick_lww(&t, key, clock)))
1347                    .collect(),
1348            ),
1349            Rule::LwwMap {
1350                verb,
1351                key,
1352                value,
1353                clock,
1354                delete,
1355            } => Value::Map(
1356                self.group_by_key(&self.current(verb, Some(key), delete.as_deref()), key)
1357                    .into_iter()
1358                    .map(|(k, t)| (k, self.pick_lww(&t, value, clock)))
1359                    .collect(),
1360            ),
1361            Rule::Initial { verb, key } => self.initial(
1362                &self
1363                    .acts
1364                    .iter()
1365                    .copied()
1366                    .filter(|a| a.verb == *verb)
1367                    .collect::<Vec<_>>(),
1368                key,
1369            ),
1370
1371            Rule::Exists { verb } => Value::Bool(!self.acts(verb).is_empty()),
1372            Rule::Count { verb } => Value::Int(self.acts(verb).len() as i128),
1373            Rule::Progress { verb } => {
1374                let positions = protocol
1375                    .map(|p| crate::repeat::accepted_positions(p, verb, &self.acts))
1376                    .unwrap_or_default();
1377                Value::Int(positions.into_iter().max().unwrap_or(0) as i128)
1378            }
1379            Rule::Events { verb, key } => {
1380                let mut entries: Vec<(Value, Value)> = self
1381                    .acts(verb)
1382                    .into_iter()
1383                    .filter_map(|a| {
1384                        self.field(a, key).map(|v| {
1385                            (
1386                                Value::Str(a.address.clone()),
1387                                Value::Pair {
1388                                    by: a.signer.clone(),
1389                                    value: alloc::boxed::Box::new(v),
1390                                },
1391                            )
1392                        })
1393                    })
1394                    .collect();
1395                entries.sort_by(|a, b| a.0.render().as_bytes().cmp(b.0.render().as_bytes()));
1396                Value::Map(entries)
1397            }
1398            Rule::SetUnion { verb, key } => self.distinct(&self.acts(verb), key),
1399            Rule::Values { verb, key } => self.distinct(&self.current(verb, None, None), key),
1400            Rule::ValuesPerKey {
1401                verb,
1402                key,
1403                value,
1404                delete,
1405            } => Value::Map(
1406                self.group_by_key(&self.current(verb, Some(key), delete.as_deref()), key)
1407                    .into_iter()
1408                    .map(|(k, t)| (k, self.distinct(&t, value)))
1409                    .collect(),
1410            ),
1411
1412            Rule::ObservedSet { add, remove, key } => {
1413                self.distinct(&self.current(add, Some(key), Some(remove)), key)
1414            }
1415            Rule::Counter { inc, dec, key } => {
1416                Value::Int(self.sum(&self.acts(inc), key) - self.sum(&self.acts(dec), key))
1417            }
1418            Rule::Histogram { field } => {
1419                let mut counts: BTreeMap<Vec<u8>, (Value, i128)> = BTreeMap::new();
1420                if let Some((_, Value::Map(entries))) = done.iter().find(|(n, _)| n == field) {
1421                    for (_, v) in entries {
1422                        let v = match v {
1423                            Value::Pair { value, .. } => (**value).clone(),
1424                            other => other.clone(),
1425                        };
1426                        if v == Value::Absent {
1427                            continue;
1428                        }
1429                        counts
1430                            .entry(v.render().into_bytes())
1431                            .or_insert_with(|| (v.clone(), 0))
1432                            .1 += 1;
1433                    }
1434                }
1435                Value::Map(
1436                    counts
1437                        .into_values()
1438                        .map(|(v, n)| (v, Value::Int(n)))
1439                        .collect(),
1440                )
1441            }
1442            Rule::Sum { field } => {
1443                let total = match done.iter().find(|(n, _)| n == field) {
1444                    Some((_, Value::Map(entries))) => {
1445                        entries.iter().filter_map(|(_, v)| v.as_int()).sum()
1446                    }
1447                    _ => 0,
1448                };
1449                Value::Int(total)
1450            }
1451        }
1452    }
1453}
1454
1455/// The fold (SPEC-019 R.2): every field of the clause over the accepted
1456/// acts, in clause order. Total on any finite slice; a set function of it.
1457pub fn fold(
1458    clause: &StateClause,
1459    protocol: Option<&CausalProtocol>,
1460    acts: &[Act],
1461) -> Vec<(String, Value)> {
1462    if clause.freezes().next().is_some() {
1463        return crate::freeze::fold(clause, protocol, acts);
1464    }
1465    fold_unfrozen(clause, protocol, acts)
1466}
1467
1468pub(crate) fn fold_unfrozen(
1469    clause: &StateClause,
1470    protocol: Option<&CausalProtocol>,
1471    acts: &[Act],
1472) -> Vec<(String, Value)> {
1473    let mut done: Vec<(String, Value)> = Vec::new();
1474    let ctx = crate::lattice::Ctx::with_protocol(clause, acts, protocol);
1475    for entry in &clause.entries {
1476        match entry {
1477            Entry::Field { name, rule } => {
1478                let v = crate::lattice::factor(rule)
1479                    .map(|f| ctx.display(&f, &done))
1480                    .unwrap_or(Value::Absent);
1481                done.push((name.clone(), v));
1482            }
1483            Entry::Condition { name, condition } => {
1484                let value = condition.evaluate(&mut |field, element| {
1485                    threshold_read(&ctx, clause, field, core::slice::from_ref(element), &done)
1486                });
1487                done.push((name.clone(), value));
1488            }
1489            Entry::Domain { .. } | Entry::Freeze { .. } | Entry::Lattice(_) => {}
1490            Entry::Threshold {
1491                name,
1492                field,
1493                elements,
1494            } => {
1495                let v = threshold_read(&ctx, clause, field, elements, &done);
1496                done.push((name.clone(), v));
1497            }
1498        }
1499    }
1500    done
1501}
1502
1503/// Independent pre-factorization evaluator for legacy conformance checks.
1504/// New threshold/freeze declarations are exercised by their dedicated suites.
1505#[doc(hidden)]
1506pub fn fold_reference(
1507    clause: &StateClause,
1508    protocol: Option<&CausalProtocol>,
1509    acts: &[Act],
1510) -> Vec<(String, Value)> {
1511    let kernel = kernel_for(clause, acts);
1512    let ctx = crate::lattice::Ctx::with_protocol(clause, acts, protocol);
1513    let mut done: Vec<(String, Value)> = Vec::new();
1514    for entry in &clause.entries {
1515        match entry {
1516            Entry::Field { name, rule } => {
1517                let fault = ctx.rule_fault(rule).or_else(|| match rule {
1518                    Rule::Histogram { field } | Rule::Sum { field } => done
1519                        .iter()
1520                        .find(|(n, _)| n == field)
1521                        .filter(|(_, v)| v.fault_evidence().is_some())
1522                        .map(|(_, v)| v.clone()),
1523                    _ => None,
1524                });
1525                let value = fault.unwrap_or_else(|| match rule {
1526                    Rule::BoundedCounter(c) => crate::escrow::observe(c, acts).value(),
1527                    Rule::Lift(lift) => {
1528                        let value = kernel.eval(rule, &done, protocol);
1529                        if let Some(mut evidence) = value.fault_evidence() {
1530                            evidence.extend(domain_support_addresses(
1531                                clause,
1532                                acts,
1533                                core::slice::from_ref(&lift.verb),
1534                            ));
1535                            conflict_top("finite lattice conflict", evidence)
1536                        } else {
1537                            value
1538                        }
1539                    }
1540                    _ => kernel.eval(rule, &done, protocol),
1541                });
1542                done.push((name.clone(), value));
1543            }
1544            Entry::Threshold {
1545                name,
1546                field,
1547                elements,
1548            } => {
1549                let value = threshold_read(&ctx, clause, field, elements, &done);
1550                done.push((name.clone(), value));
1551            }
1552            Entry::Condition { name, condition } => {
1553                let value = condition.evaluate(&mut |field, element| {
1554                    threshold_read(&ctx, clause, field, core::slice::from_ref(element), &done)
1555                });
1556                done.push((name.clone(), value));
1557            }
1558            _ => {}
1559        }
1560    }
1561    done
1562}
1563
1564/// Evaluate one field in a causal scope. Dependency values are supplied in
1565/// clause order; the freeze evaluator memoizes these scoped evaluations.
1566pub(crate) fn scoped_rule(
1567    clause: &StateClause,
1568    protocol: Option<&CausalProtocol>,
1569    acts: &[Act],
1570    rule: &Rule,
1571    done: &[(String, Value)],
1572) -> Value {
1573    let ctx = crate::lattice::Ctx::with_protocol(clause, acts, protocol);
1574    crate::lattice::factor(rule)
1575        .map(|f| ctx.display(&f, done))
1576        .unwrap_or(Value::Absent)
1577}
1578
1579/// Closure projections share the history carrier, retaining their existing
1580/// protocol-position and escrow validators as pure native algorithms.
1581pub(crate) fn closure_value(
1582    clause: &StateClause,
1583    protocol: Option<&CausalProtocol>,
1584    acts: &[Act],
1585    rule: &Rule,
1586) -> Value {
1587    match rule {
1588        Rule::Context { path, definition } => definition
1589            .as_ref()
1590            .map(|d| d.read(path, acts))
1591            .unwrap_or(Value::Absent),
1592        Rule::Progress { .. } => kernel_for(clause, acts).eval(rule, &[], protocol),
1593        Rule::BoundedCounter(c) => crate::escrow::observe(c, acts).value(),
1594        _ => Value::Absent,
1595    }
1596}
1597
1598/// Context needed to replay domain-filtered source writes from a fault witness.
1599pub(crate) fn domain_support_addresses(
1600    clause: &StateClause,
1601    acts: &[Act],
1602    verbs: &[String],
1603) -> hashbrown::HashSet<String> {
1604    let mut support = hashbrown::HashSet::new();
1605    for (_, _, field) in clause
1606        .domains()
1607        .filter(|(verb, _, _)| verbs.iter().any(|v| v == verb))
1608    {
1609        match clause.rule_of(field) {
1610            Some(Rule::Initial { verb, .. }) => {
1611                support.extend(
1612                    acts.iter()
1613                        .filter(|a| a.verb == *verb)
1614                        .map(|a| a.address.clone()),
1615                );
1616            }
1617            Some(Rule::Context {
1618                definition: Some(_),
1619                ..
1620            }) => {
1621                support.extend(
1622                    acts.iter()
1623                        .filter(|a| a.predecessors.is_empty())
1624                        .map(|a| a.address.clone()),
1625                );
1626            }
1627            _ => {}
1628        }
1629    }
1630    support
1631}
1632
1633pub(crate) fn contribution_addresses(
1634    clause: &StateClause,
1635    acts: &[Act],
1636    verbs: &[String],
1637) -> hashbrown::HashSet<String> {
1638    // A field also depends on its domain's initializer or sealed roster root.
1639    // A freezer missing that support must fault/supersede it, rather than make
1640    // an already reached threshold pending when the domain disappears at cut.
1641    let mut support = hashbrown::HashSet::new();
1642    // Freeze witnesses must survive a later initializer fork. Retain every
1643    // contribution admitted by any observed initializer, rather than applying
1644    // the now-faulting domain's empty successful display.
1645    let domains: Vec<(&str, &str, hashbrown::HashSet<String>)> = clause
1646        .domains()
1647        .filter(|(verb, _, _)| verbs.iter().any(|v| v == verb))
1648        .map(|(verb, key, field)| {
1649            let mut allowed = hashbrown::HashSet::new();
1650            if let Some(Rule::Initial {
1651                verb: opener,
1652                key: source,
1653            }) = clause.rule_of(field)
1654            {
1655                for act in acts.iter().filter(|a| a.verb == *opener) {
1656                    support.insert(act.address.clone());
1657                    if let Some(SExpr::List(values)) = act.fields.get(source) {
1658                        allowed.extend(values.iter().map(|v| Value::from_sexpr(v).render()));
1659                    }
1660                }
1661            }
1662            if let Some(Rule::Context {
1663                path,
1664                definition: Some(metadata),
1665            }) = clause.rule_of(field)
1666            {
1667                for root in acts.iter().filter(|a| a.predecessors.is_empty()) {
1668                    support.insert(root.address.clone());
1669                    if let Value::Set(members) = metadata.read(path, core::slice::from_ref(root)) {
1670                        allowed.extend(members.iter().map(Value::render));
1671                    }
1672                }
1673            }
1674            (verb, key, allowed)
1675        })
1676        .collect();
1677    let writers: hashbrown::HashSet<String> = acts
1678        .iter()
1679        .filter(|a| verbs.contains(&a.verb))
1680        .filter(|a| {
1681            domains.iter().all(|(verb, key, allowed)| {
1682                a.verb != *verb
1683                    || a.fields
1684                        .get(*key)
1685                        .is_some_and(|v| allowed.contains(&Value::from_sexpr(v).render()))
1686            })
1687        })
1688        .map(|a| a.address.clone())
1689        .collect();
1690    support.extend(writers);
1691    support
1692}
1693
1694/// A threshold read (SPEC-038 REQ-3802, CON-3801): the unique element of the
1695/// declared set at or below the field's carrier element, or `pending`.
1696/// Uniqueness is what installation's pairwise-incompatibility check buys, so
1697/// the first reached element is the only one. A lift's carrier element is
1698/// evaluated by the lattice context; a closure head's position or ⊤ is read
1699/// from its display (REQ-3808).
1700pub(crate) fn threshold_read(
1701    ctx: &crate::lattice::Ctx<'_>,
1702    clause: &StateClause,
1703    field: &str,
1704    elements: &[crate::lattice::Element],
1705    done: &[(String, Value)],
1706) -> Value {
1707    if let Some((_, fault)) = done
1708        .iter()
1709        .find(|(n, v)| n == field && v.fault_evidence().is_some())
1710    {
1711        return fault.clone();
1712    }
1713    let reached = match clause.rule_of(field).map(crate::lattice::factor) {
1714        Some(Some(f)) if matches!(f.post, crate::lattice::Post::Closure(_)) => done
1715            .iter()
1716            .find(|(n, _)| n == field)
1717            .and_then(|(_, shown)| elements.iter().find(|e| e.le_display(shown.unfrozen()))),
1718        Some(Some(f)) => {
1719            let sigma = ctx.read_carrier(&f.term);
1720            elements.iter().find(|e| e.le_with_post(&sigma, &f.post))
1721        }
1722        Some(None) => done
1723            .iter()
1724            .find(|(n, _)| n == field)
1725            .and_then(|(_, shown)| elements.iter().find(|e| e.le_display(shown.unfrozen()))),
1726        None => None,
1727    };
1728    let status = |s: &str| {
1729        (
1730            Value::Str(String::from("status")),
1731            Value::Str(String::from(s)),
1732        )
1733    };
1734    match reached {
1735        Some(e) => Value::Map(alloc::vec![
1736            (Value::Str(String::from("element")), e.render()),
1737            status("reached"),
1738        ]),
1739        None => Value::Map(alloc::vec![status("pending")]),
1740    }
1741}
1742
1743// ---------------------------------------------------------------------------
1744// State schema (R.7 `state_schema`)
1745// ---------------------------------------------------------------------------
1746
1747/// Scalar types of state-bearing fields.
1748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1749pub enum ScalarType {
1750    Str,
1751    Hlc,
1752    Int,
1753    Float,
1754    Decimal,
1755    Number,
1756    Value,
1757    Bool,
1758    /// A list of scalars (a `list` shape type).
1759    List,
1760}
1761
1762impl ScalarType {
1763    pub fn from_constraint(tc: &TypeConstraint) -> Option<ScalarType> {
1764        match tc {
1765            TypeConstraint::Float => Some(ScalarType::Float),
1766            TypeConstraint::Decimal => Some(ScalarType::Decimal),
1767            TypeConstraint::String => Some(ScalarType::Str),
1768            TypeConstraint::Hlc => Some(ScalarType::Hlc),
1769            TypeConstraint::Integer | TypeConstraint::Nonnegative => Some(ScalarType::Int),
1770            TypeConstraint::Number => Some(ScalarType::Number),
1771            TypeConstraint::Contract(c) => c
1772                .representation()
1773                .as_ref()
1774                .and_then(Self::from_constraint)
1775                .or(Some(ScalarType::Value)),
1776            TypeConstraint::Bool => Some(ScalarType::Bool),
1777            TypeConstraint::List => Some(ScalarType::List),
1778            TypeConstraint::Symbol | TypeConstraint::Keyword => None,
1779        }
1780    }
1781
1782    pub fn as_str(&self) -> &'static str {
1783        match self {
1784            ScalarType::Str => "string",
1785            ScalarType::Hlc => "hlc",
1786            ScalarType::Float => "float",
1787            ScalarType::Decimal => "decimal",
1788            ScalarType::Int => "integer",
1789            ScalarType::Number => "number",
1790            ScalarType::Value => "value",
1791            ScalarType::Bool => "bool",
1792            ScalarType::List => "list",
1793        }
1794    }
1795}
1796
1797/// The type of a state field, derived from its rule and the shapes.
1798#[derive(Debug, Clone, PartialEq, Eq)]
1799pub enum StateType {
1800    Object(Vec<(String, StateType)>),
1801    /// Immutable installed metadata or a sealed thread-context projection.
1802    Context(alloc::boxed::Box<StateType>),
1803    /// A current observation. A declared freezer can later produce an exact cut.
1804    Snapshot {
1805        value: alloc::boxed::Box<StateType>,
1806        freeze: Option<(String, FreezePolicy)>,
1807    },
1808    BoundedCounter,
1809    /// A value that may be absent (`last`).
1810    OptScalar(ScalarType),
1811    Int,
1812    Bool,
1813    Set(ScalarType),
1814    /// A map from a key type to values.
1815    Map(ScalarType, alloc::boxed::Box<StateType>),
1816    /// `events`: address → `{by, value}`.
1817    Events(ScalarType),
1818    /// `histogram`: value → count.
1819    Histogram(ScalarType),
1820    /// The referenced field's type could not be derived.
1821    Unknown,
1822    /// Boolean condition threshold (SPEC-038 CON-3805).
1823    Condition(Condition),
1824    /// A threshold read over `field` (SPEC-038 CON-3801).
1825    Threshold {
1826        field: String,
1827        elements: Vec<crate::lattice::Element>,
1828    },
1829}
1830
1831impl StateType {
1832    /// JSON rendering of a type, for the export.
1833    pub fn render(&self) -> String {
1834        match self {
1835            StateType::Object(fields) => format!(
1836                "{{\"type\":\"object\",\"fields\":{}}}",
1837                render_schema(fields)
1838            ),
1839            StateType::Context(value) => {
1840                let mut out = value.render();
1841                out.pop();
1842                out.push_str(",\"observation\":\"context\"}");
1843                out
1844            }
1845            StateType::Snapshot { value, freeze } => {
1846                let mut out = value.render();
1847                out.pop();
1848                out.push_str(",\"observation\":\"snapshot\"");
1849                if let Some((verb, policy)) = freeze {
1850                    out.push_str(",\"freeze\":{\"verb\":");
1851                    json_string(verb, &mut out);
1852                    out.push_str(",\"policy\":");
1853                    json_string(policy.as_str(), &mut out);
1854                    out.push('}');
1855                }
1856                out.push('}');
1857                out
1858            }
1859            StateType::Condition(condition) => format!(
1860                "{{\"type\":\"threshold\",\"of\":\"bool\",\"condition\":{}}}",
1861                condition.schema().render()
1862            ),
1863            StateType::Threshold { field, elements } => {
1864                let mut out = String::from("{\"type\":\"threshold\",\"field\":");
1865                json_string(field, &mut out);
1866                out.push_str(",\"elements\":[");
1867                for (i, e) in elements.iter().enumerate() {
1868                    if i > 0 {
1869                        out.push(',');
1870                    }
1871                    out.push_str(&e.render().render());
1872                }
1873                out.push_str("]}");
1874                out
1875            }
1876            StateType::BoundedCounter => String::from("{\"type\":\"bounded-counter\"}"),
1877            StateType::OptScalar(t) => {
1878                format!("{{\"type\":\"opt-scalar\",\"of\":\"{}\"}}", t.as_str())
1879            }
1880            StateType::Int => String::from("{\"type\":\"int\"}"),
1881            StateType::Bool => String::from("{\"type\":\"bool\"}"),
1882            StateType::Set(t) => format!("{{\"type\":\"set\",\"of\":\"{}\"}}", t.as_str()),
1883            StateType::Map(k, v) => {
1884                format!(
1885                    "{{\"type\":\"map\",\"key\":\"{}\",\"value\":{}}}",
1886                    k.as_str(),
1887                    v.render()
1888                )
1889            }
1890            StateType::Events(t) => format!("{{\"type\":\"events\",\"of\":\"{}\"}}", t.as_str()),
1891            StateType::Histogram(t) => {
1892                format!("{{\"type\":\"histogram\",\"of\":\"{}\"}}", t.as_str())
1893            }
1894            StateType::Unknown => String::from("{\"type\":\"unknown\"}"),
1895        }
1896    }
1897}
1898
1899/// The declared type of `(verb, key)` from the dialect's shapes.
1900pub fn field_type(
1901    shapes: &[crate::shape::ShapeConstraint],
1902    verb: &str,
1903    key: &str,
1904) -> Option<TypeConstraint> {
1905    for shape in shapes.iter().filter(|s| s.performative == verb) {
1906        for rule in &shape.rules {
1907            match rule {
1908                ShapeRule::Require {
1909                    keyword,
1910                    type_constraint,
1911                    ..
1912                }
1913                | ShapeRule::Optional {
1914                    keyword,
1915                    type_constraint,
1916                    ..
1917                } => {
1918                    if keyword == key {
1919                        return type_constraint
1920                            .as_ref()
1921                            .and_then(TypeConstraint::representation);
1922                    }
1923                }
1924                ShapeRule::MaxDepth(_) => {}
1925            }
1926        }
1927    }
1928    None
1929}
1930
1931/// `state_schema` (R.7): each field's type from its rule and the shapes.
1932pub fn state_schema(
1933    clause: &StateClause,
1934    shapes: &[crate::shape::ShapeConstraint],
1935) -> Vec<(String, StateType)> {
1936    let scalar = |verb: &str, key: &str| -> ScalarType {
1937        field_type(shapes, verb, key)
1938            .as_ref()
1939            .and_then(ScalarType::from_constraint)
1940            .unwrap_or(ScalarType::Str)
1941    };
1942    let mut out: Vec<(String, StateType)> = Vec::new();
1943    for entry in &clause.entries {
1944        let (name, rule) = match entry {
1945            Entry::Field { name, rule } => (name, rule),
1946            Entry::Condition { name, condition } => {
1947                out.push((name.clone(), StateType::Condition(condition.clone())));
1948                continue;
1949            }
1950            Entry::Domain { .. } | Entry::Freeze { .. } | Entry::Lattice(_) => continue,
1951            Entry::Threshold {
1952                name,
1953                field,
1954                elements,
1955            } => {
1956                out.push((
1957                    name.clone(),
1958                    StateType::Threshold {
1959                        field: field.clone(),
1960                        elements: elements.clone(),
1961                    },
1962                ));
1963                continue;
1964            }
1965        };
1966        let ty = match rule {
1967            Rule::Context { path, .. } => crate::context::schema(path),
1968            Rule::Lift(lift) => match &lift.projection {
1969                None => StateType::OptScalar(ScalarType::Str),
1970                Some(p)
1971                    if p.rows
1972                        .iter()
1973                        .all(|(_, v)| matches!(v, SExpr::Atom(Atom::Bool(_)))) =>
1974                {
1975                    StateType::Bool
1976                }
1977                Some(p)
1978                    if p.rows
1979                        .iter()
1980                        .all(|(_, v)| matches!(v, SExpr::Atom(Atom::Num(_)))) =>
1981                {
1982                    StateType::Int
1983                }
1984                Some(p)
1985                    if p.rows
1986                        .iter()
1987                        .all(|(_, v)| matches!(v, SExpr::Atom(Atom::Str(_)))) =>
1988                {
1989                    StateType::OptScalar(ScalarType::Str)
1990                }
1991                Some(_) => StateType::Unknown,
1992            },
1993            Rule::BoundedCounter(_) => StateType::BoundedCounter,
1994            Rule::Initial { verb, key } | Rule::LwwRegister { verb, key, .. } => {
1995                StateType::OptScalar(scalar(verb, key))
1996            }
1997            Rule::LwwPerSigner { verb, key, .. } => StateType::Map(
1998                ScalarType::Str,
1999                alloc::boxed::Box::new(StateType::OptScalar(scalar(verb, key))),
2000            ),
2001            Rule::LwwMap {
2002                verb, key, value, ..
2003            } => StateType::Map(
2004                scalar(verb, key),
2005                alloc::boxed::Box::new(StateType::OptScalar(scalar(verb, value))),
2006            ),
2007            Rule::Exists { .. } => StateType::Bool,
2008            Rule::Count { .. }
2009            | Rule::Progress { .. }
2010            | Rule::Counter { .. }
2011            | Rule::Sum { .. } => StateType::Int,
2012            Rule::Events { verb, key } => StateType::Events(scalar(verb, key)),
2013            Rule::SetUnion { verb, key } | Rule::Values { verb, key } => {
2014                StateType::Set(scalar(verb, key))
2015            }
2016            Rule::ValuesPerKey {
2017                verb, key, value, ..
2018            } => StateType::Map(
2019                scalar(verb, key),
2020                alloc::boxed::Box::new(StateType::Set(scalar(verb, value))),
2021            ),
2022            Rule::ObservedSet { add, key, .. } => StateType::Set(scalar(add, key)),
2023            Rule::Histogram { field } => {
2024                let of = out.iter().find(|(n, _)| n == field).map(|(_, t)| t.clone());
2025                match of {
2026                    Some(StateType::Map(_, v)) => match *v {
2027                        StateType::OptScalar(t) => StateType::Histogram(t),
2028                        _ => StateType::Unknown,
2029                    },
2030                    _ => StateType::Unknown,
2031                }
2032            }
2033        };
2034        out.push((String::from(name), ty));
2035    }
2036    out.into_iter()
2037        .map(|(name, ty)| {
2038            if matches!(ty, StateType::Threshold { .. } | StateType::Condition(_)) {
2039                (name, ty)
2040            } else if matches!(clause.rule_of(&name),Some(Rule::Context {path,..}) if crate::context::stable_path(path)) {
2041                (name,StateType::Context(alloc::boxed::Box::new(ty)))
2042            } else {
2043                let freeze = clause
2044                    .freezes()
2045                    .find(|(field, _, _)| *field == name)
2046                    .map(|(_, verb, policy)| (verb.to_string(), policy));
2047                (
2048                    name,
2049                    StateType::Snapshot {
2050                        value: alloc::boxed::Box::new(ty),
2051                        freeze,
2052                    },
2053                )
2054            }
2055        })
2056        .collect()
2057}
2058
2059/// JSON rendering of a schema.
2060pub fn render_schema(schema: &[(String, StateType)]) -> String {
2061    let mut out = String::from("{");
2062    for (i, (name, ty)) in schema.iter().enumerate() {
2063        if i > 0 {
2064            out.push(',');
2065        }
2066        json_string(name, &mut out);
2067        out.push(':');
2068        out.push_str(&ty.render());
2069    }
2070    out.push('}');
2071    out
2072}
2073
2074#[cfg(test)]
2075mod tests {
2076    use super::*;
2077    use crate::message::{Performative, Recipients};
2078
2079    fn act(addr: &str, verb: &str, signer: &str, preds: &[&str], fields: &[(&str, SExpr)]) -> Act {
2080        let mut params = Vec::new();
2081        for (k, v) in fields {
2082            params.push(SExpr::Atom(Atom::Keyword(String::from(*k))));
2083            params.push(v.clone());
2084        }
2085        params.push(SExpr::Atom(Atom::Keyword("clock".into())));
2086        params.push(SExpr::Atom(Atom::Str(
2087            "hlc-0000000000000000-00000000".into(),
2088        )));
2089        let message = Message::Simple {
2090            performative: Performative::Custom(String::from(verb)),
2091            recipient: Some(Recipients::One(String::from("@list"))),
2092            content: SExpr::List(Vec::new()),
2093            params,
2094            thread: Some(String::from("t")),
2095            sender: None,
2096            caused_by: Some(if preds.is_empty() {
2097                CausedBy::Begin
2098            } else {
2099                CausedBy::Single(String::from(preds[0]))
2100            }),
2101        };
2102        let mut a = Act::from_message(message, signer).unwrap();
2103        a.address = String::from(addr);
2104        a
2105    }
2106
2107    fn s(x: &str) -> SExpr {
2108        SExpr::Atom(Atom::Str(String::from(x)))
2109    }
2110    fn b(x: bool) -> SExpr {
2111        SExpr::Atom(Atom::Bool(x))
2112    }
2113    fn addrs(xs: &[&str]) -> SExpr {
2114        SExpr::List(
2115            xs.iter()
2116                .map(|x| SExpr::Atom(Atom::Symbol(String::from(*x))))
2117                .collect(),
2118        )
2119    }
2120
2121    fn checklist() -> StateClause {
2122        StateClause {
2123            entries: alloc::vec![
2124                Entry::Field {
2125                    name: "title".into(),
2126                    rule: Rule::Initial {
2127                        verb: "open".into(),
2128                        key: "title".into()
2129                    }
2130                },
2131                Entry::Field {
2132                    name: "items".into(),
2133                    rule: Rule::LwwMap {
2134                        verb: "check".into(),
2135                        key: "item".into(),
2136                        value: "done".into(),
2137                        delete: Some("drop".into()),
2138                        clock: "clock".into(),
2139                    },
2140                },
2141            ],
2142        }
2143    }
2144
2145    #[test]
2146    fn register_replaced_never_wins_and_delete_removes_key() {
2147        let m1 = act("f12201", "open", "@aria", &[], &[("title", s("Launch"))]);
2148        let m2 = act(
2149            "f12202",
2150            "check",
2151            "@bo",
2152            &["f12201"],
2153            &[
2154                ("item", s("venue")),
2155                ("done", b(false)),
2156                ("replaces", addrs(&[])),
2157            ],
2158        );
2159        let m3 = act(
2160            "f12203",
2161            "check",
2162            "@bo",
2163            &["f12201"],
2164            &[
2165                ("item", s("venue")),
2166                ("done", b(true)),
2167                ("replaces", addrs(&["f12202"])),
2168            ],
2169        );
2170        let m4 = act(
2171            "f12204",
2172            "drop",
2173            "@aria",
2174            &["f12201"],
2175            &[("item", s("venue")), ("replaces", addrs(&["f12203"]))],
2176        );
2177        let clause = checklist();
2178        let st = fold(&clause, None, &[m1.clone(), m2.clone(), m3.clone()]);
2179        assert_eq!(
2180            render_json(&st),
2181            "{\"title\":\"Launch\",\"items\":{\"venue\":true}}"
2182        );
2183        let st = fold(
2184            &clause,
2185            None,
2186            &[m1.clone(), m2.clone(), m3.clone(), m4.clone()],
2187        );
2188        assert_eq!(render_json(&st), "{\"title\":\"Launch\",\"items\":{}}");
2189        // permutation and duplication invariance
2190        let st2 = fold(
2191            &clause,
2192            None,
2193            &[m4.clone(), m3.clone(), m1.clone(), m2.clone(), m3.clone()],
2194        );
2195        assert_eq!(render_json(&st2), "{\"title\":\"Launch\",\"items\":{}}");
2196        // M2 missing: identical
2197        let st3 = fold(&clause, None, &[m1, m3, m4]);
2198        assert_eq!(render_json(&st3), "{\"title\":\"Launch\",\"items\":{}}");
2199    }
2200
2201    #[test]
2202    fn frontier_and_opener() {
2203        let m1 = act("f12201", "open", "@aria", &[], &[("title", s("Launch"))]);
2204        let m2 = act(
2205            "f12202",
2206            "check",
2207            "@bo",
2208            &["f12201"],
2209            &[("item", s("venue")), ("done", b(false))],
2210        );
2211        assert_eq!(
2212            frontier(&[m1.clone(), m2.clone()]),
2213            alloc::vec![String::from("f12202")]
2214        );
2215        assert_eq!(
2216            frontier(core::slice::from_ref(&m1)),
2217            alloc::vec![String::from("f12201")]
2218        );
2219    }
2220
2221    #[test]
2222    fn histogram_over_per_signer_and_domain_filter() {
2223        let clause = StateClause {
2224            entries: alloc::vec![
2225                Entry::Field {
2226                    name: "options".into(),
2227                    rule: Rule::Initial {
2228                        verb: "propose".into(),
2229                        key: "options".into()
2230                    }
2231                },
2232                Entry::Domain {
2233                    verb: "vote".into(),
2234                    key: "choice".into(),
2235                    field: "options".into()
2236                },
2237                Entry::Field {
2238                    name: "ballots".into(),
2239                    rule: Rule::LwwPerSigner {
2240                        verb: "vote".into(),
2241                        key: "choice".into(),
2242                        clock: "clock".into(),
2243                    }
2244                },
2245                Entry::Field {
2246                    name: "tally".into(),
2247                    rule: Rule::Histogram {
2248                        field: "ballots".into()
2249                    }
2250                },
2251            ],
2252        };
2253        let p = act(
2254            "f12201",
2255            "propose",
2256            "@aria",
2257            &[],
2258            &[("options", SExpr::List(alloc::vec![s("Pizza"), s("Sushi")]))],
2259        );
2260        let v1 = act(
2261            "f12202",
2262            "vote",
2263            "@bo",
2264            &["f12201"],
2265            &[("choice", s("Pizza"))],
2266        );
2267        let v2 = act(
2268            "f12203",
2269            "vote",
2270            "@bo",
2271            &["f12201"],
2272            &[("choice", s("Sushi"))],
2273        ); // greater address wins
2274        let v3 = act(
2275            "f12204",
2276            "vote",
2277            "@cy",
2278            &["f12201"],
2279            &[("choice", s("Tacos"))],
2280        ); // out of domain
2281        let st = fold(&clause, None, &[p, v1, v2, v3]);
2282        assert_eq!(
2283            render_json(&st),
2284            "{\"options\":[\"Pizza\",\"Sushi\"],\"ballots\":{\"@bo\":\"Sushi\"},\"tally\":{\"Sushi\":1}}"
2285        );
2286    }
2287
2288    #[test]
2289    fn json_escaping_is_minimal_and_lowercase() {
2290        let mut out = String::new();
2291        json_string("a\"b\\c\n\u{1}", &mut out);
2292        assert_eq!(out, "\"a\\\"b\\\\c\\n\\u0001\"");
2293    }
2294}
2295
2296#[cfg(test)]
2297mod act_identity_tests {
2298    use super::*;
2299    use crate::message::{Performative, Recipients, WrapperType};
2300    use proptest::prelude::*;
2301
2302    fn reference(act: &Act) -> Result<(), String> {
2303        if Act::from_message(act.message.clone(), &act.signer)? == *act {
2304            Ok(())
2305        } else {
2306            Err("inconsistent act identity".into())
2307        }
2308    }
2309    fn expr() -> impl Strategy<Value = SExpr> {
2310        prop_oneof![
2311            any::<i64>().prop_map(|n| SExpr::Atom(Atom::Num(n))),
2312            any::<bool>().prop_map(|v| SExpr::Atom(Atom::Bool(v))),
2313            ".{0,16}".prop_map(|s| SExpr::Atom(Atom::Symbol(s))),
2314            ".{0,16}".prop_map(|s| SExpr::Atom(Atom::Keyword(s))),
2315            ".{0,16}".prop_map(|s| SExpr::Atom(Atom::Str(s))),
2316        ]
2317        .prop_recursive(3, 32, 4, |inner| {
2318            proptest::collection::vec(inner, 0..4).prop_map(SExpr::List)
2319        })
2320    }
2321    proptest! {
2322        #[test]
2323        fn borrowed_identity_matches_owned_reconstruction(
2324            content in expr(), params in proptest::collection::vec(expr(), 0..24),
2325            replacement in expr(), verb in ".{0,16}",
2326            recipients in proptest::collection::vec(".{0,12}", 0..5),
2327            predecessors in proptest::collection::vec(".{0,12}", 0..5),
2328            thread in proptest::option::of(".{0,12}"),
2329            sender in proptest::option::of(".{0,12}"),
2330            recipient_kind in 0usize..3, cause_kind in 0usize..4,
2331            wrapper in 0usize..3, tamper in 0usize..9,
2332        ) {
2333            let recipient = match recipient_kind {
2334                0 => None,
2335                1 => Some(Recipients::One(recipients.first().cloned().unwrap_or_default())),
2336                _ => Some(Recipients::Set(recipients.into_iter().collect())),
2337            };
2338            let caused_by = match cause_kind {
2339                0 => None, 1 => Some(CausedBy::Begin),
2340                2 => Some(CausedBy::Single(predecessors.first().cloned().unwrap_or_default())),
2341                _ => Some(CausedBy::Multiple(predecessors)),
2342            };
2343            let mut message = Message::Simple {
2344                performative: Performative::Custom(verb), recipient, content,
2345                params, thread, sender, caused_by,
2346            };
2347            if wrapper == 1 {
2348                message = Message::Dialect { dialect_name: "probe".into(), inner: alloc::boxed::Box::new(message) };
2349            } else if wrapper == 2 {
2350                message = Message::Wrapped { wrapper: WrapperType::Signed,
2351                    params: alloc::vec![SExpr::Atom(Atom::Symbol("@host".into()))],
2352                    content: alloc::boxed::Box::new(message) };
2353            }
2354            let mut act = Act::from_message(message, "@host").unwrap();
2355            match tamper {
2356                1 => act.address.push('x'),
2357                2 => act.verb.push('x'),
2358                // Signer is supplied by the host, not derived from the message.
2359                3 => act.signer.push('x'),
2360                4 => act.predecessors.push("extra".into()),
2361                5 => { act.recipients.insert("extra".into()); },
2362                6 => { act.fields.insert("injected".into(), replacement); },
2363                7 => act.message = Message::Meta { dialect_def: replacement },
2364                8 => { act.fields.clear(); },
2365                _ => (),
2366            }
2367            prop_assert_eq!(act.validate_identity(), reference(&act));
2368        }
2369    }
2370    #[test]
2371    fn borrowed_identity_preserves_keyword_scan_and_duplicate_semantics() {
2372        let kw = |s: &str| SExpr::Atom(Atom::Keyword(s.into()));
2373        let cases = [
2374            alloc::vec![],
2375            alloc::vec![kw("tail")],
2376            alloc::vec![
2377                SExpr::Atom(Atom::Num(7)),
2378                kw("x"),
2379                kw("y"),
2380                kw("x"),
2381                SExpr::Atom(Atom::Num(2)),
2382                kw("tail")
2383            ],
2384            alloc::vec![
2385                kw("from"),
2386                SExpr::Atom(Atom::Symbol("@sender".into())),
2387                kw("thread"),
2388                SExpr::Atom(Atom::Str("t".into()))
2389            ],
2390        ];
2391        for params in cases {
2392            let message = Message::Simple {
2393                performative: Performative::Core(crate::message::CorePerformative::Tell),
2394                recipient: None,
2395                content: SExpr::List(alloc::vec![]),
2396                params,
2397                thread: None,
2398                sender: None,
2399                caused_by: Some(CausedBy::Multiple(alloc::vec![
2400                    "z".into(),
2401                    "a".into(),
2402                    "z".into()
2403                ])),
2404            };
2405            let mut act = Act::from_message(message, "@host").unwrap();
2406            assert_eq!(act.validate_identity(), reference(&act));
2407            assert!(act.validate_identity().is_ok());
2408            act.fields
2409                .insert("forged".into(), SExpr::Atom(Atom::Bool(true)));
2410            assert_eq!(act.validate_identity(), reference(&act));
2411            assert!(act.validate_identity().is_err());
2412        }
2413    }
2414}