Skip to main content

Agent

Struct Agent 

Source
pub struct Agent { /* private fields */ }
Expand description

A CBCL agent (REQ-030).

An agent is a participant in the CBCL protocol with:

  • a unique identifier
  • a set of beliefs (S-expressions)
  • a dialect registry (always containing the base dialect at index 0)
  • a message queue for incoming messages
  • conversation threads indexed by thread id

§Well-formedness Invariant

An agent is well-formed iff self.dialect_registry.is_well_formed(), i.e. the base dialect is always installed at index 0. Agent::new() guarantees this invariant, and no method on Agent can violate it.

Implementations§

Source§

impl Agent

Source

pub fn new(id: impl Into<String>) -> Self

Create a new agent with the given id, bootstrapped with the base dialect (REQ-031).

The returned agent is always well-formed: the dialect registry contains exactly the base dialect.

Source

pub fn with_policy( id: impl Into<String>, policy: UnknownPredecessorPolicy, ) -> Self

Create a new agent with the given id and unknown-predecessor policy.

Source

pub fn with_merge_policy(self, merge_policy: MergePolicy) -> Self

Set how outcomes from multiple matching protocols are combined. Defaults to MergePolicy::Conjunction (fail-closed).

Source

pub fn merge_policy(&self) -> MergePolicy

Returns the configured merge policy.

Source

pub fn with_clock<C: Clock + 'static>(self, clock: C) -> Self

Inject a Clock for buffered-entry timestamps and TTL expiry.

Without this, the agent uses NoClock which stamps every buffered entry with u64::MAX, so TTL never fires. Pass crate::clock::SystemClock (with the std feature) to use real time, or any custom Clock implementation — useful for deterministic tests.

Source

pub fn message_store(&self) -> &ThreadedMessageStore

Returns a reference to the agent’s message store.

Source

pub fn message_store_mut(&mut self) -> &mut ThreadedMessageStore

Mutable access to the agent’s message store. Callers manage content hashing — the agent itself does not synthesize hashes.

Source

pub fn policy(&self) -> &UnknownPredecessorPolicy

Returns the configured unknown-predecessor policy.

Source

pub fn pending_len(&self) -> usize

Number of buffered (pending) messages awaiting predecessor arrival.

Source

pub fn id(&self) -> &str

Returns the agent’s identifier.

Source

pub fn is_well_formed(&self) -> bool

Check whether this agent is well-formed (REQ-032).

An agent is well-formed iff the base dialect is installed at index 0 of the dialect registry. Mirrors Agent.isWellFormed in Agent.lean.

Source

pub fn dialect_registry(&self) -> &DialectRegistry

Returns a reference to the dialect registry.

Source

pub fn dialects_defining<'a>( &'a self, name: &'a str, ) -> impl Iterator<Item = &'a Dialect>

Every installed dialect defining name, in installation order (REQ-033).

Introspection only. Dispatch never uses it: a custom performative is resolved against the dialect named by its (lang …) wrapper, so more than one result here is normal rather than a conflict.

Source

pub fn install_dialect(&mut self, d: Dialect) -> Result<(), DialectInstallError>

Install a dialect after verifying R1, R2, and R3 (REQ-034).

Delegates to DialectRegistry::install. The well-formedness invariant is preserved because install only appends.

Source

pub fn beliefs(&self) -> &BTreeSet<SExpr>

Returns a reference to the agent’s belief set.

Source

pub fn add_belief(&mut self, belief: SExpr) -> bool

Add a belief to the agent’s belief set. Returns true if the belief was newly inserted.

Source

pub fn remove_belief(&mut self, belief: &SExpr) -> bool

Remove a belief from the agent’s belief set. Returns true if the belief was present.

Source

pub fn has_belief(&self, belief: &SExpr) -> bool

Check whether the agent holds a given belief.

Source

pub fn message_queue(&self) -> &VecDeque<Message>

Returns a reference to the message queue.

Source

pub fn enqueue_message(&mut self, msg: Message)

Enqueue a message at the back of the message queue.

Source

pub fn dequeue_message(&mut self) -> Option<Message>

Dequeue a message from the front of the message queue.

Source

pub fn message_queue_len(&self) -> usize

Returns the number of messages in the queue.

