Skip to main content

cbcl_core/
agent.rs

1//! Agent: a CBCL participant with beliefs, dialects, and message queues.
2//!
3//! Mirrors `Agent.lean` from the Lean 4 proof library (lines 16–39).
4//! The Agent struct holds mutable state for dialect installation, belief
5//! management, and conversation threading.
6
7#![forbid(unsafe_code)]
8
9use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
10use alloc::string::String;
11use alloc::sync::Arc;
12use alloc::vec::Vec;
13
14use crate::clock::{Clock, NoClock};
15use crate::dialect::{Dialect, DialectInstallError, DialectRegistry};
16use crate::evaluator::{Effect, EvalError, EvalResult};
17use crate::message::{CausedBy, Message};
18use crate::policy::{
19    apply_policy, DropReason, PendingEntry, PendingQueue, PendingReason, PolicyOutcome,
20    UnknownPredecessorPolicy,
21};
22use crate::protocol::{verify_causal, CausalViolation, VerificationResult};
23use crate::sexpr::SExpr;
24use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
25
26/// A CBCL agent (REQ-030).
27///
28/// An agent is a participant in the CBCL protocol with:
29/// - a unique identifier
30/// - a set of beliefs (S-expressions)
31/// - a dialect registry (always containing the base dialect at index 0)
32/// - a message queue for incoming messages
33/// - conversation threads indexed by thread id
34///
35/// # Well-formedness Invariant
36///
37/// An agent is well-formed iff `self.dialect_registry.is_well_formed()`,
38/// i.e. the base dialect is always installed at index 0. `Agent::new()`
39/// guarantees this invariant, and no method on `Agent` can violate it.
40#[derive(Debug, Clone)]
41pub struct Agent {
42    id: String,
43    beliefs: BTreeSet<SExpr>,
44    dialect_registry: DialectRegistry,
45    message_queue: VecDeque<Message>,
46    conversation_threads: BTreeMap<String, Vec<Message>>,
47    /// Per-thread message store consulted during causal verification (REQ-300).
48    message_store: ThreadedMessageStore,
49    /// Policy for handling `VerificationResult::Unknown` (REQ-305).
50    policy: UnknownPredecessorPolicy,
51    /// Buffered messages awaiting predecessor arrival under the Buffer policy.
52    pending_queue: PendingQueue,
53    /// How outcomes from multiple matching protocols are combined.
54    merge_policy: MergePolicy,
55    /// Time source for buffered-entry timestamps and TTL expiry. Defaults to
56    /// [`NoClock`], which yields `u64::MAX` so entries never expire — opt
57    /// into TTL by injecting a real clock via [`Agent::with_clock`].
58    clock: Arc<dyn Clock>,
59}
60
61/// How the agent combines verdicts when several installed protocols declare a
62/// step for the same performative.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum MergePolicy {
65    /// Strictest verdict wins: any `Reject` rejects, any `Pending`/`Buffered`
66    /// short-circuits before `Accept`. This is the fail-closed default and
67    /// matches the live verification path the parser pipeline uses.
68    #[default]
69    Conjunction,
70    /// A single `Accept` is enough to apply the message. `Reject` only fires
71    /// when *every* matching protocol rejects; otherwise `Pending`/`Buffered`
72    /// is preserved if no protocol accepted. Useful when multiple protocols
73    /// represent alternative permitted behaviours rather than a stack of
74    /// constraints to satisfy together.
75    ///
76    /// **Security surface.** Disjunction widens trust: with mixed-trust
77    /// dialects, an attacker who can install one permissive protocol can
78    /// override another protocol's rejection. Only opt in when every
79    /// installable dialect is trusted to the same level — typically when
80    /// they originated from the same authority or were verified by R4.
81    /// The pipeline (`run_pipeline_full`) is conjunction-only and remains
82    /// the right entry point for receive-side fail-closed enforcement.
83    Disjunction,
84}
85
86/// Combine two `PolicyOutcome` values under [`MergePolicy::Conjunction`]:
87/// `Reject` > `Pending` > `Buffered` > `Accept`. The strictest outcome wins
88/// so any single protocol can fail-close regardless of what other protocols
89/// say.
90///
91/// When both inputs are `Pending`, the left-hand reason is preserved. Today
92/// `PendingReason` has only one variant, so the choice is moot, but the arm
93/// is explicit so that adding new reasons doesn't silently drop one of them.
94fn merge_policy_outcomes(a: PolicyOutcome, b: PolicyOutcome) -> PolicyOutcome {
95    use PolicyOutcome::*;
96    match (a, b) {
97        (Reject(v), _) | (_, Reject(v)) => Reject(v),
98        (Pending(left), Pending(_right)) => Pending(left),
99        (Pending(r), _) | (_, Pending(r)) => Pending(r),
100        (Buffered, _) | (_, Buffered) => Buffered,
101        (Accept, Accept) => Accept,
102    }
103}
104
105/// Combine two `PolicyOutcome` values under [`MergePolicy::Disjunction`]:
106/// any `Accept` accepts. Otherwise `Pending` > `Buffered` > `Reject`, with
107/// the left-hand `Reject` preserved when both inputs reject (the disjunction
108/// only collapses to a rejection when no matching protocol accepted *and* no
109/// matching protocol left the message pending).
110fn merge_policy_outcomes_disjunctive(a: PolicyOutcome, b: PolicyOutcome) -> PolicyOutcome {
111    use PolicyOutcome::*;
112    match (a, b) {
113        (Accept, _) | (_, Accept) => Accept,
114        (Pending(r), _) | (_, Pending(r)) => Pending(r),
115        (Buffered, _) | (_, Buffered) => Buffered,
116        (Reject(v), _) => Reject(v),
117    }
118}
119
120/// Whether a `:caused-by` reference is *resolved* — every hash it names
121/// present in `thread`'s store (SPEC-003 REQ-315). `Begin` (and an absent
122/// `:caused-by`) name no hashes and count as resolved; `Single`/`Multiple`
123/// check each hash's presence via the store's hash index.
124fn caused_by_resolved(
125    caused_by: Option<&CausedBy>,
126    store: &ThreadedMessageStore,
127    thread: &ThreadId,
128) -> bool {
129    match caused_by {
130        None | Some(CausedBy::Begin) => true,
131        Some(CausedBy::Single(h)) => store.contains(&ContentHash(h.clone()), thread),
132        Some(CausedBy::Multiple(hs)) => hs
133            .iter()
134            .all(|h| store.contains(&ContentHash(h.clone()), thread)),
135    }
136}
137
138/// Resolution gate (SPEC-003 REQ-315): a `Violation` reached while some
139/// named `:caused-by` hash is still absent from the store is *provisional*
140/// — under an `(any …)` clause the eager clause algebra can supersede it
141/// with `Valid` at resolution (the lattice's monotonicity is
142/// valid-is-sticky, not violation-is-sticky, before resolution) — so
143/// action must wait: the verdict is downgraded to `Unknown`, making the
144/// Reject policy answer `CausalPending` and the Buffer policy enqueue,
145/// exactly as for any `Unknown`. A *resolved* `Violation` (every named
146/// hash present) is permanent under store growth and still maps to
147/// `Reject`.
148fn gate_unresolved_violation(result: VerificationResult, resolved: bool) -> VerificationResult {
149    if !resolved && matches!(result, VerificationResult::Violation(_)) {
150        VerificationResult::Unknown
151    } else {
152        result
153    }
154}
155
156/// Outcome of [`Agent::evaluate_and_apply`] (REQ-231 fail-closed contract).
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum AgentOutcome {
159    /// Causal verification succeeded (or was not applicable) and the message
160    /// was evaluated, with effects applied to the agent.
161    Applied(EvalResult),
162    /// Causal protocol violation; message was not evaluated.
163    CausalReject(CausalViolation),
164    /// Predecessor not yet in the local store under [`UnknownPredecessorPolicy::Reject`];
165    /// senders should retry once the predecessor arrives.
166    Pending(PendingReason),
167    /// Predecessor not yet in the local store under [`UnknownPredecessorPolicy::Buffer`];
168    /// the agent has enqueued the message for later re-evaluation.
169    Buffered,
170    /// Evaluator failure (template expansion, unknown performative, etc.).
171    EvalError(EvalError),
172}
173
174impl Agent {
175    /// Create a new agent with the given id, bootstrapped with the base dialect (REQ-031).
176    ///
177    /// The returned agent is always well-formed: the dialect registry
178    /// contains exactly the base dialect.
179    pub fn new(id: impl Into<String>) -> Self {
180        Self::with_policy(id, UnknownPredecessorPolicy::default())
181    }
182
183    /// Create a new agent with the given id and unknown-predecessor policy.
184    pub fn with_policy(id: impl Into<String>, policy: UnknownPredecessorPolicy) -> Self {
185        let pending_queue = match &policy {
186            UnknownPredecessorPolicy::Buffer { max_pending, ttl } => {
187                PendingQueue::new(*max_pending, *ttl)
188            }
189            UnknownPredecessorPolicy::Reject => PendingQueue::new(0, 0),
190        };
191        Self {
192            id: id.into(),
193            beliefs: BTreeSet::new(),
194            dialect_registry: DialectRegistry::new(),
195            message_queue: VecDeque::new(),
196            conversation_threads: BTreeMap::new(),
197            message_store: ThreadedMessageStore::new(),
198            policy,
199            pending_queue,
200            merge_policy: MergePolicy::default(),
201            clock: Arc::new(NoClock),
202        }
203    }
204
205    /// Set how outcomes from multiple matching protocols are combined.
206    /// Defaults to [`MergePolicy::Conjunction`] (fail-closed).
207    pub fn with_merge_policy(mut self, merge_policy: MergePolicy) -> Self {
208        self.merge_policy = merge_policy;
209        self
210    }
211
212    /// Returns the configured merge policy.
213    pub fn merge_policy(&self) -> MergePolicy {
214        self.merge_policy
215    }
216
217    /// Inject a [`Clock`] for buffered-entry timestamps and TTL expiry.
218    ///
219    /// Without this, the agent uses [`NoClock`] which stamps every buffered
220    /// entry with `u64::MAX`, so TTL never fires. Pass [`crate::clock::SystemClock`]
221    /// (with the `std` feature) to use real time, or any custom `Clock`
222    /// implementation — useful for deterministic tests.
223    pub fn with_clock<C: Clock + 'static>(mut self, clock: C) -> Self {
224        self.clock = Arc::new(clock);
225        self
226    }
227
228    /// Returns a reference to the agent's message store.
229    pub fn message_store(&self) -> &ThreadedMessageStore {
230        &self.message_store
231    }
232
233    /// Mutable access to the agent's message store. Callers manage content
234    /// hashing — the agent itself does not synthesize hashes.
235    pub fn message_store_mut(&mut self) -> &mut ThreadedMessageStore {
236        &mut self.message_store
237    }
238
239    /// Returns the configured unknown-predecessor policy.
240    pub fn policy(&self) -> &UnknownPredecessorPolicy {
241        &self.policy
242    }
243
244    /// Number of buffered (pending) messages awaiting predecessor arrival.
245    pub fn pending_len(&self) -> usize {
246        self.pending_queue.len()
247    }
248
249    /// Returns the agent's identifier.
250    pub fn id(&self) -> &str {
251        &self.id
252    }
253
254    // -- Well-formedness --
255
256    /// Check whether this agent is well-formed (REQ-032).
257    ///
258    /// An agent is well-formed iff the base dialect is installed at index 0
259    /// of the dialect registry. Mirrors `Agent.isWellFormed` in `Agent.lean`.
260    pub fn is_well_formed(&self) -> bool {
261        self.dialect_registry.is_well_formed()
262    }
263
264    // -- Dialect management --
265
266    /// Returns a reference to the dialect registry.
267    pub fn dialect_registry(&self) -> &DialectRegistry {
268        &self.dialect_registry
269    }
270
271    /// Every installed dialect defining `name`, in installation order
272    /// (REQ-033).
273    ///
274    /// Introspection only. Dispatch never uses it: a custom performative is
275    /// resolved against the dialect named by its `(lang …)` wrapper, so more
276    /// than one result here is normal rather than a conflict.
277    pub fn dialects_defining<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Dialect> {
278        self.dialect_registry.dialects_defining(name)
279    }
280
281    /// Install a dialect after verifying R1, R2, and R3 (REQ-034).
282    ///
283    /// Delegates to `DialectRegistry::install`. The well-formedness
284    /// invariant is preserved because install only appends.
285    pub fn install_dialect(&mut self, d: Dialect) -> Result<(), DialectInstallError> {
286        self.dialect_registry.install(d)
287    }
288
289    // -- Beliefs --
290
291    /// Returns a reference to the agent's belief set.
292    pub fn beliefs(&self) -> &BTreeSet<SExpr> {
293        &self.beliefs
294    }
295
296    /// Add a belief to the agent's belief set.
297    /// Returns `true` if the belief was newly inserted.
298    pub fn add_belief(&mut self, belief: SExpr) -> bool {
299        self.beliefs.insert(belief)
300    }
301
302    /// Remove a belief from the agent's belief set.
303    /// Returns `true` if the belief was present.
304    pub fn remove_belief(&mut self, belief: &SExpr) -> bool {
305        self.beliefs.remove(belief)
306    }
307
308    /// Check whether the agent holds a given belief.
309    pub fn has_belief(&self, belief: &SExpr) -> bool {
310        self.beliefs.contains(belief)
311    }
312
313    // -- Message queue --
314
315    /// Returns a reference to the message queue.
316    pub fn message_queue(&self) -> &VecDeque<Message> {
317        &self.message_queue
318    }
319
320    /// Enqueue a message at the back of the message queue.
321    pub fn enqueue_message(&mut self, msg: Message) {
322        self.message_queue.push_back(msg);
323    }
324
325    /// Dequeue a message from the front of the message queue.
326    pub fn dequeue_message(&mut self) -> Option<Message> {
327        self.message_queue.pop_front()
328    }
329
330    /// Returns the number of messages in the queue.
331    pub fn message_queue_len(&self) -> usize {
332        self.message_queue.len()
333    }
334
335    // -- Conversation threads --
336
337    /// Returns a reference to all conversation threads.
338    pub fn conversation_threads(&self) -> &BTreeMap<String, Vec<Message>> {
339        &self.conversation_threads
340    }
341
342    /// Get the messages in a specific conversation thread.
343    pub fn thread(&self, thread_id: &str) -> Option<&[Message]> {
344        self.conversation_threads
345            .get(thread_id)
346            .map(|v| v.as_slice())
347    }
348
349    /// Append a message to a conversation thread, creating the thread if needed.
350    pub fn append_to_thread(&mut self, thread_id: impl Into<String>, msg: Message) {
351        self.conversation_threads
352            .entry(thread_id.into())
353            .or_default()
354            .push(msg);
355    }
356
357    // -- Evaluation --
358
359    /// Evaluate a message and apply its effects to this agent.
360    ///
361    /// Pipeline (REQ-231 fail-closed):
362    /// 1. Causal verification against the agent's dialect registry, message
363    ///    store, and configured [`UnknownPredecessorPolicy`].
364    /// 2. On `Accept`: evaluate the message and apply its effects.
365    /// 3. On a *resolved* `Violation`: return [`AgentOutcome::CausalReject`]
366    ///    without applying. A provisional `Violation` — some named
367    ///    `:caused-by` hash still absent from the store — is downgraded to
368    ///    `Unknown` first (SPEC-003 REQ-315), so it follows 4/5 instead.
369    /// 4. On `Unknown` + `Reject` policy: return [`AgentOutcome::Pending`].
370    /// 5. On `Unknown` + `Buffer` policy: enqueue in the pending queue and
371    ///    return [`AgentOutcome::Buffered`]; the message is *not* applied.
372    ///
373    /// Buffered entries are timestamped via the injected [`Clock`]. With the
374    /// default [`NoClock`] this is `u64::MAX`, so [`Self::expire`] will never
375    /// drain them. Inject a real clock via [`Self::with_clock`] (or call
376    /// [`Self::evaluate_and_apply_at`] for an explicit one-off override) to
377    /// enable TTL-based eviction.
378    pub fn evaluate_and_apply(&mut self, msg: &Message) -> AgentOutcome {
379        let now = self.clock.now();
380        self.evaluate_and_apply_at(msg, now)
381    }
382
383    /// Like [`Self::evaluate_and_apply`] but stamps any newly-buffered entry
384    /// with the supplied `now` (seconds since epoch), bypassing the injected
385    /// clock. Useful for tests or when the caller wants per-message control
386    /// over the timestamp.
387    pub fn evaluate_and_apply_at(&mut self, msg: &Message, now: u64) -> AgentOutcome {
388        // Step 1: causal verification (only meaningful for Simple messages with a
389        // performative whose owning dialect declares a causal protocol).
390        if let Some(verdict) = self.causal_verdict(msg) {
391            match verdict {
392                PolicyOutcome::Accept => {}
393                PolicyOutcome::Reject(cv) => return AgentOutcome::CausalReject(cv),
394                PolicyOutcome::Pending(reason) => return AgentOutcome::Pending(reason),
395                PolicyOutcome::Buffered => {
396                    self.buffer_pending(msg, now);
397                    return AgentOutcome::Buffered;
398                }
399            }
400        }
401
402        // Step 2: evaluate and apply.
403        let result = match crate::evaluator::evaluate(msg, &self.dialect_registry) {
404            Ok(r) => r,
405            Err(e) => return AgentOutcome::EvalError(e),
406        };
407
408        for effect in &result.effects {
409            match effect {
410                Effect::StoreBelief(belief) => {
411                    self.add_belief(belief.clone());
412                }
413                Effect::RemoveBelief(belief) => {
414                    self.remove_belief(belief);
415                }
416                _ => {
417                    // Other effects (send, announce, etc.) are returned to the
418                    // caller for external handling — the agent cannot perform
419                    // I/O itself.
420                }
421            }
422        }
423
424        if let Some(ref thread_id) = result.thread {
425            self.append_to_thread(thread_id.clone(), msg.clone());
426        }
427
428        AgentOutcome::Applied(result)
429    }
430
431    /// Run causal verification + policy mapping for a message.
432    ///
433    /// Returns `None` when no installed protocol constrains the message —
434    /// the innermost payload is not Simple, or no installed dialect declares
435    /// a protocol step for its performative.
436    ///
437    /// Multiple installed dialects may declare protocols for the same
438    /// performative (notably child dialects constraining a base/inherited
439    /// performative such as `ok`); constraints compose by conjunction so any
440    /// rejection short-circuits, with `Pending`/`Buffered` outranking
441    /// `Accept`. This mirrors the full pipeline's step 6a.
442    ///
443    /// Each per-protocol verdict passes through the REQ-315 resolution gate
444    /// ([`gate_unresolved_violation`]) before [`apply_policy`], so only
445    /// resolved `Violation`s can become `Reject`.
446    fn causal_verdict(&self, msg: &Message) -> Option<PolicyOutcome> {
447        let inner = msg.innermost_simple()?;
448        let (caused_by, thread, perf_name) = match inner {
449            Message::Simple {
450                caused_by,
451                thread,
452                performative,
453                ..
454            } => (caused_by.as_ref(), thread.as_ref(), performative.name()),
455            _ => return None,
456        };
457
458        let thread_id = ThreadId(thread.cloned().unwrap_or_else(|| String::from("default")));
459
460        // SPEC-003 REQ-315: resolvedness is a property of the message and
461        // store alone, shared by every matching protocol's verdict.
462        let resolved = caused_by_resolved(caused_by, &self.message_store, &thread_id);
463
464        let mut decision: Option<PolicyOutcome> = None;
465        for d in self.dialect_registry.iter() {
466            let Some(ref proto) = d.causal_protocol else {
467                continue;
468            };
469            if !proto.steps.contains_key(perf_name) {
470                continue;
471            }
472            let result =
473                verify_causal(perf_name, caused_by, &self.message_store, proto, &thread_id);
474            let result = gate_unresolved_violation(result, resolved);
475            let outcome = apply_policy(&result, &self.policy);
476            decision = Some(match decision {
477                None => outcome,
478                Some(prev) => match self.merge_policy {
479                    MergePolicy::Conjunction => merge_policy_outcomes(prev, outcome),
480                    MergePolicy::Disjunction => merge_policy_outcomes_disjunctive(prev, outcome),
481                },
482            });
483            // Conjunction can short-circuit on Reject (any rejection wins);
484            // Disjunction can short-circuit on Accept (any accept wins).
485            match (self.merge_policy, &decision) {
486                (MergePolicy::Conjunction, Some(PolicyOutcome::Reject(_))) => break,
487                (MergePolicy::Disjunction, Some(PolicyOutcome::Accept)) => break,
488                _ => {}
489            }
490        }
491        decision
492    }
493
494    /// Enqueue a message in the pending queue under the Buffer policy.
495    ///
496    /// Buffers the original (possibly wrapped) message, but uses the
497    /// innermost Simple's caused_by/thread/performative for re-evaluation
498    /// keys so wrapped pending messages are handled identically to bare ones.
499    /// `now` (seconds since epoch) is stamped onto the entry for use by
500    /// [`Self::expire`]; callers that don't need TTL semantics can pass
501    /// `u64::MAX` to opt out.
502    fn buffer_pending(&mut self, msg: &Message, now: u64) {
503        let Some(inner) = msg.innermost_simple() else {
504            return;
505        };
506        let Message::Simple {
507            caused_by,
508            thread,
509            performative,
510            ..
511        } = inner
512        else {
513            return;
514        };
515        let thread_id = ThreadId(thread.clone().unwrap_or_else(|| String::from("default")));
516
517        // The agent does not synthesize content hashes; store an empty hash for
518        // the buffered entry. Callers that re-evaluate will look up by
519        // :caused-by, which is what verify_causal needs.
520        let entry = PendingEntry {
521            hash: ContentHash(String::new()),
522            message: msg.clone(),
523            thread: thread_id,
524            performative: String::from(performative.name()),
525            caused_by: caused_by.clone(),
526            inserted_at: now,
527        };
528        self.pending_queue.enqueue(entry);
529    }
530
531    /// Drop buffered entries whose TTL has elapsed at `now` (seconds since
532    /// epoch). Returns the dropped entries with [`DropReason::CausalTimeout`].
533    ///
534    /// Entries stamped with `u64::MAX` (the default when the agent is
535    /// constructed without a clock and [`Self::evaluate_and_apply`] is used)
536    /// never expire. To get TTL behaviour, either inject a real clock via
537    /// [`Self::with_clock`] or pass an explicit timestamp via
538    /// [`Self::evaluate_and_apply_at`] / [`Self::step_at`].
539    ///
540    /// **Eviction is pull-based.** The agent does not call `expire` on its
541    /// own — the embedder is responsible for invoking it on a schedule that
542    /// matches the configured TTL (e.g. once per second, once per minute).
543    /// Without that, expired entries linger in the queue until the next
544    /// caller-driven invocation, holding memory but not causing
545    /// correctness issues. A future revision could opt-in to expire-on-each
546    /// `evaluate_and_apply` if it becomes a footgun in practice.
547    pub fn expire(&mut self, now: u64) -> Vec<(PendingEntry, DropReason)> {
548        self.pending_queue.expire(now)
549    }
550
551    /// Re-evaluate buffered messages against the (possibly grown) message store.
552    ///
553    /// Returns the entries that now resolve to either `Accept` or `Reject`.
554    /// Entries whose performative isn't constrained by any installed
555    /// protocol stay buffered (rather than being spuriously accepted by an
556    /// unrelated protocol — `verify_causal` returns `Valid` for performatives
557    /// outside a protocol's step set, so iterating naively over every
558    /// installed protocol would flush entries that are still waiting on
559    /// their real predecessor).
560    ///
561    /// When multiple protocols constrain the same performative, results
562    /// compose by conjunction (any rejection rejects, any `Unknown` keeps
563    /// pending) — the same semantics as the live verification path.
564    ///
565    /// The caller is responsible for re-applying accepted messages; the
566    /// agent does not auto-apply them, since [`Agent::evaluate_and_apply`]
567    /// mutates state and the caller may want explicit control over re-entry.
568    pub fn reevaluate_pending(&mut self) -> Vec<(PendingEntry, PolicyOutcome)> {
569        let registry = &self.dialect_registry;
570        let store = &self.message_store;
571        let merge = self.merge_policy;
572        self.pending_queue.re_evaluate_with(|entry, thread_id| {
573            // SPEC-003 REQ-315: same resolution gate as the live path — a
574            // still-provisional Violation keeps the entry pending rather
575            // than flushing it as Reject.
576            let resolved = caused_by_resolved(entry.caused_by.as_ref(), store, thread_id);
577            let mut combined: Option<VerificationResult> = None;
578            for d in registry.iter() {
579                let Some(ref proto) = d.causal_protocol else {
580                    continue;
581                };
582                if !proto.steps.contains_key(entry.performative.as_str()) {
583                    continue;
584                }
585                let r = verify_causal(
586                    &entry.performative,
587                    entry.caused_by.as_ref(),
588                    store,
589                    proto,
590                    thread_id,
591                );
592                let r = gate_unresolved_violation(r, resolved);
593                combined = Some(match combined {
594                    None => r,
595                    Some(prev) => match merge {
596                        // Conjunction = lattice meet (Unknown < Valid; Valid ⊓ Violation = Violation).
597                        MergePolicy::Conjunction => prev.meet(r),
598                        // Strong Kleene disjunction preserves a pending alternative.
599                        MergePolicy::Disjunction => prev.join(r),
600                    },
601                });
602            }
603            combined
604        })
605    }
606
607    /// Dequeue the next message, evaluate it, and apply effects.
608    ///
609    /// Returns `None` if the queue is empty. Buffered entries inherit the
610    /// `u64::MAX` timestamp from [`Self::evaluate_and_apply`]; use
611    /// [`Self::step_at`] when TTL semantics are required.
612    pub fn step(&mut self) -> Option<AgentOutcome> {
613        let msg = self.dequeue_message()?;
614        Some(self.evaluate_and_apply(&msg))
615    }
616
617    /// Like [`Self::step`] but stamps any newly-buffered entry with `now`.
618    pub fn step_at(&mut self, now: u64) -> Option<AgentOutcome> {
619        let msg = self.dequeue_message()?;
620        Some(self.evaluate_and_apply_at(&msg, now))
621    }
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use crate::dialect::{PerformativeDef, ResourceBounds};
628    use crate::message::{CorePerformative, Performative};
629    use crate::sexpr::Atom;
630
631    fn valid_custom_dialect(name: &str) -> Dialect {
632        Dialect {
633            types: Default::default(),
634            roles: Vec::new(),
635            state: None,
636            state_bounds: None,
637            causal_locality: Default::default(),
638            name: String::from(name),
639            extends: Vec::new(),
640            author: None,
641            performatives: vec![PerformativeDef {
642                role: None,
643                name: String::from("custom-action"),
644                params: Vec::new(),
645                template: SExpr::List(alloc::vec![
646                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
647                    SExpr::Atom(Atom::Symbol(String::from("custom"))),
648                ]),
649            }],
650            resources: ResourceBounds {
651                max_depth: 8,
652                max_expansion_size: 512,
653            },
654            examples: Vec::new(),
655            signature: None,
656            hash: None,
657            protocol: None,
658            causal_protocol: None,
659            shapes: Vec::new(),
660        }
661    }
662
663    fn simple_tell(content: &str) -> Message {
664        Message::Simple {
665            performative: Performative::Core(CorePerformative::Tell),
666            recipient: None,
667            content: SExpr::Atom(Atom::Str(String::from(content))),
668            params: Vec::new(),
669            thread: None,
670            sender: None,
671            caused_by: None,
672        }
673    }
674
675    // -- Construction and well-formedness --
676
677    #[test]
678    fn new_agent_is_well_formed() {
679        let agent = Agent::new("agent-1");
680        assert!(agent.is_well_formed());
681        assert_eq!(agent.id(), "agent-1");
682    }
683
684    #[test]
685    fn new_agent_has_base_dialect() {
686        let agent = Agent::new("a");
687        assert_eq!(agent.dialect_registry().len(), 1);
688        assert_eq!(agent.dialect_registry().get(0).unwrap().name, "cbcl-base");
689    }
690
691    #[test]
692    fn new_agent_has_empty_beliefs() {
693        let agent = Agent::new("a");
694        assert!(agent.beliefs().is_empty());
695    }
696
697    #[test]
698    fn new_agent_has_empty_message_queue() {
699        let agent = Agent::new("a");
700        assert_eq!(agent.message_queue_len(), 0);
701        assert!(agent.message_queue().is_empty());
702    }
703
704    #[test]
705    fn new_agent_has_empty_threads() {
706        let agent = Agent::new("a");
707        assert!(agent.conversation_threads().is_empty());
708    }
709
710    // -- Dialect management --
711
712    #[test]
713    fn install_dialect_preserves_well_formedness() {
714        let mut agent = Agent::new("a");
715        agent.install_dialect(valid_custom_dialect("ext")).unwrap();
716        assert!(agent.is_well_formed());
717        assert_eq!(agent.dialect_registry().len(), 2);
718    }
719
720    #[test]
721    fn dialects_defining_finds_custom() {
722        let mut agent = Agent::new("a");
723        agent.install_dialect(valid_custom_dialect("ext")).unwrap();
724        let names: Vec<&str> = agent
725            .dialects_defining("custom-action")
726            .map(|d| d.name.as_str())
727            .collect();
728        assert_eq!(names, vec!["ext"]);
729    }
730
731    /// REQ-033: two dialects defining one performative name is legitimate —
732    /// the `(lang …)` wrapper says which is meant — so introspection reports
733    /// both rather than treating the second as a conflict.
734    #[test]
735    fn dialects_defining_reports_every_definer() {
736        let mut agent = Agent::new("a");
737        agent.install_dialect(valid_custom_dialect("ext")).unwrap();
738        agent.install_dialect(valid_custom_dialect("ext2")).unwrap();
739        let names: Vec<&str> = agent
740            .dialects_defining("custom-action")
741            .map(|d| d.name.as_str())
742            .collect();
743        assert_eq!(names, vec!["ext", "ext2"]);
744    }
745
746    #[test]
747    fn install_bad_dialect_rejected() {
748        let mut agent = Agent::new("a");
749        let bad = Dialect {
750            types: Default::default(),
751            roles: Vec::new(),
752            state: None,
753            state_bounds: None,
754            causal_locality: Default::default(),
755            name: String::from("bad"),
756            extends: Vec::new(),
757            author: None,
758            performatives: vec![PerformativeDef {
759                role: None,
760                name: String::from("tell"), // R3 violation: redefines core
761                params: Vec::new(),
762                template: SExpr::Atom(Atom::Symbol(String::from("x"))),
763            }],
764            resources: ResourceBounds {
765                max_depth: 8,
766                max_expansion_size: 512,
767            },
768            examples: Vec::new(),
769            signature: None,
770            hash: None,
771            protocol: None,
772            causal_protocol: None,
773            shapes: Vec::new(),
774        };
775        assert!(agent.install_dialect(bad).is_err());
776        // Still well-formed, still only base dialect
777        assert!(agent.is_well_formed());
778        assert_eq!(agent.dialect_registry().len(), 1);
779    }
780
781    // -- Beliefs --
782
783    #[test]
784    fn add_and_check_belief() {
785        let mut agent = Agent::new("a");
786        let belief = SExpr::Atom(Atom::Symbol(String::from("sky-is-blue")));
787        assert!(!agent.has_belief(&belief));
788        assert!(agent.add_belief(belief.clone()));
789        assert!(agent.has_belief(&belief));
790        assert_eq!(agent.beliefs().len(), 1);
791    }
792
793    #[test]
794    fn add_duplicate_belief() {
795        let mut agent = Agent::new("a");
796        let belief = SExpr::Atom(Atom::Num(42));
797        assert!(agent.add_belief(belief.clone()));
798        assert!(!agent.add_belief(belief)); // duplicate
799        assert_eq!(agent.beliefs().len(), 1);
800    }
801
802    #[test]
803    fn remove_belief() {
804        let mut agent = Agent::new("a");
805        let belief = SExpr::Atom(Atom::Bool(true));
806        agent.add_belief(belief.clone());
807        assert!(agent.remove_belief(&belief));
808        assert!(!agent.has_belief(&belief));
809        assert!(agent.beliefs().is_empty());
810    }
811
812    #[test]
813    fn remove_absent_belief() {
814        let mut agent = Agent::new("a");
815        let belief = SExpr::Atom(Atom::Num(1));
816        assert!(!agent.remove_belief(&belief));
817    }
818
819    // -- Message queue --
820
821    #[test]
822    fn enqueue_dequeue_fifo() {
823        let mut agent = Agent::new("a");
824        agent.enqueue_message(simple_tell("first"));
825        agent.enqueue_message(simple_tell("second"));
826        assert_eq!(agent.message_queue_len(), 2);
827
828        let first = agent.dequeue_message().unwrap();
829        assert_eq!(
830            first.content(),
831            Some(&SExpr::Atom(Atom::Str(String::from("first"))))
832        );
833
834        let second = agent.dequeue_message().unwrap();
835        assert_eq!(
836            second.content(),
837            Some(&SExpr::Atom(Atom::Str(String::from("second"))))
838        );
839
840        assert!(agent.dequeue_message().is_none());
841    }
842
843    // -- Conversation threads --
844
845    #[test]
846    fn append_to_thread_creates_thread() {
847        let mut agent = Agent::new("a");
848        agent.append_to_thread("t1", simple_tell("hello"));
849        assert_eq!(agent.thread("t1").unwrap().len(), 1);
850    }
851
852    #[test]
853    fn append_to_thread_accumulates() {
854        let mut agent = Agent::new("a");
855        agent.append_to_thread("t1", simple_tell("msg1"));
856        agent.append_to_thread("t1", simple_tell("msg2"));
857        assert_eq!(agent.thread("t1").unwrap().len(), 2);
858    }
859
860    #[test]
861    fn absent_thread_returns_none() {
862        let agent = Agent::new("a");
863        assert!(agent.thread("nonexistent").is_none());
864    }
865
866    #[test]
867    fn multiple_threads() {
868        let mut agent = Agent::new("a");
869        agent.append_to_thread("t1", simple_tell("a"));
870        agent.append_to_thread("t2", simple_tell("b"));
871        assert_eq!(agent.conversation_threads().len(), 2);
872        assert_eq!(agent.thread("t1").unwrap().len(), 1);
873        assert_eq!(agent.thread("t2").unwrap().len(), 1);
874    }
875
876    // -- Evaluation --
877
878    fn expect_applied(outcome: AgentOutcome) -> EvalResult {
879        match outcome {
880            AgentOutcome::Applied(r) => r,
881            other => panic!("expected Applied, got {other:?}"),
882        }
883    }
884
885    #[test]
886    fn evaluate_and_apply_stores_belief_on_tell() {
887        let mut agent = Agent::new("@alice");
888        let msg = simple_tell("the sky is blue");
889        let result = expect_applied(agent.evaluate_and_apply(&msg));
890        // tell produces StoreBelief effect → agent should hold the belief
891        assert!(agent.has_belief(&SExpr::Atom(Atom::Str(String::from("the sky is blue")))));
892        assert!(!result.effects.is_empty());
893    }
894
895    #[test]
896    fn evaluate_and_apply_tracks_thread() {
897        let mut agent = Agent::new("@alice");
898        let msg = Message::Simple {
899            performative: Performative::Core(CorePerformative::Tell),
900            recipient: Some("@bob".into()),
901            content: SExpr::Atom(Atom::Str(String::from("hello"))),
902            params: Vec::new(),
903            thread: Some(String::from("conv-1")),
904            sender: Some(String::from("@alice")),
905            caused_by: None,
906        };
907        let _ = expect_applied(agent.evaluate_and_apply(&msg));
908        assert_eq!(agent.thread("conv-1").unwrap().len(), 1);
909    }
910
911    #[test]
912    fn step_processes_queued_message() {
913        let mut agent = Agent::new("@alice");
914        agent.enqueue_message(simple_tell("fact-1"));
915        agent.enqueue_message(simple_tell("fact-2"));
916
917        let _r1 = expect_applied(agent.step().unwrap());
918        assert!(agent.has_belief(&SExpr::Atom(Atom::Str(String::from("fact-1")))));
919        assert_eq!(agent.message_queue_len(), 1);
920
921        let _r2 = expect_applied(agent.step().unwrap());
922        assert!(agent.has_belief(&SExpr::Atom(Atom::Str(String::from("fact-2")))));
923        assert_eq!(agent.message_queue_len(), 0);
924    }
925
926    #[test]
927    fn step_returns_none_on_empty_queue() {
928        let mut agent = Agent::new("@alice");
929        assert!(agent.step().is_none());
930    }
931
932    #[test]
933    fn evaluate_and_apply_no_thread_no_tracking() {
934        let mut agent = Agent::new("@alice");
935        let msg = simple_tell("hi");
936        let _ = expect_applied(agent.evaluate_and_apply(&msg));
937        assert!(agent.conversation_threads().is_empty());
938    }
939
940    // -- REQ-231 / REQ-305: agent enforces causal verification --
941
942    fn ack_dialect_with_protocol() -> Dialect {
943        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
944        let mut steps = alloc::collections::BTreeMap::new();
945        steps.insert(
946            "begin".into(),
947            StepDecl {
948                performative: "begin".into(),
949                predecessors: alloc::vec![],
950                successors: alloc::vec![NodeRef::Single("ack".into())],
951            },
952        );
953        steps.insert(
954            "ack".into(),
955            StepDecl {
956                performative: "ack".into(),
957                predecessors: alloc::vec![NodeRef::Single("begin".into())],
958                successors: alloc::vec![],
959            },
960        );
961        let proto = CausalProtocol { steps };
962
963        Dialect {
964            types: Default::default(),
965            roles: Vec::new(),
966            state: None,
967            state_bounds: None,
968            causal_locality: Default::default(),
969            name: String::from("ack-dialect"),
970            extends: alloc::vec![String::from("cbcl")],
971            author: None,
972            performatives: vec![PerformativeDef {
973                role: None,
974                name: String::from("ack"),
975                params: Vec::new(),
976                template: SExpr::List(alloc::vec![
977                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
978                    SExpr::Atom(Atom::Symbol(String::from("ack-action"))),
979                ]),
980            }],
981            resources: ResourceBounds {
982                max_depth: 8,
983                max_expansion_size: 512,
984            },
985            examples: Vec::new(),
986            signature: None,
987            hash: None,
988            protocol: None,
989            causal_protocol: Some(proto),
990            shapes: Vec::new(),
991        }
992    }
993
994    fn ack_with_caused_by(hash: &str) -> Message {
995        Message::Dialect {
996            dialect_name: String::from("ack-dialect"),
997            inner: alloc::boxed::Box::new(Message::Simple {
998                performative: Performative::Custom(String::from("ack")),
999                recipient: None,
1000                content: SExpr::Atom(Atom::Str(String::from("done"))),
1001                params: Vec::new(),
1002                thread: None,
1003                sender: None,
1004                caused_by: Some(crate::message::CausedBy::Single(String::from(hash))),
1005            }),
1006        }
1007    }
1008
1009    #[test]
1010    fn agent_rejects_unknown_predecessor_under_default_policy() {
1011        let mut agent = Agent::new("@alice");
1012        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1013        let msg = ack_with_caused_by("missing-hash");
1014        match agent.evaluate_and_apply(&msg) {
1015            AgentOutcome::Pending(_) => {}
1016            other => panic!("expected Pending under default Reject policy, got {other:?}"),
1017        }
1018        // No belief stored, no thread tracked — message was not applied.
1019        assert!(agent.beliefs().is_empty());
1020    }
1021
1022    #[test]
1023    fn agent_buffers_unknown_predecessor_under_buffer_policy() {
1024        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(60));
1025        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1026        let msg = ack_with_caused_by("missing-hash");
1027        match agent.evaluate_and_apply(&msg) {
1028            AgentOutcome::Buffered => {}
1029            other => panic!("expected Buffered under Buffer policy, got {other:?}"),
1030        }
1031        assert_eq!(agent.pending_len(), 1);
1032    }
1033
1034    #[test]
1035    fn agent_rejects_missing_caused_by_when_protocol_requires_predecessor() {
1036        let mut agent = Agent::new("@alice");
1037        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1038        // ack with no :caused-by; protocol requires "begin" as predecessor.
1039        let msg = Message::Simple {
1040            performative: Performative::Custom(String::from("ack")),
1041            recipient: None,
1042            content: SExpr::Atom(Atom::Str(String::from("done"))),
1043            params: Vec::new(),
1044            thread: None,
1045            sender: None,
1046            caused_by: None,
1047        };
1048        match agent.evaluate_and_apply(&msg) {
1049            AgentOutcome::CausalReject(crate::protocol::CausalViolation::MissingCausedBy) => {}
1050            other => panic!("expected CausalReject(MissingCausedBy), got {other:?}"),
1051        }
1052    }
1053
1054    #[test]
1055    fn agent_accepts_when_predecessor_is_present() {
1056        use crate::store::ContentHash as Hash;
1057        let mut agent = Agent::new("@alice");
1058        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1059
1060        // Insert a "begin" message into the agent's store.
1061        let begin = Message::Simple {
1062            performative: Performative::Custom(String::from("begin")),
1063            recipient: None,
1064            content: SExpr::Atom(Atom::Str(String::from("start"))),
1065            params: Vec::new(),
1066            thread: None,
1067            sender: None,
1068            caused_by: Some(crate::message::CausedBy::Begin),
1069        };
1070        agent.message_store_mut().append(
1071            Hash(String::from("begin-hash")),
1072            ThreadId(String::from("default")),
1073            begin,
1074        );
1075
1076        let msg = ack_with_caused_by("begin-hash");
1077        let outcome = agent.evaluate_and_apply(&msg);
1078        match outcome {
1079            AgentOutcome::Applied(_) => {}
1080            other => panic!("expected Applied, got {other:?}"),
1081        }
1082    }
1083
1084    // -- SPEC-003 REQ-315 / TEST-355: resolution-gated rejection --
1085
1086    /// Dialect whose protocol gives `z` the disjunctive clause `(any x y)`.
1087    fn any_xy_dialect() -> Dialect {
1088        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1089        let mut any_set = alloc::collections::BTreeSet::new();
1090        any_set.insert(String::from("x"));
1091        any_set.insert(String::from("y"));
1092        let mut steps = alloc::collections::BTreeMap::new();
1093        steps.insert(
1094            "begin".into(),
1095            StepDecl {
1096                performative: "begin".into(),
1097                predecessors: alloc::vec![],
1098                successors: alloc::vec![NodeRef::Single("x".into()), NodeRef::Single("y".into()),],
1099            },
1100        );
1101        steps.insert(
1102            "x".into(),
1103            StepDecl {
1104                performative: "x".into(),
1105                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1106                successors: alloc::vec![NodeRef::Single("z".into())],
1107            },
1108        );
1109        steps.insert(
1110            "y".into(),
1111            StepDecl {
1112                performative: "y".into(),
1113                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1114                successors: alloc::vec![NodeRef::Single("z".into())],
1115            },
1116        );
1117        steps.insert(
1118            "z".into(),
1119            StepDecl {
1120                performative: "z".into(),
1121                predecessors: alloc::vec![NodeRef::Any(any_set)],
1122                successors: alloc::vec![],
1123            },
1124        );
1125        let def = |name: &str| PerformativeDef {
1126            role: None,
1127            name: String::from(name),
1128            params: Vec::new(),
1129            template: SExpr::List(alloc::vec![
1130                SExpr::Atom(Atom::Symbol(String::from("effect"))),
1131                SExpr::Atom(Atom::Symbol(alloc::format!("{name}-action"))),
1132            ]),
1133        };
1134        Dialect {
1135            types: Default::default(),
1136            roles: Vec::new(),
1137            state: None,
1138            state_bounds: None,
1139            causal_locality: Default::default(),
1140            name: String::from("any-xy"),
1141            extends: alloc::vec![String::from("cbcl")],
1142            author: None,
1143            performatives: vec![def("x"), def("y"), def("z")],
1144            resources: ResourceBounds {
1145                max_depth: 8,
1146                max_expansion_size: 512,
1147            },
1148            examples: Vec::new(),
1149            signature: None,
1150            hash: None,
1151            protocol: None,
1152            causal_protocol: Some(CausalProtocol { steps }),
1153            shapes: Vec::new(),
1154        }
1155    }
1156
1157    fn z_with_caused_by_hashes(hashes: &[&str]) -> Message {
1158        Message::Simple {
1159            performative: Performative::Custom(String::from("z")),
1160            recipient: None,
1161            content: SExpr::Atom(Atom::Str(String::from("zed"))),
1162            params: Vec::new(),
1163            thread: None,
1164            sender: None,
1165            caused_by: Some(crate::message::CausedBy::Multiple(
1166                hashes.iter().map(|h| String::from(*h)).collect(),
1167            )),
1168        }
1169    }
1170
1171    /// Append a predecessor of the given performative type at `hash` in the
1172    /// default thread.
1173    fn append_pred(agent: &mut Agent, hash: &str, perf: &str) {
1174        use crate::store::ContentHash as Hash;
1175        let msg = Message::Simple {
1176            performative: Performative::Custom(String::from(perf)),
1177            recipient: None,
1178            content: SExpr::Atom(Atom::Str(String::from("p"))),
1179            params: Vec::new(),
1180            thread: None,
1181            sender: None,
1182            caused_by: Some(crate::message::CausedBy::Begin),
1183        };
1184        agent.message_store_mut().append(
1185            Hash(String::from(hash)),
1186            ThreadId(String::from("default")),
1187            msg,
1188        );
1189    }
1190
1191    #[test]
1192    fn agent_gates_provisional_violation_as_pending_until_resolution() {
1193        // TEST-355: m names two hashes under z's `(any x y)` clause — one
1194        // resolving to a stored wrong-typed predecessor, one absent. The
1195        // verifier's verdict is an eager Violation, but the message is
1196        // unresolved, so the agent must answer Pending(CausalPending), NOT
1197        // CausalReject (which the ungated Violation → Reject mapping gave).
1198        let mut agent = Agent::new("@alice");
1199        agent.install_dialect(any_xy_dialect()).unwrap();
1200        append_pred(&mut agent, "h-wrong", "w"); // not x or y
1201        let m = z_with_caused_by_hashes(&["h-absent", "h-wrong"]);
1202        match agent.evaluate_and_apply(&m) {
1203            AgentOutcome::Pending(PendingReason::CausalPending) => {}
1204            other => panic!("expected Pending for a provisional violation, got {other:?}"),
1205        }
1206
1207        // The absent hash arrives wrong-typed too: m is now resolved, the
1208        // Violation is permanent under store growth, and the gate no
1209        // longer applies — a resolved Violation still maps to Reject.
1210        append_pred(&mut agent, "h-absent", "w2");
1211        match agent.evaluate_and_apply(&m) {
1212            AgentOutcome::CausalReject(_) => {}
1213            other => panic!("expected CausalReject once resolved, got {other:?}"),
1214        }
1215    }
1216
1217    #[test]
1218    fn agent_buffers_provisional_violation_until_resolution() {
1219        // TEST-355 under the Buffer policy: a provisional Violation is
1220        // enqueued exactly as an Unknown, and re-evaluation while the
1221        // named hash is still absent keeps it buffered rather than
1222        // flushing it as Reject.
1223        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(60));
1224        agent.install_dialect(any_xy_dialect()).unwrap();
1225        append_pred(&mut agent, "h-wrong", "w");
1226        let m = z_with_caused_by_hashes(&["h-absent", "h-wrong"]);
1227        match agent.evaluate_and_apply(&m) {
1228            AgentOutcome::Buffered => {}
1229            other => panic!("expected Buffered, got {other:?}"),
1230        }
1231        assert_eq!(agent.pending_len(), 1);
1232
1233        // Still unresolved: the re-evaluation gate keeps it pending.
1234        let resolved = agent.reevaluate_pending();
1235        assert!(
1236            resolved.is_empty(),
1237            "provisional violation must stay buffered, got {resolved:?}"
1238        );
1239        assert_eq!(agent.pending_len(), 1);
1240
1241        // Resolution with a second wrong-typed predecessor: flushed as
1242        // Reject.
1243        append_pred(&mut agent, "h-absent", "w2");
1244        let resolved = agent.reevaluate_pending();
1245        assert_eq!(resolved.len(), 1);
1246        match &resolved[0].1 {
1247            PolicyOutcome::Reject(_) => {}
1248            other => panic!("expected Reject after resolution, got {other:?}"),
1249        }
1250        assert_eq!(agent.pending_len(), 0);
1251    }
1252
1253    #[test]
1254    fn agent_still_rejects_resolved_violation_immediately() {
1255        // REQ-315's other half: when every named hash is present, a
1256        // Violation is permanent under store growth and maps straight to
1257        // Reject — the gate must not delay it.
1258        let mut agent = Agent::new("@alice");
1259        agent.install_dialect(any_xy_dialect()).unwrap();
1260        append_pred(&mut agent, "h-wrong", "w");
1261        let m = Message::Simple {
1262            performative: Performative::Custom(String::from("z")),
1263            recipient: None,
1264            content: SExpr::Atom(Atom::Str(String::from("zed"))),
1265            params: Vec::new(),
1266            thread: None,
1267            sender: None,
1268            caused_by: Some(crate::message::CausedBy::Single(String::from("h-wrong"))),
1269        };
1270        match agent.evaluate_and_apply(&m) {
1271            AgentOutcome::CausalReject(crate::protocol::CausalViolation::InvalidPredecessor {
1272                ..
1273            }) => {}
1274            other => panic!("expected CausalReject(InvalidPredecessor), got {other:?}"),
1275        }
1276    }
1277
1278    #[test]
1279    fn resolution_with_legal_type_still_rejects_multi_hash_any_reference() {
1280        // TEST-355's remaining branch expects that once the absent hash
1281        // arrives with a *legal* type (x or y), m verifies Valid and is
1282        // accepted. The deployed `verify_causal` has no multi-hash
1283        // evaluation for `(any …)` clauses — a `Multiple` reference
1284        // without an `(all …)` declaration is FanInWithoutAllDecl
1285        // regardless of the store — so at resolution the verdict is a
1286        // (resolved) Violation and the gate correctly stands aside. This
1287        // test pins that gap: delivering the Accept branch of TEST-355
1288        // needs `(any …)` clause evaluation over multi-hash references in
1289        // the verifier, which REQ-315 scopes out of this change.
1290        let mut agent = Agent::new("@alice");
1291        agent.install_dialect(any_xy_dialect()).unwrap();
1292        append_pred(&mut agent, "h-wrong", "w");
1293        let m = z_with_caused_by_hashes(&["h-absent", "h-wrong"]);
1294        match agent.evaluate_and_apply(&m) {
1295            AgentOutcome::Pending(PendingReason::CausalPending) => {}
1296            other => panic!("expected Pending pre-resolution, got {other:?}"),
1297        }
1298        append_pred(&mut agent, "h-absent", "x"); // legal type
1299        match agent.evaluate_and_apply(&m) {
1300            AgentOutcome::CausalReject(crate::protocol::CausalViolation::FanInWithoutAllDecl {
1301                ..
1302            }) => {}
1303            other => panic!("expected CausalReject(FanInWithoutAllDecl), got {other:?}"),
1304        }
1305    }
1306
1307    // -- PR feedback P1: wrappers must not bypass agent causal verification. --
1308
1309    fn ack_simple_with_missing_predecessor() -> Message {
1310        Message::Simple {
1311            performative: Performative::Custom(String::from("ack")),
1312            recipient: None,
1313            content: SExpr::Atom(Atom::Str(String::from("done"))),
1314            params: Vec::new(),
1315            thread: None,
1316            sender: None,
1317            caused_by: Some(crate::message::CausedBy::Single(String::from("missing"))),
1318        }
1319    }
1320
1321    #[test]
1322    fn agent_wrapped_message_does_not_bypass_causal() {
1323        let mut agent = Agent::new("@alice");
1324        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1325        // Wrap the violating ack in an envelope.
1326        let wrapped = Message::Wrapped {
1327            wrapper: crate::message::WrapperType::Envelope,
1328            params: vec![
1329                SExpr::Atom(Atom::Keyword(String::from("from"))),
1330                SExpr::Atom(Atom::Symbol(String::from("@alice"))),
1331            ],
1332            content: alloc::boxed::Box::new(ack_simple_with_missing_predecessor()),
1333        };
1334        match agent.evaluate_and_apply(&wrapped) {
1335            AgentOutcome::Pending(_) => {}
1336            other => panic!("expected wrapper to surface inner Pending, got {other:?}"),
1337        }
1338        assert!(
1339            agent.beliefs().is_empty(),
1340            "wrapped reject should not apply effects"
1341        );
1342    }
1343
1344    #[test]
1345    fn agent_lang_scoped_message_does_not_bypass_causal() {
1346        let mut agent = Agent::new("@alice");
1347        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1348        let scoped = Message::Dialect {
1349            dialect_name: String::from("ack-dialect"),
1350            inner: alloc::boxed::Box::new(ack_simple_with_missing_predecessor()),
1351        };
1352        match agent.evaluate_and_apply(&scoped) {
1353            AgentOutcome::Pending(_) => {}
1354            other => panic!("expected lang-scoped wrapper to surface inner Pending, got {other:?}"),
1355        }
1356    }
1357
1358    // -- PR feedback P1: child protocols on inherited (core) performatives. --
1359
1360    fn ok_protocol_dialect() -> Dialect {
1361        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1362        let mut steps = alloc::collections::BTreeMap::new();
1363        steps.insert(
1364            "begin".into(),
1365            StepDecl {
1366                performative: "begin".into(),
1367                predecessors: alloc::vec![],
1368                successors: alloc::vec![NodeRef::Single("ok".into())],
1369            },
1370        );
1371        steps.insert(
1372            "ok".into(),
1373            StepDecl {
1374                performative: "ok".into(),
1375                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1376                successors: alloc::vec![],
1377            },
1378        );
1379        Dialect {
1380            types: Default::default(),
1381            roles: Vec::new(),
1382            state: None,
1383            state_bounds: None,
1384            causal_locality: Default::default(),
1385            name: String::from("ok-protocol"),
1386            extends: alloc::vec![String::from("cbcl")],
1387            author: None,
1388            performatives: alloc::vec![],
1389            resources: ResourceBounds {
1390                max_depth: 8,
1391                max_expansion_size: 512,
1392            },
1393            examples: alloc::vec![],
1394            signature: None,
1395            hash: None,
1396            protocol: None,
1397            causal_protocol: Some(CausalProtocol { steps }),
1398            shapes: alloc::vec![],
1399        }
1400    }
1401
1402    #[test]
1403    fn agent_enforces_child_protocol_on_core_performative() {
1404        let mut agent = Agent::new("@alice");
1405        agent.install_dialect(ok_protocol_dialect()).unwrap();
1406        // (ok) with no :caused-by — child protocol requires "begin".
1407        let msg = Message::Simple {
1408            performative: Performative::Core(CorePerformative::Ok),
1409            recipient: None,
1410            content: SExpr::List(Vec::new()),
1411            params: Vec::new(),
1412            thread: None,
1413            sender: None,
1414            caused_by: None,
1415        };
1416        match agent.evaluate_and_apply(&msg) {
1417            AgentOutcome::CausalReject(crate::protocol::CausalViolation::MissingCausedBy) => {}
1418            other => panic!(
1419                "expected child protocol on core `ok` to reject MissingCausedBy, got {other:?}"
1420            ),
1421        }
1422    }
1423
1424    // -- PR feedback P2: reevaluate_pending must not flush via unrelated protocol. --
1425
1426    #[test]
1427    fn agent_reevaluate_does_not_accept_via_unrelated_protocol() {
1428        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1429
1430        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(60));
1431        // Protocol A constrains "ack" (caller will buffer an "ack").
1432        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1433        // Protocol B constrains an unrelated performative "ping" — its mere
1434        // presence used to flush every pending entry as Accept because
1435        // verify_causal returned Valid for performatives outside its steps.
1436        let mut steps = alloc::collections::BTreeMap::new();
1437        steps.insert(
1438            "begin".into(),
1439            StepDecl {
1440                performative: "begin".into(),
1441                predecessors: alloc::vec![],
1442                successors: alloc::vec![NodeRef::Single("ping".into())],
1443            },
1444        );
1445        steps.insert(
1446            "ping".into(),
1447            StepDecl {
1448                performative: "ping".into(),
1449                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1450                successors: alloc::vec![],
1451            },
1452        );
1453        agent
1454            .install_dialect(Dialect {
1455                types: Default::default(),
1456                roles: Vec::new(),
1457                state: None,
1458                state_bounds: None,
1459                causal_locality: Default::default(),
1460                name: String::from("ping-dialect"),
1461                extends: alloc::vec![String::from("cbcl")],
1462                author: None,
1463                performatives: alloc::vec![PerformativeDef {
1464                    role: None,
1465                    name: String::from("ping"),
1466                    params: Vec::new(),
1467                    template: SExpr::List(alloc::vec![
1468                        SExpr::Atom(Atom::Symbol(String::from("effect"))),
1469                        SExpr::Atom(Atom::Symbol(String::from("ping-action"))),
1470                    ]),
1471                }],
1472                resources: ResourceBounds {
1473                    max_depth: 8,
1474                    max_expansion_size: 512,
1475                },
1476                examples: Vec::new(),
1477                signature: None,
1478                hash: None,
1479                protocol: None,
1480                causal_protocol: Some(CausalProtocol { steps }),
1481                shapes: Vec::new(),
1482            })
1483            .unwrap();
1484
1485        // Buffer an ack with a missing predecessor.
1486        let msg = ack_with_caused_by("missing");
1487        match agent.evaluate_and_apply(&msg) {
1488            AgentOutcome::Buffered => {}
1489            other => panic!("expected Buffered, got {other:?}"),
1490        }
1491        assert_eq!(agent.pending_len(), 1);
1492
1493        // Re-evaluate without adding the predecessor. Only the ack-dialect's
1494        // protocol matches the entry; its verdict is Unknown so the entry
1495        // stays buffered. The unrelated ping-dialect protocol must not flush
1496        // it as Accept.
1497        let resolved = agent.reevaluate_pending();
1498        assert!(
1499            resolved.is_empty(),
1500            "unrelated protocol should not flush pending entry, got {resolved:?}"
1501        );
1502        assert_eq!(agent.pending_len(), 1);
1503    }
1504
1505    // -- PR feedback (low): default-buffered entries don't insta-expire --
1506
1507    #[test]
1508    fn agent_default_buffered_entries_never_expire() {
1509        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(60));
1510        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1511
1512        // Buffer via the no-clock entry point; entry should be stamped with
1513        // u64::MAX so even the largest reasonable `now` does not expire it.
1514        match agent.evaluate_and_apply(&ack_with_caused_by("missing")) {
1515            AgentOutcome::Buffered => {}
1516            other => panic!("expected Buffered, got {other:?}"),
1517        }
1518        assert_eq!(agent.pending_len(), 1);
1519
1520        let dropped = agent.expire(u64::MAX / 2);
1521        assert!(
1522            dropped.is_empty(),
1523            "default-buffered entry must not expire, got {dropped:?}"
1524        );
1525        assert_eq!(agent.pending_len(), 1);
1526    }
1527
1528    #[test]
1529    fn agent_evaluate_and_apply_at_respects_ttl() {
1530        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(10));
1531        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1532
1533        // Buffer at t=100; TTL=10s so it expires at t=110.
1534        match agent.evaluate_and_apply_at(&ack_with_caused_by("missing"), 100) {
1535            AgentOutcome::Buffered => {}
1536            other => panic!("expected Buffered, got {other:?}"),
1537        }
1538        assert_eq!(agent.pending_len(), 1);
1539
1540        // At t=109, nothing has expired yet.
1541        let dropped = agent.expire(109);
1542        assert!(dropped.is_empty(), "TTL not yet elapsed, got {dropped:?}");
1543        assert_eq!(agent.pending_len(), 1);
1544
1545        // At t=110 the entry expires.
1546        let dropped = agent.expire(110);
1547        assert_eq!(dropped.len(), 1);
1548        assert_eq!(dropped[0].1, DropReason::CausalTimeout);
1549        assert_eq!(agent.pending_len(), 0);
1550    }
1551
1552    // -- MergePolicy: any-protocol-accepts (disjunction) mode --
1553    //
1554    // Two installed dialects both declare protocol steps for the inherited
1555    // core performative `ok` — neither *defines* `ok` (R3 forbids that) but
1556    // each constrains it differently. This is the canonical "two protocols
1557    // matching the same perf" shape we proved supported in earlier review
1558    // rounds; it's what makes a discriminating disjunction test possible.
1559
1560    /// Single-predecessor protocol on `ok`: accepts `(ok :caused-by begin)`.
1561    fn single_pred_ok_dialect(name: &str) -> Dialect {
1562        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1563        let mut steps = alloc::collections::BTreeMap::new();
1564        steps.insert(
1565            "begin".into(),
1566            StepDecl {
1567                performative: "begin".into(),
1568                predecessors: alloc::vec![],
1569                successors: alloc::vec![NodeRef::Single("ok".into())],
1570            },
1571        );
1572        steps.insert(
1573            "ok".into(),
1574            StepDecl {
1575                performative: "ok".into(),
1576                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1577                successors: alloc::vec![],
1578            },
1579        );
1580        Dialect {
1581            types: Default::default(),
1582            roles: Vec::new(),
1583            state: None,
1584            state_bounds: None,
1585            causal_locality: Default::default(),
1586            name: String::from(name),
1587            extends: alloc::vec![String::from("cbcl")],
1588            author: None,
1589            performatives: alloc::vec![],
1590            resources: ResourceBounds {
1591                max_depth: 8,
1592                max_expansion_size: 512,
1593            },
1594            examples: Vec::new(),
1595            signature: None,
1596            hash: None,
1597            protocol: None,
1598            causal_protocol: Some(CausalProtocol { steps }),
1599            shapes: Vec::new(),
1600        }
1601    }
1602
1603    /// Strict protocol on `ok`: rejects any `:caused-by` (no predecessors).
1604    fn strict_no_pred_ok_dialect(name: &str) -> Dialect {
1605        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1606        let mut steps = alloc::collections::BTreeMap::new();
1607        // begin step needed for reachability (R5).
1608        steps.insert(
1609            "begin".into(),
1610            StepDecl {
1611                performative: "begin".into(),
1612                predecessors: alloc::vec![],
1613                successors: alloc::vec![NodeRef::Single("ok".into())],
1614            },
1615        );
1616        steps.insert(
1617            "ok".into(),
1618            StepDecl {
1619                performative: "ok".into(),
1620                predecessors: alloc::vec![], // no predecessors permitted
1621                successors: alloc::vec![],
1622            },
1623        );
1624        Dialect {
1625            types: Default::default(),
1626            roles: Vec::new(),
1627            state: None,
1628            state_bounds: None,
1629            causal_locality: Default::default(),
1630            name: String::from(name),
1631            extends: alloc::vec![String::from("cbcl")],
1632            author: None,
1633            performatives: alloc::vec![],
1634            resources: ResourceBounds {
1635                max_depth: 8,
1636                max_expansion_size: 512,
1637            },
1638            examples: Vec::new(),
1639            signature: None,
1640            hash: None,
1641            protocol: None,
1642            causal_protocol: Some(CausalProtocol { steps }),
1643            shapes: Vec::new(),
1644        }
1645    }
1646
1647    /// Fan-in protocol on `ok`: requires `(all p1 p2)` — two custom perfs.
1648    fn fan_in_ok_dialect(name: &str) -> Dialect {
1649        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1650        let mut all_set = alloc::collections::BTreeSet::new();
1651        all_set.insert(String::from("p1"));
1652        all_set.insert(String::from("p2"));
1653
1654        let mut steps = alloc::collections::BTreeMap::new();
1655        steps.insert("begin".into(), StepDecl {
1656            performative: "begin".into(),
1657            predecessors: alloc::vec![],
1658            successors: alloc::vec![
1659                NodeRef::Single("p1".into()),
1660                NodeRef::Single("p2".into()),
1661            ],
1662        });
1663        steps.insert(
1664            "p1".into(),
1665            StepDecl {
1666                performative: "p1".into(),
1667                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1668                successors: alloc::vec![NodeRef::Single("ok".into())],
1669            },
1670        );
1671        steps.insert(
1672            "p2".into(),
1673            StepDecl {
1674                performative: "p2".into(),
1675                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1676                successors: alloc::vec![NodeRef::Single("ok".into())],
1677            },
1678        );
1679        steps.insert(
1680            "ok".into(),
1681            StepDecl {
1682                performative: "ok".into(),
1683                predecessors: alloc::vec![NodeRef::All(all_set)],
1684                successors: alloc::vec![],
1685            },
1686        );
1687        Dialect {
1688            types: Default::default(),
1689            roles: Vec::new(),
1690            state: None,
1691            state_bounds: None,
1692            causal_locality: Default::default(),
1693            name: String::from(name),
1694            extends: alloc::vec![String::from("cbcl")],
1695            author: None,
1696            performatives: vec![
1697                PerformativeDef {
1698                    role: None,
1699                    name: String::from("p1"),
1700                    params: Vec::new(),
1701                    template: SExpr::List(alloc::vec![
1702                        SExpr::Atom(Atom::Symbol(String::from("effect"))),
1703                        SExpr::Atom(Atom::Symbol(String::from("p1-action"))),
1704                    ]),
1705                },
1706                PerformativeDef {
1707                    role: None,
1708                    name: String::from("p2"),
1709                    params: Vec::new(),
1710                    template: SExpr::List(alloc::vec![
1711                        SExpr::Atom(Atom::Symbol(String::from("effect"))),
1712                        SExpr::Atom(Atom::Symbol(String::from("p2-action"))),
1713                    ]),
1714                },
1715            ],
1716            resources: ResourceBounds {
1717                max_depth: 8,
1718                max_expansion_size: 512,
1719            },
1720            examples: Vec::new(),
1721            signature: None,
1722            hash: None,
1723            protocol: None,
1724            causal_protocol: Some(CausalProtocol { steps }),
1725            shapes: Vec::new(),
1726        }
1727    }
1728
1729    fn core_ok_with_caused_by(caused_by: crate::message::CausedBy) -> Message {
1730        Message::Simple {
1731            performative: Performative::Core(CorePerformative::Ok),
1732            recipient: None,
1733            content: SExpr::List(Vec::new()),
1734            params: Vec::new(),
1735            thread: None,
1736            sender: None,
1737            caused_by: Some(caused_by),
1738        }
1739    }
1740
1741    #[test]
1742    fn agent_disjunction_accepts_when_one_protocol_accepts_other_rejects() {
1743        use crate::store::{ContentHash as Hash, MessageStore as _};
1744
1745        // Two protocols both fire on `ok`:
1746        //   single_pred: requires `begin` predecessor → Valid given begin in store
1747        //   strict:      requires no predecessor      → Violation (extraneous)
1748        let mut agent = Agent::new("@alice").with_merge_policy(MergePolicy::Disjunction);
1749        agent
1750            .install_dialect(single_pred_ok_dialect("accept-after-begin"))
1751            .expect("single_pred dialect must install");
1752        agent
1753            .install_dialect(strict_no_pred_ok_dialect("strict-no-pred"))
1754            .expect("strict dialect must install");
1755
1756        // Insert a `begin` (any non-ok core performative is fine — its
1757        // performative name just needs to match what single_pred allows as
1758        // the predecessor type for `ok`).
1759        let begin_msg = Message::Simple {
1760            performative: Performative::Custom(String::from("begin")),
1761            recipient: None,
1762            content: SExpr::List(Vec::new()),
1763            params: Vec::new(),
1764            thread: None,
1765            sender: None,
1766            caused_by: Some(crate::message::CausedBy::Begin),
1767        };
1768        agent.message_store_mut().append(
1769            Hash(String::from("begin-hash")),
1770            ThreadId(String::from("default")),
1771            begin_msg,
1772        );
1773
1774        let msg =
1775            core_ok_with_caused_by(crate::message::CausedBy::Single(String::from("begin-hash")));
1776        match agent.evaluate_and_apply(&msg) {
1777            AgentOutcome::Applied(_) => {}
1778            other => panic!(
1779                "expected disjunction Accept (one protocol accepts, one rejects), got {other:?}"
1780            ),
1781        }
1782    }
1783
1784    #[test]
1785    fn agent_conjunction_rejects_same_setup_disjunction_accepts() {
1786        use crate::store::{ContentHash as Hash, MessageStore as _};
1787
1788        // Same fixture as above but with conjunction: the strict protocol's
1789        // Violation is enough to reject.
1790        let mut agent = Agent::new("@alice"); // default Conjunction
1791        agent
1792            .install_dialect(single_pred_ok_dialect("accept-after-begin"))
1793            .unwrap();
1794        agent
1795            .install_dialect(strict_no_pred_ok_dialect("strict-no-pred"))
1796            .unwrap();
1797
1798        let begin_msg = Message::Simple {
1799            performative: Performative::Custom(String::from("begin")),
1800            recipient: None,
1801            content: SExpr::List(Vec::new()),
1802            params: Vec::new(),
1803            thread: None,
1804            sender: None,
1805            caused_by: Some(crate::message::CausedBy::Begin),
1806        };
1807        agent.message_store_mut().append(
1808            Hash(String::from("begin-hash")),
1809            ThreadId(String::from("default")),
1810            begin_msg,
1811        );
1812
1813        let msg =
1814            core_ok_with_caused_by(crate::message::CausedBy::Single(String::from("begin-hash")));
1815        match agent.evaluate_and_apply(&msg) {
1816            AgentOutcome::CausalReject(_) => {}
1817            other => panic!("expected conjunction CausalReject, got {other:?}"),
1818        }
1819    }
1820
1821    #[test]
1822    fn agent_disjunction_reevaluate_keeps_buffered_when_one_protocol_unknown() {
1823        // Guards against premature rejection of (Unknown, Violation).
1824        // Strong Kleene join keeps the unresolved alternative pending.
1825        //
1826        // fan_in protocol: ok requires `(all p1 p2)` — Multiple-friendly.
1827        // single_pred  : ok requires single `begin` — *not* Multiple-friendly,
1828        //                so a Multiple `:caused-by` triggers
1829        //                Violation(FanInWithoutAllDecl) without any store
1830        //                lookup, regardless of whether the hashes are known.
1831        //
1832        // Send `(ok :caused-by (h1 h2))` with store empty:
1833        //   fan_in     → Unknown (h1, h2 missing from store)
1834        //   single_pred → Violation (FanInWithoutAllDecl)
1835        //
1836        // Live disjunction path: merge_policy_outcomes_disjunctive
1837        //   (Buffered, Reject) = Buffered ✓
1838        //
1839        // Re-evaluation uses the same strong Kleene disjunction:
1840        //   Unknown.join(Violation) = Unknown → kept buffered.
1841        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(60))
1842            .with_merge_policy(MergePolicy::Disjunction);
1843        agent.install_dialect(fan_in_ok_dialect("fan-in")).unwrap();
1844        agent
1845            .install_dialect(single_pred_ok_dialect("single-pred"))
1846            .unwrap();
1847
1848        let msg = core_ok_with_caused_by(crate::message::CausedBy::Multiple(alloc::vec![
1849            String::from("h1"),
1850            String::from("h2"),
1851        ]));
1852        match agent.evaluate_and_apply(&msg) {
1853            AgentOutcome::Buffered => {}
1854            other => panic!("expected Buffered live, got {other:?}"),
1855        }
1856        assert_eq!(agent.pending_len(), 1);
1857
1858        let resolved = agent.reevaluate_pending();
1859        assert!(
1860            resolved.is_empty(),
1861            "disjunction must not flush still-pending entry across an \
1862             unrelated Violation, got {resolved:?}"
1863        );
1864        assert_eq!(agent.pending_len(), 1);
1865    }
1866
1867    #[test]
1868    fn merge_policy_default_is_conjunction() {
1869        let agent = Agent::new("@alice");
1870        assert_eq!(agent.merge_policy(), MergePolicy::Conjunction);
1871    }
1872
1873    #[test]
1874    fn with_merge_policy_sets_disjunction() {
1875        let agent = Agent::new("@alice").with_merge_policy(MergePolicy::Disjunction);
1876        assert_eq!(agent.merge_policy(), MergePolicy::Disjunction);
1877    }
1878
1879    // Strong Kleene disjunction used by pending protocol re-evaluation.
1880
1881    fn vr_violation() -> VerificationResult {
1882        VerificationResult::Violation(crate::protocol::CausalViolation::MissingCausedBy)
1883    }
1884
1885    #[test]
1886    fn strong_kleene_join_valid_absorbs() {
1887        assert!(matches!(
1888            VerificationResult::Valid.join(VerificationResult::Unknown),
1889            VerificationResult::Valid
1890        ));
1891        assert!(matches!(
1892            VerificationResult::Unknown.join(VerificationResult::Valid),
1893            VerificationResult::Valid
1894        ));
1895        assert!(matches!(
1896            VerificationResult::Valid.join(vr_violation()),
1897            VerificationResult::Valid
1898        ));
1899        assert!(matches!(
1900            vr_violation().join(VerificationResult::Valid),
1901            VerificationResult::Valid
1902        ));
1903    }
1904
1905    #[test]
1906    fn strong_kleene_join_unknown_outranks_violation() {
1907        assert!(matches!(
1908            VerificationResult::Unknown.join(vr_violation()),
1909            VerificationResult::Unknown
1910        ));
1911        assert!(matches!(
1912            vr_violation().join(VerificationResult::Unknown),
1913            VerificationResult::Unknown
1914        ));
1915    }
1916
1917    #[test]
1918    fn strong_kleene_join_violation_only_when_no_hope() {
1919        assert!(matches!(
1920            vr_violation().join(vr_violation()),
1921            VerificationResult::Violation(_)
1922        ));
1923    }
1924
1925    // -- Clock injection --
1926
1927    #[derive(Debug)]
1928    struct FixedClock(u64);
1929    impl crate::clock::Clock for FixedClock {
1930        fn now(&self) -> u64 {
1931            self.0
1932        }
1933    }
1934
1935    /// A clock that increments on each `now()` call, useful for tests that
1936    /// want to observe Arc-shared mutability across cloned agents.
1937    #[derive(Debug)]
1938    struct TickingClock(core::sync::atomic::AtomicU64);
1939    impl crate::clock::Clock for TickingClock {
1940        fn now(&self) -> u64 {
1941            self.0.fetch_add(1, core::sync::atomic::Ordering::Relaxed)
1942        }
1943    }
1944
1945    #[test]
1946    fn agent_uses_injected_clock_for_buffer_timestamps() {
1947        let mut agent = Agent::with_policy("@alice", UnknownPredecessorPolicy::buffer(10))
1948            .with_clock(FixedClock(100));
1949        agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1950
1951        // The agent now consults FixedClock(100) automatically — no _at
1952        // call needed. Buffer at clock=100; TTL=10 → expires at 110.
1953        match agent.evaluate_and_apply(&ack_with_caused_by("missing")) {
1954            AgentOutcome::Buffered => {}
1955            other => panic!("expected Buffered, got {other:?}"),
1956        }
1957
1958        let dropped = agent.expire(109);
1959        assert!(dropped.is_empty(), "TTL not yet elapsed: {dropped:?}");
1960
1961        let dropped = agent.expire(110);
1962        assert_eq!(dropped.len(), 1);
1963        assert_eq!(dropped[0].1, DropReason::CausalTimeout);
1964    }
1965
1966    #[test]
1967    fn agent_clone_shares_clock_via_arc() {
1968        // Cloning an agent shares the Arc<dyn Clock> rather than duplicating
1969        // it. A clock with interior mutability (here an AtomicU64) advances
1970        // for both clones — proving they share state, not that the clone
1971        // captured a snapshot.
1972        let agent_a =
1973            Agent::new("@alice").with_clock(TickingClock(core::sync::atomic::AtomicU64::new(0)));
1974        let agent_b = agent_a.clone();
1975        // Each call to either agent's clock increments the shared counter.
1976        let t0 = agent_a.clock.now();
1977        let t1 = agent_b.clock.now();
1978        let t2 = agent_a.clock.now();
1979        assert_eq!(t0, 0);
1980        assert_eq!(t1, 1);
1981        assert_eq!(t2, 2);
1982    }
1983}