Skip to main content

MemorySubstrate

Struct MemorySubstrate 

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

The core persistence handle for Punch.

Wraps a SQLite Connection behind a tokio::sync::Mutex so it can be shared across async tasks without blocking the executor. Optionally includes an EmbeddingStore for semantic search over stored memories.

Implementations§

Source§

impl MemorySubstrate

Source

pub async fn create_bout(&self, fighter_id: &FighterId) -> PunchResult<BoutId>

Create a new bout for the given fighter and return its ID.

Source

pub async fn save_message( &self, bout_id: &BoutId, message: &Message, ) -> PunchResult<()>

Append a message to an existing bout.

Source

pub async fn load_messages(&self, bout_id: &BoutId) -> PunchResult<Vec<Message>>

Load all messages for a bout in chronological order.

Source

pub async fn list_bouts( &self, fighter_id: &FighterId, ) -> PunchResult<Vec<BoutSummary>>

List all bouts for a fighter, most recent first.

Source

pub async fn delete_bout(&self, bout_id: &BoutId) -> PunchResult<()>

Delete a bout and all its messages (cascading).

Source§

impl MemorySubstrate

Source

pub async fn save_creed(&self, creed: &Creed) -> PunchResult<()>

Save or update a creed. Uses fighter_name as the natural key.

Source

pub async fn load_creed_by_name( &self, fighter_name: &str, ) -> PunchResult<Option<Creed>>

Load a creed by fighter name. Returns None if no creed exists.

Source

pub async fn load_creed_by_fighter( &self, fighter_id: &FighterId, ) -> PunchResult<Option<Creed>>

Load a creed by fighter ID. Returns None if no creed exists.

Source

pub async fn list_creeds(&self) -> PunchResult<Vec<Creed>>

List all creeds.

Source

pub async fn delete_creed(&self, fighter_name: &str) -> PunchResult<()>

Delete a creed by fighter name.

Source

pub async fn bind_creed_to_fighter( &self, fighter_name: &str, fighter_id: &FighterId, ) -> PunchResult<()>

Bind a creed to a specific fighter instance (after spawn/respawn).

Source§

impl MemorySubstrate

Source

pub async fn save_fighter( &self, id: &FighterId, manifest: &FighterManifest, status: FighterStatus, ) -> PunchResult<()>

Persist a fighter’s manifest and status.

Source

pub async fn load_fighter( &self, id: &FighterId, ) -> PunchResult<Option<FighterManifest>>

Load a fighter manifest by ID.

Source

pub async fn list_fighters( &self, ) -> PunchResult<Vec<(FighterId, String, FighterStatus)>>

List all stored fighters as (FighterId, name, FighterStatus) tuples.

Source

pub async fn update_fighter_status( &self, id: &FighterId, status: FighterStatus, ) -> PunchResult<()>

Update a fighter’s operational status.

Source

pub async fn delete_fighter(&self, id: &FighterId) -> PunchResult<()>

Delete a fighter and all related data (cascading).

Source§

impl MemorySubstrate

Source

pub async fn add_entity( &self, fighter_id: &FighterId, name: &str, entity_type: &str, properties: &Value, ) -> PunchResult<()>

Add (or upsert) an entity to a fighter’s knowledge graph.

Source

pub async fn add_relation( &self, fighter_id: &FighterId, from: &str, relation: &str, to: &str, properties: &Value, ) -> PunchResult<()>

Add (or upsert) a relation between two entities.

Source

pub async fn query_entities( &self, fighter_id: &FighterId, query: &str, ) -> PunchResult<Vec<KnowledgeEntity>>

Query entities matching a name or type substring.

Source

pub async fn query_relations( &self, fighter_id: &FighterId, entity: &str, ) -> PunchResult<Vec<KnowledgeRelation>>

Query all relations involving a given entity (as source or target).

Source§

impl MemorySubstrate

Source

