1#![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#[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 message_store: ThreadedMessageStore,
49 policy: UnknownPredecessorPolicy,
51 pending_queue: PendingQueue,
53 merge_policy: MergePolicy,
55 clock: Arc<dyn Clock>,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum MergePolicy {
65 #[default]
69 Conjunction,
70 Disjunction,
84}
85
86fn 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
105fn 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
120fn 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
138fn 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#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum AgentOutcome {
159 Applied(EvalResult),
162 CausalReject(CausalViolation),
164 Pending(PendingReason),
167 Buffered,
170 EvalError(EvalError),
172}
173
174impl Agent {
175 pub fn new(id: impl Into<String>) -> Self {
180 Self::with_policy(id, UnknownPredecessorPolicy::default())
181 }
182
183 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 pub fn with_merge_policy(mut self, merge_policy: MergePolicy) -> Self {
208 self.merge_policy = merge_policy;
209 self
210 }
211
212 pub fn merge_policy(&self) -> MergePolicy {
214 self.merge_policy
215 }
216
217 pub fn with_clock<C: Clock + 'static>(mut self, clock: C) -> Self {
224 self.clock = Arc::new(clock);
225 self
226 }
227
228 pub fn message_store(&self) -> &ThreadedMessageStore {
230 &self.message_store
231 }
232
233 pub fn message_store_mut(&mut self) -> &mut ThreadedMessageStore {
236 &mut self.message_store
237 }
238
239 pub fn policy(&self) -> &UnknownPredecessorPolicy {
241 &self.policy
242 }
243
244 pub fn pending_len(&self) -> usize {
246 self.pending_queue.len()
247 }
248
249 pub fn id(&self) -> &str {
251 &self.id
252 }
253
254 pub fn is_well_formed(&self) -> bool {
261 self.dialect_registry.is_well_formed()
262 }
263
264 pub fn dialect_registry(&self) -> &DialectRegistry {
268 &self.dialect_registry
269 }
270
271 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 pub fn install_dialect(&mut self, d: Dialect) -> Result<(), DialectInstallError> {
286 self.dialect_registry.install(d)
287 }
288
289 pub fn beliefs(&self) -> &BTreeSet<SExpr> {
293 &self.beliefs
294 }
295
296 pub fn add_belief(&mut self, belief: SExpr) -> bool {
299 self.beliefs.insert(belief)
300 }
301
302 pub fn remove_belief(&mut self, belief: &SExpr) -> bool {
305 self.beliefs.remove(belief)
306 }
307
308 pub fn has_belief(&self, belief: &SExpr) -> bool {
310 self.beliefs.contains(belief)
311 }
312
313 pub fn message_queue(&self) -> &VecDeque<Message> {
317 &self.message_queue
318 }
319
320 pub fn enqueue_message(&mut self, msg: Message) {
322 self.message_queue.push_back(msg);
323 }
324
325 pub fn dequeue_message(&mut self) -> Option<Message> {
327 self.message_queue.pop_front()
328 }
329
330 pub fn message_queue_len(&self) -> usize {
332 self.message_queue.len()
333 }
334
335 pub fn conversation_threads(&self) -> &BTreeMap<String, Vec<Message>> {
339 &self.conversation_threads
340 }
341
342 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 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 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 pub fn evaluate_and_apply_at(&mut self, msg: &Message, now: u64) -> AgentOutcome {
388 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 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 }
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 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 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 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 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 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 pub fn expire(&mut self, now: u64) -> Vec<(PendingEntry, DropReason)> {
548 self.pending_queue.expire(now)
549 }
550
551 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 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 MergePolicy::Conjunction => prev.meet(r),
598 MergePolicy::Disjunction => prev.join(r),
600 },
601 });
602 }
603 combined
604 })
605 }
606
607 pub fn step(&mut self) -> Option<AgentOutcome> {
613 let msg = self.dequeue_message()?;
614 Some(self.evaluate_and_apply(&msg))
615 }
616
617 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 #[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 #[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 #[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"), 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 assert!(agent.is_well_formed());
778 assert_eq!(agent.dialect_registry().len(), 1);
779 }
780
781 #[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)); 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 #[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 #[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 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 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 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 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 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 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 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 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 let mut agent = Agent::new("@alice");
1199 agent.install_dialect(any_xy_dialect()).unwrap();
1200 append_pred(&mut agent, "h-wrong", "w"); 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 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 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 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 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 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 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"); 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 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 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 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 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 #[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 agent.install_dialect(ack_dialect_with_protocol()).unwrap();
1433 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 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 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 #[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 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 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 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 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 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 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 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![], 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 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 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 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 let mut agent = Agent::new("@alice"); 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 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 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 #[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 #[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 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 let agent_a =
1973 Agent::new("@alice").with_clock(TickingClock(core::sync::atomic::AtomicU64::new(0)));
1974 let agent_b = agent_a.clone();
1975 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}