Source

pub fn conversation_threads(&self) -> &BTreeMap<String, Vec<Message>>

Returns a reference to all conversation threads.

Source

pub fn thread(&self, thread_id: &str) -> Option<&[Message]>

Get the messages in a specific conversation thread.

Source

pub fn append_to_thread(&mut self, thread_id: impl Into<String>, msg: Message)

Append a message to a conversation thread, creating the thread if needed.

Source

pub fn evaluate_and_apply(&mut self, msg: &Message) -> AgentOutcome

Evaluate a message and apply its effects to this agent.

Pipeline (REQ-231 fail-closed):

  1. Causal verification against the agent’s dialect registry, message store, and configured UnknownPredecessorPolicy.
  2. On Accept: evaluate the message and apply its effects.
  3. On a resolved Violation: return AgentOutcome::CausalReject without applying. A provisional Violation — some named :caused-by hash still absent from the store — is downgraded to Unknown first (SPEC-003 REQ-315), so it follows 4/5 instead.
  4. On Unknown + Reject policy: return AgentOutcome::Pending.
  5. On Unknown + Buffer policy: enqueue in the pending queue and return AgentOutcome::Buffered; the message is not applied.

Buffered entries are timestamped via the injected Clock. With the default NoClock this is u64::MAX, so Self::expire will never drain them. Inject a real clock via Self::with_clock (or call Self::evaluate_and_apply_at for an explicit one-off override) to enable TTL-based eviction.

Source

pub fn evaluate_and_apply_at(&mut self, msg: &Message, now: u64) -> AgentOutcome

Like Self::evaluate_and_apply but stamps any newly-buffered entry with the supplied now (seconds since epoch), bypassing the injected clock. Useful for tests or when the caller wants per-message control over the timestamp.

Source

pub fn expire(&mut self, now: u64) -> Vec<(PendingEntry, DropReason)>

Drop buffered entries whose TTL has elapsed at now (seconds since epoch). Returns the dropped entries with DropReason::CausalTimeout.

Entries stamped with u64::MAX (the default when the agent is constructed without a clock and Self::evaluate_and_apply is used) never expire. To get TTL behaviour, either inject a real clock via Self::with_clock or pass an explicit timestamp via Self::evaluate_and_apply_at / Self::step_at.

Eviction is pull-based. The agent does not call expire on its own — the embedder is responsible for invoking it on a schedule that matches the configured TTL (e.g. once per second, once per minute). Without that, expired entries linger in the queue until the next caller-driven invocation, holding memory but not causing correctness issues. A future revision could opt-in to expire-on-each evaluate_and_apply if it becomes a footgun in practice.

Source

pub fn reevaluate_pending(&mut self) -> Vec<(PendingEntry, PolicyOutcome)>

Re-evaluate buffered messages against the (possibly grown) message store.

Returns the entries that now resolve to either Accept or Reject. Entries whose performative isn’t constrained by any installed protocol stay buffered (rather than being spuriously accepted by an unrelated protocol — verify_causal returns Valid for performatives outside a protocol’s step set, so iterating naively over every installed protocol would flush entries that are still waiting on their real predecessor).

When multiple protocols constrain the same performative, results compose by conjunction (any rejection rejects, any Unknown keeps pending) — the same semantics as the live verification path.

The caller is responsible for re-applying accepted messages; the agent does not auto-apply them, since Agent::evaluate_and_apply mutates state and the caller may want explicit control over re-entry.

Source

pub fn step(&mut self) -> Option<AgentOutcome>

Dequeue the next message, evaluate it, and apply effects.

Returns None if the queue is empty. Buffered entries inherit the u64::MAX timestamp from Self::evaluate_and_apply; use Self::step_at when TTL semantics are required.

Source

pub fn step_at(&mut self, now: u64) -> Option<AgentOutcome>

Like Self::step but stamps any newly-buffered entry with now.

Trait Implementations§

Source§

impl Clone for Agent

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Agent

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Forget for Agent

§

impl Freeze for Agent

§

impl Move for Agent

§