pub async fn cleanup_old_messages( &self, cutoff: DateTime<Utc>, ) -> PunchResult<usize>

Delete bout messages older than the given cutoff date.

Returns the number of messages deleted.

Source

pub async fn compact_memories( &self, max_per_fighter: usize, ) -> PunchResult<usize>

Compact memory entries by removing low-confidence entries when a fighter exceeds the maximum number of memories.

Returns the number of entries removed.

Source

pub async fn vacuum(&self) -> PunchResult<()>

Run SQLite VACUUM to reclaim disk space.

Source

pub async fn count_bouts_in_period( &self, start: DateTime<Utc>, end: DateTime<Utc>, ) -> PunchResult<usize>

Count bouts created within a time period.

Source

pub async fn count_messages_in_period( &self, start: DateTime<Utc>, end: DateTime<Utc>, ) -> PunchResult<usize>

Count messages created within a time period.

Source§

impl MemorySubstrate

Source

pub async fn store_memory( &self, fighter_id: &FighterId, key: &str, value: &str, confidence: f64, ) -> PunchResult<()>

Store (or overwrite) a key-value memory for a fighter.

Source

pub async fn recall_memories( &self, fighter_id: &FighterId, query: &str, limit: u32, ) -> PunchResult<Vec<MemoryEntry>>

Recall memories matching a query substring, ordered by confidence descending.

Source

pub async fn decay_memories( &self, fighter_id: &FighterId, rate: f64, ) -> PunchResult<()>

Decay all memory confidences for a fighter by a multiplicative rate.

Each memory’s confidence becomes confidence * (1.0 - rate). Memories that decay below a threshold (0.01) are automatically deleted.

Source

pub async fn delete_memory( &self, fighter_id: &FighterId, key: &str, ) -> PunchResult<()>

Delete a specific memory by key.

Source§

impl MemorySubstrate

Source

pub fn new(path: &Path) -> PunchResult<Self>

Open (or create) a SQLite database at path and run pending migrations.

Source

pub async fn conn(&self) -> MutexGuard<'_, Connection>

Get a lock on the underlying database connection.

This is intended for advanced queries that don’t have a dedicated method. Prefer using the higher-level methods on MemorySubstrate when possible.

Source

pub fn in_memory() -> PunchResult<Self>

Create an in-memory substrate (useful for testing).

Source

pub fn with_embedding_store( self, conn: Arc<StdMutex<Connection>>, embedder: Box<dyn Embedder>, ) -> PunchResult<Self>

Attach an embedding store with the given embedder for semantic recall.

The embedding store shares a separate SQLite connection (via std::sync::Mutex) since it operates synchronously.

Source

pub fn with_builtin_embeddings(self) -> PunchResult<Self>

Attach a default built-in (TF-IDF) embedding store using an in-memory SQLite connection. Useful for testing and offline operation.

Source

pub fn has_embedding_store(&self) -> bool

Returns whether an embedding store is attached.

Source

pub fn embed_and_store( &self, text: &str, metadata: HashMap<String, String>, ) -> PunchResult<Option<String>>

Store a text embedding (if the embedding store is attached).

Perform semantic search over stored embeddings. Falls back to None if no embedding store is attached.

Source§

impl MemorySubstrate

Source

pub async fn record_usage( &self, fighter_id: &FighterId, model: &str, input_tokens: u64, output_tokens: u64, cost_usd: f64, ) -> PunchResult<()>

Record a usage event for a fighter.

Source

pub async fn get_usage_summary( &self, fighter_id: &FighterId, since: DateTime<Utc>, ) -> PunchResult<UsageSummary>

Get an aggregated usage summary for a fighter since the given timestamp.

Source

pub async fn get_total_usage_summary( &self, since: DateTime<Utc>, ) -> PunchResult<UsageSummary>

Get an aggregated usage summary across ALL fighters since the given timestamp.

Auto Trait Implementations§

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more