Skip to main content

cbcl_core/
escrow.rs

1//! SPEC-019 CON-1907..1909: pure escrow verification over authenticated acts.
2//! Protocol admission remains independent. A ready verdict is conditional on
3//! nonforking account issuance; it does not prove absence of undisclosed forks.
4#![forbid(unsafe_code)]
5use crate::message::{Message, WrapperType};
6use crate::sexpr::{Atom, SExpr};
7use crate::state::{Act, Value};
8use alloc::collections::{BTreeMap, BTreeSet};
9use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12
13pub const PREV: &str = "escrow-prev";
14pub const DEPS: &str = "escrow-deps";
15pub const NONCE: &str = "escrow-nonce";
16
17/// The default preserves existing per-signer resource ownership.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum Ownership {
21    #[default]
22    Account,
23    Collective,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub struct CounterRule {
29    #[cfg_attr(feature = "serde", serde(default))]
30    pub ownership: Ownership,
31    #[cfg_attr(feature = "serde", serde(default))]
32    pub certification: crate::certification::Certification,
33    pub floor: i64,
34    pub ceiling: Option<i64>,
35    pub initial_verb: String,
36    pub initial_key: String,
37    pub headroom_key: Option<String>,
38    pub issuer: String,
39    pub increment: (String, String),
40    pub decrement: (String, String),
41    pub transfer: Option<(String, String, String)>,
42    pub transfer_headroom: Option<(String, String, String)>,
43}
44impl CounterRule {
45    pub fn operation_verbs(&self) -> Vec<&str> {
46        let mut out = alloc::vec![self.increment.0.as_str(), self.decrement.0.as_str()];
47        if let Some(t) = &self.transfer {
48            out.push(&t.0);
49        }
50        if let Some(t) = &self.transfer_headroom {
51            out.push(&t.0);
52        }
53        out
54    }
55    pub fn verbs(&self) -> Vec<&str> {
56        let mut v = self.operation_verbs();
57        v.push(&self.initial_verb);
58        v
59    }
60    pub fn data_fields(&self) -> Vec<(&str, &str)> {
61        let mut v = alloc::vec![
62            (self.initial_verb.as_str(), self.initial_key.as_str()),
63            (&self.increment.0, &self.increment.1),
64            (&self.decrement.0, &self.decrement.1)
65        ];
66        if let Some((verb, r, k)) = &self.transfer {
67            v.push((verb, r));
68            v.push((verb, k));
69        }
70        if let Some(k) = &self.headroom_key {
71            v.push((&self.initial_verb, k));
72        }
73        if let Some((a, b, c)) = &self.transfer_headroom {
74            v.push((a, b));
75            v.push((a, c));
76        }
77        v
78    }
79    pub fn canonical_options(&self) -> Vec<SExpr> {
80        let sym = |x: &str| SExpr::Atom(Atom::Symbol(x.into()));
81        let key = |x: &str| SExpr::Atom(Atom::Keyword(x.into()));
82        let mut v = alloc::vec![SExpr::List(alloc::vec![
83            sym("floor"),
84            SExpr::Atom(Atom::Num(self.floor))
85        ])];
86        if let Some(n) = self.ceiling {
87            v.push(SExpr::List(alloc::vec![
88                sym("ceiling"),
89                SExpr::Atom(Atom::Num(n))
90            ]));
91        }
92        if let Some(profile) = self.certification.canonical_option() {
93            v.push(profile);
94        }
95        if self.ownership == Ownership::Collective {
96            v.push(SExpr::List(alloc::vec![
97                sym("ownership"),
98                sym("collective")
99            ]));
100        }
101        v.push(SExpr::List(alloc::vec![
102            sym(if self.ownership == Ownership::Collective {
103                "initial"
104            } else {
105                "initial-rights"
106            }),
107            sym(&self.initial_verb),
108            key(&self.initial_key)
109        ]));
110        if let Some(k) = &self.headroom_key {
111            v.push(SExpr::List(alloc::vec![
112                sym("initial-headroom"),
113                sym(&self.initial_verb),
114                key(k)
115            ]));
116        }
117        v.push(SExpr::List(alloc::vec![
118            sym("issuers"),
119            if self.issuer.is_empty() {
120                SExpr::List(Vec::new())
121            } else {
122                sym(&self.issuer)
123            }
124        ]));
125        for (name, (verb, k)) in [
126            ("increment", &self.increment),
127            ("decrement", &self.decrement),
128        ] {
129            v.push(SExpr::List(alloc::vec![sym(name), sym(verb), key(k)]));
130        }
131        if let Some((a, b, c)) = &self.transfer {
132            v.push(SExpr::List(alloc::vec![
133                sym("transfer"),
134                sym(a),
135                key(b),
136                key(c)
137            ]));
138        }
139        if let Some((a, b, c)) = &self.transfer_headroom {
140            v.push(SExpr::List(alloc::vec![
141                sym("transfer-headroom"),
142                sym(a),
143                key(b),
144                key(c)
145            ]));
146        }
147        v
148    }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Snapshot {
153    pub value: i128,
154    pub rights: BTreeMap<String, i128>,
155    pub headroom: Option<BTreeMap<String, i128>>,
156    pub tips: BTreeMap<String, String>,
157    pub opener: String,
158}
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum Outcome {
161    Ready(Snapshot),
162    Pending(Vec<String>),
163    Fault {
164        reason: String,
165        evidence: Vec<String>,
166    },
167}
168impl Outcome {
169    pub fn value(&self) -> Value {
170        let text = |s: &str| Value::Str(s.into());
171        let mut entries = BTreeMap::<String, Value>::new();
172        match self {
173            Self::Ready(s) => {
174                entries.insert(String::from("status"), text("ready"));
175                entries.insert(String::from("value"), Value::Int(s.value));
176                let balances = |m: &BTreeMap<String, i128>| {
177                    Value::Map(m.iter().map(|(k, v)| (text(k), Value::Int(*v))).collect())
178                };
179                entries.insert(String::from("rights"), balances(&s.rights));
180                if let Some(h) = &s.headroom {
181                    entries.insert(String::from("headroom"), balances(h));
182                }
183            }
184            Self::Pending(xs) => {
185                entries.insert(String::from("status"), text("pending"));
186                entries.insert(
187                    String::from("evidence"),
188                    Value::List(xs.iter().map(|s| text(s)).collect()),
189                );
190            }
191            Self::Fault { reason, evidence } => {
192                entries.insert(String::from("status"), text("fault"));
193                entries.insert(String::from("reason"), text(reason));
194                entries.insert(
195                    String::from("evidence"),
196                    Value::List(evidence.iter().map(|s| text(s)).collect()),
197                );
198            }
199        }
200        Value::Map(
201            entries
202                .into_iter()
203                .map(|(k, v)| (Value::Str(k), v))
204                .collect(),
205        )
206    }
207}
208fn fault(reason: &str, evidence: Vec<String>) -> Outcome {
209    Outcome::Fault {
210        reason: reason.into(),
211        evidence,
212    }
213}
214fn text(x: &SExpr) -> Option<&str> {
215    match x {
216        SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => Some(s),
217        _ => None,
218    }
219}
220fn number(x: &SExpr) -> Option<i64> {
221    if let SExpr::Atom(Atom::Num(n)) = x {
222        Some(*n)
223    } else {
224        None
225    }
226}
227fn account(x: &SExpr) -> Option<&str> {
228    text(x).filter(|s| s.starts_with('@') && s.len() > 1)
229}
230fn lang(msg: &Message) -> Option<&str> {
231    match msg {
232        Message::Dialect { dialect_name, .. } => Some(dialect_name),
233        Message::Wrapped { content, .. } => lang(content),
234        _ => None,
235    }
236}
237fn cast(msg: &Message) -> Option<&[SExpr]> {
238    match msg {
239        Message::Wrapped {
240            wrapper: WrapperType::WithRoles,
241            params,
242            ..
243        } => match params.first()? {
244            SExpr::List(xs) => Some(xs),
245            _ => None,
246        },
247        Message::Wrapped { content, .. } | Message::Dialect { inner: content, .. } => cast(content),
248        _ => None,
249    }
250}
251/// Recognize allocation pairs before use, including exact account spelling.
252pub fn allocations(x: &SExpr) -> Result<BTreeMap<String, i128>, String> {
253    let SExpr::List(xs) = x else {
254        return Err("allocations must be a list".into());
255    };
256    if xs.is_empty() {
257        return Err("allocations must be nonempty".into());
258    }
259    let mut m = BTreeMap::new();
260    for x in xs {
261        let SExpr::List(pair) = x else {
262            return Err("allocation must be (account natural)".into());
263        };
264        if pair.len() != 2 {
265            return Err("allocation must be (account natural)".into());
266        }
267        let a = account(&pair[0]).ok_or("allocation account must start with @")?;
268        let n = number(&pair[1])
269            .filter(|n| *n >= 0)
270            .ok_or("allocation amount must be a natural integer")?;
271        if m.insert(a.into(), i128::from(n)).is_some() {
272            return Err("duplicate allocation account".into());
273        }
274    }
275    Ok(m)
276}
277/// Rule-relevant projection of an authenticated, identity-checked native act.
278/// No Message or application content is retained. `identity` commits the original
279/// canonical Simple identity for duplicate checks; signature bytes are absent.
280#[derive(Debug, Clone, PartialEq, Eq)]
281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
282#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
283pub struct ResourceFact {
284    pub address: String,
285    pub verb: String,
286    pub signer: String,
287    pub predecessors: Vec<String>,
288    pub fields: BTreeMap<String, SExpr>,
289    pub language: Option<String>,
290    pub thread: Option<String>,
291    pub from: Option<SExpr>,
292    pub bindings: Option<Vec<SExpr>>,
293    pub identity: [u8; 32],
294}
295
296/// Check a complete incoming Act before discarding any of its payload.
297pub fn project_resource_fact(c: &CounterRule, a: &Act) -> Result<Option<ResourceFact>, String> {
298    let rebuilt = Act::from_message(a.message.clone(), &a.signer)?;
299    if rebuilt != *a {
300        return Err(String::from("inconsistent act identity"));
301    }
302    Ok(project_unchecked(c, a))
303}
304/// Native and state resource links now share one canonical multihash spelling.
305pub fn resource_state_id(id: &str) -> String {
306    id.into()
307}
308fn projected_link(x: &SExpr) -> SExpr {
309    match x {
310        SExpr::Atom(Atom::Str(s)) => SExpr::Atom(Atom::Str(resource_state_id(s))),
311        SExpr::Atom(Atom::Symbol(s)) => SExpr::Atom(Atom::Symbol(resource_state_id(s))),
312        _ => x.clone(),
313    }
314}
315// Canonical native Simple identity, not a wire-AST representation tag. Native
316// typed identity already equates One/singleton Set, None/empty Set, and core/
317// custom performative aliases. Fact snapshots must not split on those aliases.
318// observe() retains its separate raw-attempt conflict diagnostics; projection
319// continuation is over the identity-consistent accepted store. A raw attempt
320// list is a diagnostic input to observe(), not this accepted-store contract.
321fn simple_identity(m: &Message) -> [u8; 32] {
322    use sha2::{Digest, Sha256};
323    Sha256::digest(crate::equivocation::message_content_hash(m).as_bytes()).into()
324}
325fn project_unchecked(c: &CounterRule, a: &Act) -> Option<ResourceFact> {
326    let bindings = cast(&a.message);
327    if !c.verbs().contains(&a.verb.as_str()) && bindings.is_none() {
328        return None;
329    }
330    let identity = simple_identity(a.simple());
331    let mut names: BTreeSet<&str> = c
332        .data_fields()
333        .into_iter()
334        .filter(|(v, _)| *v == a.verb)
335        .map(|(_, k)| k)
336        .collect();
337    names.extend([PREV, DEPS]);
338    Some(ResourceFact {
339        address: a.address.clone(),
340        verb: a.verb.clone(),
341        signer: a.signer.clone(),
342        predecessors: a
343            .predecessors
344            .iter()
345            .map(|id| resource_state_id(id))
346            .collect(),
347        fields: a
348            .fields
349            .iter()
350            .filter(|(k, _)| names.contains(k.as_str()))
351            .map(|(k, v)| {
352                (
353                    k.clone(),
354                    if k == PREV {
355                        projected_link(v)
356                    } else if k == DEPS {
357                        match v {
358                            SExpr::List(xs) => SExpr::List(xs.iter().map(projected_link).collect()),
359                            _ => v.clone(),
360                        }
361                    } else {
362                        v.clone()
363                    },
364                )
365            })
366            .collect(),
367        language: lang(&a.message).map(String::from),
368        thread: a.simple().thread().map(String::from),
369        from: raw_field(a.simple(), "from").cloned(),
370        bindings: bindings.map(|xs| xs.to_vec()),
371        identity,
372    })
373}
374
375#[derive(Clone, Copy)]
376enum Kind {
377    Increment,
378    Decrement,
379    Transfer,
380    Headroom,
381}
382struct Node<'a> {
383    act: &'a ResourceFact,
384    prev: String,
385    deps: Vec<String>,
386    kind: Kind,
387    amount: i128,
388    recipient: Option<String>,
389}
390fn operation<'a>(
391    c: &CounterRule,
392    a: &'a ResourceFact,
393) -> Option<(Kind, &'a SExpr, Option<&'a SExpr>)> {
394    let (kind, key, recipient) = if a.verb == c.increment.0 {
395        (Kind::Increment, c.increment.1.as_str(), None)
396    } else if a.verb == c.decrement.0 {
397        (Kind::Decrement, c.decrement.1.as_str(), None)
398    } else if let Some((_, r, k)) = c.transfer.as_ref().filter(|(v, _, _)| a.verb == *v) {
399        (Kind::Transfer, k.as_str(), Some(r.as_str()))
400    } else if let Some((v, r, k)) = &c.transfer_headroom {
401        if &a.verb == v {
402            (Kind::Headroom, k.as_str(), Some(r.as_str()))
403        } else {
404            return None;
405        }
406    } else {
407        return None;
408    };
409    Some((
410        kind,
411        a.fields.get(key)?,
412        recipient.and_then(|k| a.fields.get(k)),
413    ))
414}
415fn add(m: &mut BTreeMap<String, i128>, owner: &str, n: i128) -> Result<(), String> {
416    let v = m.get_mut(owner).ok_or("unknown account")?;
417    *v = v.checked_add(n).ok_or("arithmetic overflow")?;
418    Ok(())
419}
420fn apply(
421    n: &Node,
422    rights: &mut BTreeMap<String, i128>,
423    headroom: &mut Option<BTreeMap<String, i128>>,
424) -> Result<(), String> {
425    let owner = &n.act.signer;
426    let amount = n.amount;
427    match n.kind {
428        Kind::Increment => {
429            if let Some(h) = headroom {
430                add(h, owner, -amount)?;
431            }
432            add(rights, owner, amount)?;
433        }
434        Kind::Decrement => {
435            add(rights, owner, -amount)?;
436            if let Some(h) = headroom {
437                add(h, owner, amount)?;
438            }
439        }
440        Kind::Transfer => {
441            add(rights, owner, -amount)?;
442            add(
443                rights,
444                n.recipient.as_deref().ok_or("missing recipient")?,
445                amount,
446            )?;
447        }
448        Kind::Headroom => {
449            let h = headroom
450                .as_mut()
451                .ok_or("headroom transfer requires ceiling")?;
452            add(h, owner, -amount)?;
453            add(
454                h,
455                n.recipient.as_deref().ok_or("missing recipient")?,
456                amount,
457            )?;
458        }
459    }
460    Ok(())
461}
462fn total(m: &BTreeMap<String, i128>) -> Option<i128> {
463    m.values().try_fold(0i128, |sum, n| sum.checked_add(*n))
464}
465
466#[derive(Clone, Default)]
467struct Summary {
468    sequence: usize,
469    tips: BTreeMap<String, String>,
470    credited: i128,
471    debited: i128,
472    sent_rights: BTreeMap<String, i128>,
473    sent_headroom: BTreeMap<String, i128>,
474}
475impl Summary {
476    fn record(&mut self, n: &Node) -> Result<(), String> {
477        self.sequence = self.sequence.checked_add(1).ok_or("sequence overflow")?;
478        match n.kind {
479            Kind::Increment => {
480                self.credited = self
481                    .credited
482                    .checked_add(n.amount)
483                    .ok_or("arithmetic overflow")?
484            }
485            Kind::Decrement => {
486                self.debited = self
487                    .debited
488                    .checked_add(n.amount)
489                    .ok_or("arithmetic overflow")?
490            }
491            Kind::Transfer | Kind::Headroom => {
492                let to = n.recipient.as_ref().ok_or("missing recipient")?;
493                let map = if matches!(n.kind, Kind::Transfer) {
494                    &mut self.sent_rights
495                } else {
496                    &mut self.sent_headroom
497                };
498                let entry = map.entry(to.clone()).or_default();
499                *entry = entry.checked_add(n.amount).ok_or("arithmetic overflow")?;
500            }
501        }
502        Ok(())
503    }
504}
505fn local_budgets(
506    owner: &str,
507    initial: &BTreeMap<String, i128>,
508    headroom: Option<&BTreeMap<String, i128>>,
509    own: &Summary,
510    tips: &BTreeMap<String, String>,
511    summaries: &BTreeMap<String, Summary>,
512) -> Result<(i128, Option<i128>), String> {
513    let outgoing = total(&own.sent_rights).ok_or("arithmetic overflow")?;
514    let mut rights = initial[owner]
515        .checked_add(own.credited)
516        .and_then(|v| v.checked_sub(own.debited))
517        .and_then(|v| v.checked_sub(outgoing))
518        .ok_or("arithmetic overflow")?;
519    let mut space = if let Some(h) = headroom {
520        let outgoing = total(&own.sent_headroom).ok_or("arithmetic overflow")?;
521        Some(
522            h[owner]
523                .checked_add(own.debited)
524                .and_then(|v| v.checked_sub(own.credited))
525                .and_then(|v| v.checked_sub(outgoing))
526                .ok_or("arithmetic overflow")?,
527        )
528    } else {
529        None
530    };
531    for (other, tip) in tips {
532        if other == owner {
533            continue;
534        }
535        let summary = &summaries[tip];
536        rights = rights
537            .checked_add(*summary.sent_rights.get(owner).unwrap_or(&0))
538            .ok_or("arithmetic overflow")?;
539        if let Some(h) = space.as_mut() {
540            *h = h
541                .checked_add(*summary.sent_headroom.get(owner).unwrap_or(&0))
542                .ok_or("arithmetic overflow")?;
543        }
544    }
545    Ok((rights, space))
546}
547
548/// Observe the complete supplied accepted history. Invalid acts fault rather than
549/// disappearing. Missing evidence returns pending; no partial balance is exposed.
550/// Inputs must be authenticated and protocol accepted by the host.
551pub fn observe(c: &CounterRule, acts: &[Act]) -> Outcome {
552    if c.ownership == Ownership::Collective {
553        return fault(
554            "collective counter requires the certificate runtime",
555            Vec::new(),
556        );
557    }
558    if c.certification.is_quorum() {
559        return fault("quorum-budget requires an explicit certificate runtime; legacy fold cannot prove finality", Vec::new());
560    }
561    let mut all: BTreeMap<&str, &Act> = BTreeMap::new();
562    for a in acts {
563        let rebuilt = match Act::from_message(a.message.clone(), &a.signer) {
564            Ok(x) => x,
565            Err(e) => return fault(&e, alloc::vec![a.address.clone()]),
566        };
567        if a.address != rebuilt.address
568            || a.verb != rebuilt.verb
569            || a.fields != rebuilt.fields
570            || a.predecessors != rebuilt.predecessors
571            || a.recipients != rebuilt.recipients
572        {
573            return fault("inconsistent act identity", alloc::vec![a.address.clone()]);
574        }
575        if let Some(prev) = all.insert(&a.address, a) {
576            if prev.signer != a.signer
577                || prev.simple() != a.simple()
578                || lang(&prev.message) != lang(&a.message)
579                || cast(&prev.message) != cast(&a.message)
580            {
581                return fault(
582                    "conflicting authenticated identity",
583                    alloc::vec![a.address.clone()],
584                );
585            }
586        }
587    }
588    let facts: BTreeMap<String, ResourceFact> = all
589        .values()
590        .filter_map(|a| project_unchecked(c, a).map(|f| (f.address.clone(), f)))
591        .collect();
592    observe_facts(c, &facts, |id| all.contains_key(id))
593}
594
595/// Minimal observation inputs, not signed evidence or resource finality authority.
596/// `present` denotes accepted identities, including non-resource dependencies.
597/// Callers importing a certified projection must pin its rule and provenance.
598pub fn observe_facts<F: Fn(&str) -> bool>(
599    c: &CounterRule,
600    all: &BTreeMap<String, ResourceFact>,
601    present: F,
602) -> Outcome {
603    let mut outcome = observe_facts_inner(c, all, &present);
604    // Unsupported profiles have a history-independent native fault. Preserve
605    // that boundary (and compact checkpoint compatibility) across projections.
606    if c.ownership == Ownership::Collective || c.certification.is_quorum() {
607        return outcome;
608    }
609    if let Outcome::Fault { evidence, .. } = &mut outcome {
610        // SPEC-038 REQ-3806: a later diagnosis must not erase an earlier
611        // witness. Evidence is a contextual certificate, not a minimal blame
612        // set: retain all accepted resource facts and accepted cited context.
613        evidence.extend(all.keys().cloned());
614        for fact in all.values() {
615            evidence.extend(fact.predecessors.iter().filter(|id| present(id)).cloned());
616            if let Some(id) = fact
617                .fields
618                .get(PREV)
619                .and_then(text)
620                .filter(|id| present(id))
621            {
622                evidence.push(id.to_string());
623            }
624            if let Some(SExpr::List(deps)) = fact.fields.get(DEPS) {
625                evidence.extend(
626                    deps.iter()
627                        .filter_map(text)
628                        .filter(|id| present(id))
629                        .map(String::from),
630                );
631            }
632        }
633        crate::state::sort_addresses(evidence);
634        evidence.dedup();
635    }
636    outcome
637}
638
639fn observe_facts_inner<F: Fn(&str) -> bool>(
640    c: &CounterRule,
641    all: &BTreeMap<String, ResourceFact>,
642    present: F,
643) -> Outcome {
644    if c.ownership == Ownership::Collective {
645        return fault(
646            "collective counter requires the certificate runtime",
647            Vec::new(),
648        );
649    }
650    if c.certification.is_quorum() {
651        return fault("quorum-budget requires an explicit certificate runtime; legacy fold cannot prove finality", Vec::new());
652    }
653    let openers: Vec<_> = all.values().filter(|a| a.verb == c.initial_verb).collect();
654    if openers.is_empty() {
655        return Outcome::Pending(Vec::new());
656    }
657    if openers.len() != 1 {
658        return fault(
659            "multiple resource openers",
660            openers.iter().map(|a| a.address.clone()).collect(),
661        );
662    }
663    let op = openers[0];
664    if op.predecessors.len() != 1 {
665        return fault(
666            "resource opener needs a cast-bearing root",
667            alloc::vec![op.address.clone()],
668        );
669    }
670    let Some(root) = all.get(op.predecessors[0].as_str()) else {
671        return if present(&op.predecessors[0]) {
672            fault("missing authenticated cast", op.predecessors.clone())
673        } else {
674            Outcome::Pending(op.predecessors.clone())
675        };
676    };
677    let Some(bindings) = root.bindings.as_deref() else {
678        return fault(
679            "missing authenticated cast",
680            alloc::vec![root.address.clone()],
681        );
682    };
683    let mut members = BTreeSet::new();
684    let mut issuers = BTreeSet::new();
685    for binding in bindings {
686        let SExpr::List(xs) = binding else {
687            return fault("malformed cast", alloc::vec![root.address.clone()]);
688        };
689        let Some(role) = xs.first().and_then(text) else {
690            return fault("malformed cast role", alloc::vec![root.address.clone()]);
691        };
692        for key in &xs[1..] {
693            let Some(key) = account(key) else {
694                return fault("malformed cast account", alloc::vec![root.address.clone()]);
695            };
696            members.insert(key.to_string());
697            if role == c.issuer {
698                issuers.insert(key.to_string());
699            }
700        }
701    }
702    if !members.contains(&op.signer) {
703        return fault(
704            "resource opener signer is outside the cast",
705            alloc::vec![op.address.clone()],
706        );
707    }
708    let initial = match op
709        .fields
710        .get(&c.initial_key)
711        .ok_or("missing initial allocations")
712        .and_then(|x| allocations(x).map_err(|_| "invalid initial allocations"))
713    {
714        Ok(x) => x,
715        Err(e) => return fault(e, alloc::vec![op.address.clone()]),
716    };
717    if initial.keys().any(|k| !members.contains(k))
718        || issuers.iter().any(|k| !initial.contains_key(k))
719    {
720        return fault(
721            "allocation accounts and issuer cast disagree",
722            alloc::vec![op.address.clone()],
723        );
724    }
725    let initial_headroom = if let Some(key) = &c.headroom_key {
726        match op
727            .fields
728            .get(key)
729            .ok_or("missing headroom allocations")
730            .and_then(|x| allocations(x).map_err(|_| "invalid headroom allocations"))
731        {
732            Ok(h) if h.keys().eq(initial.keys()) => Some(h),
733            _ => {
734                return fault(
735                    "headroom accounts must match allocations",
736                    alloc::vec![op.address.clone()],
737                )
738            }
739        }
740    } else {
741        None
742    };
743    let Some(initial_total) = total(&initial).and_then(|v| v.checked_add(i128::from(c.floor)))
744    else {
745        return fault("arithmetic overflow", alloc::vec![op.address.clone()]);
746    };
747    if let Some(ceiling) = c.ceiling {
748        if ceiling < c.floor
749            || initial_headroom
750                .as_ref()
751                .and_then(total)
752                .and_then(|h| h.checked_add(initial_total))
753                != Some(i128::from(ceiling))
754        {
755            return fault(
756                "initial rights plus headroom must equal ceiling minus floor",
757                alloc::vec![op.address.clone()],
758            );
759        }
760    }
761    let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
762    let mut children: BTreeMap<(String, String), String> = BTreeMap::new();
763    for a in all
764        .values()
765        .filter(|a| c.operation_verbs().contains(&a.verb.as_str()))
766    {
767        if a.thread != op.thread || a.language != op.language || !initial.contains_key(&a.signer) {
768            return fault(
769                "foreign resource instance or account",
770                alloc::vec![a.address.clone()],
771            );
772        }
773        if a.from.as_ref().and_then(text) != Some(a.signer.as_str()) {
774            return fault(
775                "resource signer disagrees with :from",
776                alloc::vec![a.address.clone()],
777            );
778        }
779        let Some((kind, amount, recipient)) = operation(c, a) else {
780            return fault(
781                "malformed resource operation",
782                alloc::vec![a.address.clone()],
783            );
784        };
785        let Some(amount) = number(amount).filter(|n| *n > 0) else {
786            return fault(
787                "resource amount must be positive",
788                alloc::vec![a.address.clone()],
789            );
790        };
791        if matches!(kind, Kind::Increment) && !issuers.contains(&a.signer) {
792            return fault("unauthorized increment", alloc::vec![a.address.clone()]);
793        }
794        let recipient = if matches!(kind, Kind::Transfer | Kind::Headroom) {
795            match recipient.and_then(account) {
796                Some(r) if initial.contains_key(r) && r != a.signer => Some(r.to_string()),
797                _ => return fault("invalid resource recipient", alloc::vec![a.address.clone()]),
798            }
799        } else {
800            None
801        };
802        let Some(prev) = a
803            .fields
804            .get(PREV)
805            .and_then(text)
806            .filter(|s| crate::r7::is_address(s))
807        else {
808            return fault(
809                "missing escrow previous address",
810                alloc::vec![a.address.clone()],
811            );
812        };
813        let Some(SExpr::List(xs)) = a.fields.get(DEPS) else {
814            return fault(
815                "missing escrow dependencies",
816                alloc::vec![a.address.clone()],
817            );
818        };
819        let mut deps = Vec::new();
820        let mut seen = BTreeSet::new();
821        for x in xs {
822            let Some(dep) = text(x).filter(|s| crate::r7::is_address(s) && *s != prev) else {
823                return fault("invalid escrow dependency", alloc::vec![a.address.clone()]);
824            };
825            if !seen.insert(dep) {
826                return fault(
827                    "duplicate escrow dependency",
828                    alloc::vec![a.address.clone()],
829                );
830            }
831            deps.push(dep.to_string());
832        }
833        if let Some(other) = children.insert((a.signer.clone(), prev.into()), a.address.clone()) {
834            let mut evidence = alloc::vec![other, a.address.clone()];
835            evidence.sort();
836            return fault("owner fork", evidence);
837        }
838        nodes.insert(
839            a.address.clone(),
840            Node {
841                act: a,
842                prev: prev.into(),
843                deps,
844                kind,
845                amount: i128::from(amount),
846                recipient,
847            },
848        );
849    }
850    let mut missing = BTreeSet::new();
851    for n in nodes.values() {
852        for dep in core::iter::once(&n.prev).chain(n.deps.iter()) {
853            if dep == &op.address {
854                continue;
855            }
856            if let Some(parent) = nodes.get(dep) {
857                if dep == &n.prev && parent.act.signer != n.act.signer {
858                    return fault(
859                        "wrong owner previous link",
860                        alloc::vec![n.act.address.clone(), dep.clone()],
861                    );
862                }
863            } else if all.contains_key(dep.as_str()) || present(dep) {
864                return fault(
865                    "foreign resource dependency",
866                    alloc::vec![n.act.address.clone(), dep.clone()],
867                );
868            } else {
869                missing.insert(dep.clone());
870            }
871        }
872    }
873    // Validate every dependency-closed component before reporting missing
874    // evidence elsewhere. Otherwise an unrelated pending account could hide
875    // an already established budget fault (SPEC-038 REQ-3806).
876    // Kahn traversal plus bounded account frontiers. Each summary stores only
877    // the latest observed operation per account and that owner's cumulative
878    // transfers. Installed profiles bound accounts and dependencies by max-list;
879    // no quadratic ancestor sets or recursive traversal are required.
880    let mut waiting: BTreeMap<String, Vec<String>> = BTreeMap::new();
881    let mut remaining = BTreeMap::new();
882    let mut ready = BTreeSet::new();
883    for (address, n) in &nodes {
884        let dependencies: BTreeSet<_> = core::iter::once(&n.prev)
885            .chain(n.deps.iter())
886            .filter(|d| *d != &op.address)
887            .cloned()
888            .collect();
889        remaining.insert(address.clone(), dependencies.len());
890        if dependencies.is_empty() {
891            ready.insert(address.clone());
892        }
893        for parent in dependencies {
894            waiting.entry(parent).or_default().push(address.clone());
895        }
896    }
897    let mut summaries: BTreeMap<String, Summary> = BTreeMap::new();
898    while let Some(address) = ready.pop_first() {
899        let n = &nodes[&address];
900        let own = if n.prev == op.address {
901            Summary::default()
902        } else {
903            summaries[&n.prev].clone()
904        };
905        let mut tips = own.tips.clone();
906        for dep in &n.deps {
907            if dep == &op.address {
908                continue;
909            }
910            for (owner, tip) in &summaries[dep].tips {
911                if tips.get(owner).map_or(true, |old| {
912                    summaries[old].sequence < summaries[tip].sequence
913                }) {
914                    tips.insert(owner.clone(), tip.clone());
915                }
916            }
917        }
918        let (rights_budget, headroom_budget) = match local_budgets(
919            &n.act.signer,
920            &initial,
921            initial_headroom.as_ref(),
922            &own,
923            &tips,
924            &summaries,
925        ) {
926            Ok(b) => b,
927            Err(e) => return fault(&e, alloc::vec![address.clone()]),
928        };
929        let budget = if matches!(n.kind, Kind::Increment | Kind::Headroom) {
930            headroom_budget
931        } else {
932            Some(rights_budget)
933        };
934        if budget.is_some_and(|b| b < n.amount) {
935            return fault(
936                if matches!(n.kind, Kind::Increment | Kind::Headroom) {
937                    "insufficient headroom"
938                } else {
939                    "insufficient rights"
940                },
941                alloc::vec![address.clone()],
942            );
943        }
944        let mut next = own;
945        if let Err(e) = next.record(n) {
946            return fault(&e, alloc::vec![address.clone()]);
947        }
948        next.tips = tips;
949        next.tips.insert(n.act.signer.clone(), address.clone());
950        summaries.insert(address.clone(), next);
951        if let Some(children) = waiting.remove(&address) {
952            for child in children {
953                let count = remaining.get_mut(&child).expect("known dependent");
954                *count -= 1;
955                if *count == 0 {
956                    ready.insert(child);
957                }
958            }
959        }
960    }
961    if !missing.is_empty() {
962        // Missing references block budget evaluation, but cannot hide an
963        // independent cycle. Release their graph edges without inventing
964        // resource summaries, then finish the structural Kahn traversal.
965        for dependency in &missing {
966            if let Some(children) = waiting.remove(dependency) {
967                for child in children {
968                    let count = remaining.get_mut(&child).expect("known dependent");
969                    *count -= 1;
970                    if *count == 0 {
971                        ready.insert(child);
972                    }
973                }
974            }
975        }
976        let mut reached = summaries.len();
977        while let Some(address) = ready.pop_first() {
978            reached += 1;
979            if let Some(children) = waiting.remove(&address) {
980                for child in children {
981                    let count = remaining.get_mut(&child).expect("known dependent");
982                    *count -= 1;
983                    if *count == 0 {
984                        ready.insert(child);
985                    }
986                }
987            }
988        }
989        if reached != nodes.len() {
990            return fault(
991                "cyclic escrow dependencies",
992                nodes.keys().cloned().collect(),
993            );
994        }
995        return Outcome::Pending(missing.into_iter().collect());
996    }
997    if summaries.len() != nodes.len() {
998        return fault(
999            "cyclic escrow dependencies",
1000            nodes.keys().cloned().collect(),
1001        );
1002    }
1003    let mut rights = initial;
1004    let mut headroom = initial_headroom;
1005    for n in nodes.values() {
1006        if let Err(e) = apply(n, &mut rights, &mut headroom) {
1007            return fault(&e, alloc::vec![n.act.address.clone()]);
1008        }
1009    }
1010    if rights.values().any(|n| *n < 0)
1011        || headroom
1012            .as_ref()
1013            .is_some_and(|h| h.values().any(|n| *n < 0))
1014    {
1015        return fault("negative escrow budget", nodes.keys().cloned().collect());
1016    }
1017    let Some(value) = total(&rights).and_then(|v| v.checked_add(i128::from(c.floor))) else {
1018        return fault("arithmetic overflow", Vec::new());
1019    };
1020    if let Some(c) = c.ceiling {
1021        if headroom
1022            .as_ref()
1023            .and_then(total)
1024            .and_then(|h| value.checked_add(h))
1025            != Some(i128::from(c))
1026        {
1027            return fault("headroom conservation failure", Vec::new());
1028        }
1029    }
1030    let mut tips = BTreeMap::new();
1031    for n in nodes.values() {
1032        if !children.contains_key(&(n.act.signer.clone(), n.act.address.clone())) {
1033            tips.insert(n.act.signer.clone(), n.act.address.clone());
1034        }
1035    }
1036    Outcome::Ready(Snapshot {
1037        value,
1038        rights,
1039        headroom,
1040        tips,
1041        opener: op.address.clone(),
1042    })
1043}
1044
1045/// Install-time validation, including collisions and role/shape references.
1046pub fn declaration_errors(d: &crate::dialect::Dialect) -> Vec<String> {
1047    use crate::shape::TypeConstraint as T;
1048    use crate::state::{opener_verb, Rule};
1049    let mut errors = Vec::new();
1050    let mut operation_owner = BTreeMap::new();
1051    let Some(clause) = &d.state else {
1052        return errors;
1053    };
1054    let reserved = |key: &str| {
1055        [PREV, DEPS, NONCE, crate::state::RESERVED_REPLACES].contains(&key)
1056            || crate::state::ROUTING_KEYWORDS.contains(&key)
1057    };
1058    for (name, rule) in clause.fields() {
1059        let Rule::BoundedCounter(c) = rule else {
1060            continue;
1061        };
1062        if let Err(error) = c.certification.validate() {
1063            errors.push(error);
1064        }
1065        if d.roles.is_empty() {
1066            errors.push("bounded counters require an authenticated role cast".into());
1067        }
1068        if d.causal_protocol.as_ref().and_then(opener_verb) != Some(c.initial_verb.as_str()) {
1069            errors.push(format!(
1070                "bounded-counter '{name}' must initialize from the unique opener"
1071            ));
1072        }
1073        if !c.issuer.is_empty() && !d.roles.iter().any(|r| r.name == c.issuer) {
1074            errors.push(format!(
1075                "unknown bounded-counter issuer role '{}'",
1076                c.issuer
1077            ));
1078        }
1079        let bounds = crate::r7::bounds_of(d);
1080        if c.floor.unsigned_abs() > bounds.max_number as u64
1081            || c.ceiling
1082                .is_some_and(|n| n < c.floor || n.unsigned_abs() > bounds.max_number as u64)
1083        {
1084            errors.push("counter bounds exceed numeric limits or ceiling is below floor".into());
1085        }
1086        if (c.ownership == Ownership::Account && c.ceiling.is_some() != c.headroom_key.is_some())
1087            || c.transfer_headroom.is_some() && c.ceiling.is_none()
1088        {
1089            errors.push(
1090                "ceiling requires initial-headroom; headroom transfers require ceiling".into(),
1091            );
1092        }
1093        if c.ownership == Ownership::Collective {
1094            if !c.certification.is_quorum()
1095                || c.headroom_key.is_some()
1096                || c.transfer.is_some()
1097                || c.transfer_headroom.is_some()
1098            {
1099                errors.push("collective counters require quorum-budget and scalar initialization without account transfers".into());
1100            }
1101            for verb in c.verbs() {
1102                if d.find_performative(verb)
1103                    .and_then(|p| p.role.as_ref())
1104                    .is_none()
1105                {
1106                    errors.push(format!(
1107                        "collective verb '{verb}' requires an explicit from role"
1108                    ));
1109                }
1110            }
1111        } else if c.transfer.is_none() {
1112            errors.push("account counters require a transfer mapping".into());
1113        }
1114        for verb in c.operation_verbs() {
1115            if verb == c.initial_verb || operation_owner.insert(verb, name).is_some() {
1116                errors.push(format!(
1117                    "operation '{verb}' must serve exactly one counter and operation kind"
1118                ));
1119            }
1120        }
1121        let mut expected = alloc::vec![
1122            (
1123                c.initial_verb.as_str(),
1124                c.initial_key.as_str(),
1125                alloc::vec![if c.ownership == Ownership::Collective {
1126                    T::Integer
1127                } else {
1128                    T::List
1129                }]
1130            ),
1131            (&c.increment.0, &c.increment.1, alloc::vec![T::Integer]),
1132            (&c.decrement.0, &c.decrement.1, alloc::vec![T::Integer])
1133        ];
1134        if let Some((v, r, k)) = &c.transfer {
1135            expected.push((v, r, alloc::vec![T::Symbol, T::String]));
1136            expected.push((v, k, alloc::vec![T::Integer]));
1137            if r == k {
1138                errors.push("counter data fields must be distinct".into());
1139            }
1140        }
1141        if c.headroom_key.as_ref() == Some(&c.initial_key) {
1142            errors.push("counter data fields must be distinct".into());
1143        }
1144        if let Some(k) = &c.headroom_key {
1145            expected.push((&c.initial_verb, k, alloc::vec![T::List]));
1146        }
1147        if let Some((v, r, k)) = &c.transfer_headroom {
1148            if r == k {
1149                errors.push("headroom recipient and amount fields must differ".into());
1150            }
1151            expected.push((v, r, alloc::vec![T::Symbol, T::String]));
1152            expected.push((v, k, alloc::vec![T::Integer]));
1153        }
1154        for (v, k, types) in expected {
1155            if reserved(k) {
1156                errors.push(format!("counter data may not read reserved :{k}"));
1157            }
1158            if !d.shapes.iter().filter(|shape|shape.performative==v).any(|shape|shape.rules.iter().any(|rule|matches!(rule,crate::shape::ShapeRule::Require{keyword,type_constraint:Some(t),..} if keyword==k&&t.representation().as_ref().is_some_and(|base|types.contains(base) || types.contains(&T::Integer) && *base == T::Nonnegative)))) {
1159                errors.push(format!(
1160                    "counter '{name}': '{v}' requires an appropriately typed :{k}"
1161                ));
1162            }
1163        }
1164        for (v, _, _) in clause.domains() {
1165            if c.verbs().contains(&v) {
1166                errors.push(format!("domain may not hide resource acts of '{v}'"));
1167            }
1168        }
1169    }
1170    // No ordinary state rule can interpret compiler-owned resource evidence.
1171    for (_, rule) in clause.fields() {
1172        for (_, k) in rule.data_fields() {
1173            if [PREV, DEPS, NONCE].contains(&k) {
1174                errors.push("state data may not read escrow bookkeeping".into());
1175            }
1176        }
1177    }
1178    for (_, k, _) in clause.domains() {
1179        if [PREV, DEPS, NONCE].contains(&k) {
1180            errors.push("domain may not read escrow bookkeeping".into());
1181        }
1182    }
1183    errors
1184}
1185/// The resource operation bound to a verb, if any (installation ensures unique).
1186pub fn rule_for<'a>(
1187    d: &'a crate::dialect::Dialect,
1188    verb: &str,
1189) -> Option<(&'a str, &'a CounterRule)> {
1190    d.state.as_ref()?.fields().find_map(|(name, r)| match r {
1191        crate::state::Rule::BoundedCounter(c) if c.operation_verbs().contains(&verb) => {
1192            Some((name, c.as_ref()))
1193        }
1194        _ => None,
1195    })
1196}
1197/// Shape typing exception: a resource recipient is an authenticated account key.
1198pub fn recipient_field(d: &crate::dialect::Dialect, verb: &str, key: &str) -> bool {
1199    rule_for(d, verb).is_some_and(|(_, c)| {
1200        c.transfer
1201            .as_ref()
1202            .is_some_and(|(v, r, _)| v == verb && r == key)
1203            || c.transfer_headroom
1204                .as_ref()
1205                .is_some_and(|(v, r, _)| v == verb && r == key)
1206    })
1207}
1208/// Resource candidate check. A faulted base cannot authorize any candidate.
1209pub fn check(c: &CounterRule, acts: &[Act], candidate: &Act) -> Outcome {
1210    match observe(c, acts) {
1211        Outcome::Ready(_) => {}
1212        other => return other,
1213    }
1214    let mut with = acts.to_vec();
1215    with.push(candidate.clone());
1216    observe(c, &with)
1217}
1218/// Pure candidate completion. Durable issuance is a separate required host gate.
1219pub fn bookkeeping(
1220    d: &crate::dialect::Dialect,
1221    acts: &[Act],
1222    thread: &str,
1223    signer: &str,
1224    verb: &str,
1225) -> Result<Vec<(String, SExpr)>, String> {
1226    let Some((_, c)) = rule_for(d, verb) else {
1227        return Ok(Vec::new());
1228    };
1229    let snapshot = match observe_in(d, thread, c, acts) {
1230        Outcome::Ready(s) => s,
1231        other => return Err(other.value().render()),
1232    };
1233    if !snapshot.rights.contains_key(signer) {
1234        return Err("signer is not a resource account".into());
1235    }
1236    let prev = snapshot
1237        .tips
1238        .get(signer)
1239        .unwrap_or(&snapshot.opener)
1240        .clone();
1241    let deps: BTreeSet<_> = snapshot
1242        .tips
1243        .iter()
1244        .filter(|(owner, _)| owner.as_str() != signer)
1245        .map(|(_, a)| a.clone())
1246        .collect();
1247    if deps.len() > crate::r7::bounds_of(d).max_list as usize {
1248        return Err("escrow dependency limit exceeded".into());
1249    }
1250    Ok(alloc::vec![
1251        (PREV.into(), SExpr::Atom(Atom::Symbol(prev))),
1252        (
1253            DEPS.into(),
1254            SExpr::List(
1255                deps.into_iter()
1256                    .map(|a| SExpr::Atom(Atom::Symbol(a)))
1257                    .collect()
1258            )
1259        )
1260    ])
1261}
1262
1263/// Host capability required for durable issuance. All operation kinds share
1264/// the same (dialect, thread, opener, field, account) lane. Implementations must
1265/// atomically persist the FULL candidate against `expected_previous` and never
1266/// sign/publish a losing candidate. Recovery reuses the persisted candidate.
1267pub trait IssuanceGate {
1268    fn compare_and_append(
1269        &mut self,
1270        lane: &IssuanceLane,
1271        expected_previous: &str,
1272        candidate: &Act,
1273    ) -> Result<(), String>;
1274}
1275#[derive(Debug, Clone, PartialEq, Eq)]
1276pub struct IssuanceLane {
1277    pub dialect: String,
1278    pub thread: String,
1279    pub opener: String,
1280    pub field: String,
1281    pub account: String,
1282}
1283/// Complete and reserve one resource act before returning it for signing.
1284/// Authentication, protocol admission and idempotent effect delivery remain
1285/// host duties. This helper does not provide a default, non-durable gate.
1286pub fn issue<G: IssuanceGate>(
1287    inst: &crate::intend::Instance,
1288    signer: &crate::role::AgentKey,
1289    verb: &str,
1290    fields: BTreeMap<String, SExpr>,
1291    gate: &mut G,
1292) -> Result<Message, String> {
1293    let (field, c) = rule_for(inst.dialect, verb).ok_or("not a resource operation")?;
1294    if c.certification.is_quorum() {
1295        return Err("quorum-budget uses independent validator votes, not IssuanceGate".into());
1296    }
1297    let message = crate::intend::intend(inst, signer, verb, fields).map_err(|e| e.to_string())?;
1298    let candidate = Act::from_message(message.clone(), &signer.0)?;
1299    let Outcome::Ready(s) = observe_in(inst.dialect, &inst.thread.0, c, inst.acts) else {
1300        return Err("resource history is not ready".into());
1301    };
1302    let previous = candidate
1303        .fields
1304        .get(PREV)
1305        .and_then(text)
1306        .ok_or("missing escrow previous")?;
1307    let lane = IssuanceLane {
1308        dialect: crate::canonical::dialect_name(inst.dialect),
1309        thread: inst.thread.0.clone(),
1310        opener: s.opener,
1311        field: field.into(),
1312        account: signer.0.clone(),
1313    };
1314    gate.compare_and_append(&lane, previous, &candidate)?;
1315    Ok(message)
1316}
1317
1318fn raw_field<'a>(msg: &'a Message, key: &str) -> Option<&'a SExpr> {
1319    let Message::Simple { params, .. } = msg else {
1320        return None;
1321    };
1322    params.windows(2).find_map(|xs| {
1323        if matches!(&xs[0],SExpr::Atom(Atom::Keyword(k)) if k==key) {
1324            Some(&xs[1])
1325        } else {
1326            None
1327        }
1328    })
1329}
1330
1331/// Context-pinned observation for bindings and business authorization. The
1332/// lower-level `observe` is a mathematical observation under a caller-supplied
1333/// pinned-history premise; this entry checks that premise's structural portion.
1334pub fn observe_in(
1335    d: &crate::dialect::Dialect,
1336    thread: &str,
1337    c: &CounterRule,
1338    acts: &[Act],
1339) -> Outcome {
1340    for a in acts.iter().filter(|a| c.verbs().contains(&a.verb.as_str())) {
1341        if crate::r7::verify_state_shape(d, &a.message).is_err()
1342            || d.shapes
1343                .iter()
1344                .filter(|shape| shape.performative == a.verb)
1345                .any(|shape| shape.check(&SExpr::from(a.simple())).is_err())
1346        {
1347            return fault(
1348                "invalid resource message shape",
1349                alloc::vec![a.address.clone()],
1350            );
1351        }
1352        if let Message::Simple { params, .. } = a.simple() {
1353            let mut seen = BTreeSet::new();
1354            for pair in params.chunks(2) {
1355                if let Some(SExpr::Atom(Atom::Keyword(key))) = pair.first() {
1356                    if !seen.insert(key) {
1357                        return fault("duplicate resource keyword", alloc::vec![a.address.clone()]);
1358                    }
1359                }
1360            }
1361        }
1362        if a.simple().thread() != Some(thread) || lang(&a.message) != Some(d.name.as_str()) {
1363            return fault(
1364                "resource history context mismatch",
1365                alloc::vec![a.address.clone()],
1366            );
1367        }
1368    }
1369    // Validate the actual cast against installed role cardinalities, rather
1370    // than interpreting arbitrary binding lists as a valid cast.
1371    for opener in acts.iter().filter(|a| a.verb == c.initial_verb) {
1372        for root in acts.iter().filter(|a| {
1373            opener
1374                .predecessors
1375                .iter()
1376                .any(|id| resource_state_id(id) == a.address)
1377        }) {
1378            if root.verb != "hello"
1379                || root.simple().thread() != Some(thread)
1380                || !root.predecessors.is_empty()
1381                || crate::intend::cast_of(&root.message, d).is_err()
1382            {
1383                return fault(
1384                    "resource root context mismatch",
1385                    alloc::vec![root.address.clone()],
1386                );
1387            }
1388        }
1389    }
1390    observe(c, acts)
1391}
1392
1393/// Context-pinned fold; existing pure `state::fold` retains its precondition
1394/// that the supplied accepted acts already belong to the chosen instance.
1395pub fn fold_instance(
1396    d: &crate::dialect::Dialect,
1397    thread: &str,
1398    acts: &[Act],
1399) -> Vec<(String, Value)> {
1400    let Some(clause) = &d.state else {
1401        return Vec::new();
1402    };
1403    let mut result = crate::state::fold(clause, d.causal_protocol.as_ref(), acts);
1404    for ((_, rule), (_, value)) in clause.fields().zip(result.iter_mut()) {
1405        if let crate::state::Rule::BoundedCounter(c) = rule {
1406            *value = observe_in(d, thread, c, acts).value();
1407        }
1408    }
1409    result
1410}