impl Send for Agent
where RawVecInner: Send, NodeRef<Owned, SExpr, SetValZST, LeafOrInternal>: Send, BoxRaw<(SExpr, SetValZST)>: Send, NodeRef<Owned, String, SExpr, LeafOrInternal>: Send, BoxRaw<(String, SExpr)>: Send, NodeRef<Owned, String, SetValZST, LeafOrInternal>: Send, BoxRaw<(String, SetValZST)>: Send, NodeRef<Owned, String, StepDecl, LeafOrInternal>: Send, BoxRaw<(String, StepDecl)>: Send, Arc<Node>: Send, NodeRef<Owned, String, BTreeSet<String>, LeafOrInternal>: Send, BoxRaw<(String, BTreeSet<String>)>: Send, BoxRaw<Definition>: Send, BoxRaw<Lift>: Send, BoxRaw<CounterRule>: Send, BoxRaw<Value>: Send, BoxRaw<Message>: Send, NodeRef<Owned, String, Vec<Message>, LeafOrInternal>: Send, BoxRaw<(String, Vec<Message>)>: Send, RawTable<(ThreadId, Vec<(ContentHash, Message)>)>: Send, RawTable<(ContentHash, (ThreadId, usize))>: Send, RawTable<(ThreadId, HashSet<ContentHash>)>: Send, RawTable<(ContentHash, RedactedEnvelope)>: Send, RawTable<(ContentHash, OpenedEnvelope)>: Send, RawTable<(ThreadId, VecDeque<PendingEntry>)>: Send, Arc<dyn Clock>: Send,

§

impl Sync for Agent
where RawVecInner: Sync, NodeRef<Owned, SExpr, SetValZST, LeafOrInternal>: Sync, BoxRaw<(SExpr, SetValZST)>: Sync, NodeRef<Owned, String, SExpr, LeafOrInternal>: Sync, BoxRaw<(String, SExpr)>: Sync, NodeRef<Owned, String, SetValZST, LeafOrInternal>: Sync, BoxRaw<(String, SetValZST)>: Sync, NodeRef<Owned, String, StepDecl, LeafOrInternal>: Sync, BoxRaw<(String, StepDecl)>: Sync, Arc<Node>: Sync, NodeRef<Owned, String, BTreeSet<String>, LeafOrInternal>: Sync, BoxRaw<(String, BTreeSet<String>)>: Sync, BoxRaw<Definition>: Sync, BoxRaw<Lift>: Sync, BoxRaw<CounterRule>: Sync, BoxRaw<Value>: Sync, BoxRaw<Message>: Sync, NodeRef<Owned, String, Vec<Message>, LeafOrInternal>: Sync, BoxRaw<(String, Vec<Message>)>: Sync, RawTable<(ThreadId, Vec<(ContentHash, Message)>)>: Sync, RawTable<(ContentHash, (ThreadId, usize))>: Sync, RawTable<(ThreadId, HashSet<ContentHash>)>: Sync, RawTable<(ContentHash, RedactedEnvelope)>: Sync, RawTable<(ContentHash, OpenedEnvelope)>: Sync, RawTable<(ThreadId, VecDeque<PendingEntry>)>: Sync, Arc<dyn Clock>: Sync,

§

impl Unpin for Agent
where *const u8 is !null: Unpin, *const LeafNode<SExpr, SetValZST> is !null: Unpin, Box<(SExpr, SetValZST)>: Unpin, *const LeafNode<String, SExpr> is !null: Unpin, Box<(String, SExpr)>: Unpin, *const LeafNode<String, SetValZST> is !null: Unpin, Box<(String, SetValZST)>: Unpin, *const LeafNode<String, StepDecl> is !null: Unpin, Box<(String, StepDecl)>: Unpin, Arc<Node>: Unpin, *const LeafNode<String, BTreeSet<String>> is !null: Unpin, Box<(String, BTreeSet<String>)>: Unpin, Box<Definition>: Unpin, Box<Lift>: Unpin, Box<CounterRule>: Unpin, Box<Value>: Unpin, Box<Message>: Unpin, *const LeafNode<String, Vec<Message>> is !null: Unpin, Box<(String, Vec<Message>)>: Unpin, *const LeafNode<KeyId, SetValZST> is !null: Unpin, Box<(KeyId, SetValZST)>: Unpin, Arc<dyn Clock>: Unpin,

§

impl UnsafeUnpin for Agent

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.