Skip to main content

MemoryRepository

Struct MemoryRepository 

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

Repository for memory operations

Implementations§

Source§

impl MemoryRepository

Source

pub fn new(pool: SqlitePool) -> Self

Source

pub fn pool(&self) -> &SqlitePool

Source

pub async fn store(&self, params: StoreMemoryParams<'_>) -> Result<Memory>

Store a new memory

Source

pub async fn store_with_lineage( &self, params: StoreMemoryWithLineageParams<'_>, ) -> Result<Memory>

Store a memory and write evidence lineage rows atomically.

Source

pub async fn enqueue_job(&self, params: EnqueueJobParams<'_>) -> Result<i64>

Enqueue a new cognitive job.

Source

pub async fn claim_jobs( &self, namespace_id: i64, job_type: &str, lease_owner: &str, lease_ttl_secs: u64, limit: i64, ) -> Result<Vec<ClaimedMemoryJob>>

Claim up to limit pending (or stale running) jobs for a given type and namespace.

Stale running jobs are those whose lease has expired (lease_expires_at < now). Claimed jobs are transitioned to running with a lease owner and TTL.

Source

pub async fn complete_job(&self, job: &ClaimedMemoryJob) -> Result<()>

Mark a job as completed.

Source

pub async fn fail_job(&self, job: &ClaimedMemoryJob, error: &str) -> Result<()>

Mark a job as failed. If attempts < MAX_JOB_ATTEMPTS, requeue it as pending. Otherwise, mark it permanently failed.

Source

pub async fn get_most_reinforced_by_namespace( &self, namespace_id: i64, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Source

pub async fn get_contradictions_by_namespace( &self, namespace_id: i64, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Source

pub async fn list_by_session_key( &self, namespace_id: i64, session_key: &str, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Source

pub async fn store_digest(&self, params: StoreDigestParams<'_>) -> Result<i64>

Register a session digest for a memory.

Returns the digest row ID. Uses the unique index on (namespace_id, session_key, digest_kind, end_memory_id) to prevent duplicate registrations.

Source

pub async fn latest_digest_for_session( &self, namespace_id: i64, session_key: &str, digest_kind: &str, ) -> Result<Option<Memory>>

Get the latest digest memory for a session and digest kind. Returns the Memory row that the digest points to, or None.

Source

pub async fn latest_digest_for_namespace( &self, namespace_id: i64, digest_kind: &str, ) -> Result<Option<Memory>>

Get the latest digest memory for a namespace and digest kind, regardless of session key. Returns the Memory row that the digest points to, or None if no digest exists.

Source

pub async fn session_digest_rollover( &self, namespace_id: i64, session_key: &str, ) -> Result<SessionDigestRollover>

Return how much fresh non-raw, non-digest session content has accumulated since the latest covered digest window.

Source

pub async fn get_recent_by_perspective( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, ) -> Result<Vec<Memory>>

Get recent memories scoped to a perspective, optionally narrowed to a session.

By default, raw-activity noise is excluded. Set include_raw to true to include operational hook event payloads.

Source

pub async fn get_recent_by_perspective_opts( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Like Self::get_recent_by_perspective but allows opting into raw-activity noise inclusion.

Source

pub async fn get_by_cognitive_level( &self, namespace_id: i64, level: CognitiveLevel, limit: i64, ) -> Result<Vec<Memory>>

Get active memories by cognitive level ordered from newest to oldest.

Source

pub async fn get_by_cognitive_level_with_perspective( &self, namespace_id: i64, level: CognitiveLevel, perspective: &PerspectiveKey, limit: i64, ) -> Result<Vec<Memory>>

Get active memories by cognitive level and perspective, ordered from newest to oldest.

Unlike Self::get_by_cognitive_level, this method applies perspective filtering (observer, subject, session_key, and session_keys arrays) in the SQL query BEFORE the LIMIT is applied, ensuring the caller receives up to limit matching results.

Source

pub async fn get_most_reinforced_by_perspective( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, ) -> Result<Vec<Memory>>

Get the most reinforced perspective-aligned memories first.

By default, raw-activity noise and contradiction memories are excluded.

Source

pub async fn get_most_reinforced_by_perspective_opts( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Like Self::get_most_reinforced_by_perspective but allows opting into raw-activity noise inclusion.

Source

pub async fn get_contradictions_by_perspective( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, ) -> Result<Vec<Memory>>

Get contradiction memories for the requested perspective.

By default, raw-activity noise is excluded.

Source

pub async fn get_contradictions_by_perspective_opts( &self, namespace_id: i64, perspective: &PerspectiveKey, limit: i64, include_raw: bool, ) -> Result<Vec<Memory>>

Like Self::get_contradictions_by_perspective but allows opting into raw-activity noise inclusion.

Source

pub async fn search_working_set( &self, params: WorkingSetParams<'_>, ) -> Result<Vec<Memory>>

Assemble a bounded working set from multiple retrieval buckets.

This is the low-level repository primitive used by higher-level services (e.g. RepresentationService) to build a [WorkingRepresentation].

The method queries four buckets in sequence:

  1. Digests — latest short + long session digests
  2. Reinforced — highest reinforcement-scored memories
  3. Recent — newest perspective-aligned memories
  4. Contradictions — highest-confidence contradiction records

Results are deduplicated by memory ID (first-seen-wins in bucket order) and truncated to max_items.

Source

pub async fn load_lineage( &self, memory_id: i64, ) -> Result<Vec<MemoryLineageEntry>>

Load all evidence lineage entries for a given memory (as derived or source).

Source

pub async fn load_lineage_batch( &self, memory_ids: &[i64], ) -> Result<HashMap<i64, Vec<MemoryLineageEntry>>>

Load lineage rows for many source/derived memory IDs in one query.

Source

pub async fn get_by_id(&self, id: i64) -> Result<Option<Memory>>

Get a memory by ID

Source

pub async fn get_by_content( &self, namespace_id: i64, content: &str, ) -> Result<Memory>

Get a memory by namespace and content (fallback for id 0 edge case)

Source

pub async fn search_by_namespace( &self, namespace_id: i64, limit: usize, offset: usize, ) -> Result<Vec<Memory>>

Search memories by namespace

Source

pub async fn count_by_namespace(&self, namespace_id: i64) -> Result<i64>

Count memories in namespace

Source

pub async fn count_all_by_namespace(&self, namespace_id: i64) -> Result<i64>

Count all memories in namespace (including inactive/archived)

Source

pub async fn count_archived_by_namespace( &self, namespace_id: i64, ) -> Result<i64>

Count archived memories in namespace

Source

pub async fn delete(&self, id: i64) -> Result<bool>

Delete a memory

Source

pub async fn touch(&self, id: i64) -> Result<()>

Update access count

Source

pub async fn get_unconsolidated( &self, namespace_id: i64, limit: i32, ) -> Result<Vec<MemoryRow>>

Get unconsolidated memories

Source

pub async fn mark_consolidated(&self, id: i64) -> Result<()>

Mark a memory as consolidated

Source

pub async fn mark_consolidated_batch(&self, ids: &[i64]) -> Result<()>

Mark multiple memories as consolidated in a single query

Source

pub async fn search_by_text( &self, namespace_id: i64, query: &str, limit: i32, include_raw: bool, ) -> Result<Vec<MemoryRow>>

Search memories by text content (LIKE search)

Source

pub async fn search_by_text_memories( &self, namespace_id: i64, query: &str, limit: i32, include_raw: bool, ) -> Result<Vec<Memory>>

Search memories by text content and return domain memories.

Source

pub async fn get_semantic_candidates( &self, params: SemanticCandidateParams<'_>, ) -> Result<Vec<Memory>>

Fetch recent, embedding-bearing cognition memories for vector-first semantic recall.

Source

pub async fn list_filtered( &self, namespace_id: i64, filters: ListMemoryFilters<'_>, ) -> Result<Vec<Memory>>

List memories with optional filters

Source

pub async fn list_missing_cognitive_metadata( &self, namespace_id: i64, limit: i64, offset: i64, ) -> Result<Vec<Memory>>

List memories that still need cognition metadata backfilled.

Source

pub async fn count_missing_cognitive_metadata( &self, namespace_id: i64, ) -> Result<i64>

Count memories that still need cognition metadata backfilled.

Source

pub async fn update_memory_metadata( &self, memory_id: i64, metadata: &Value, ) -> Result<()>

Replace the metadata blob for a single memory.

Source

pub async fn list_session_keys_without_digests( &self, namespace_id: i64, limit: i64, ) -> Result<Vec<String>>

List distinct session keys that have cognitive metadata but no digest coverage yet.

Source

pub async fn count_distinct_session_keys_with_cognition( &self, namespace_id: i64, ) -> Result<i64>

Count distinct non-empty cognitive session keys present in active memories.

Source

pub async fn list_archived_raw_cleanup_candidates( &self, namespace_id: i64, older_than: DateTime<Utc>, limit: i64, ) -> Result<Vec<Memory>>

List lineage-backed archived raw-activity memories that are safe to prune.

Source

pub async fn count_archived_raw_cleanup_candidates( &self, namespace_id: i64, older_than: DateTime<Utc>, ) -> Result<i64>

Count lineage-backed archived raw-activity memories that are safe to prune.

Source

pub async fn delete_batch(&self, ids: &[i64]) -> Result<u64>

Delete a batch of memories by id.

Source

pub async fn delete_by_content_pattern( &self, namespace_id: i64, pattern: &str, ) -> Result<u64>

Delete memories matching a content pattern (for cleaning noise)

Source

pub async fn count_filtered( &self, namespace_id: i64, category: Option<&str>, since: Option<DateTime<Utc>>, until: Option<DateTime<Utc>>, include_raw: bool, ) -> Result<i64>

Count memories matching filters (for stats with time ranges)

Source

pub async fn store_distilled_summary( &self, params: StoreMemoryParams<'_>, source_ids: &[i64], ) -> Result<Memory>

Store a distilled summary and archive its source memories atomically.

Source

pub async fn list_jobs( &self, namespace_id: i64, job_type: Option<&str>, status: Option<&str>, limit: i64, offset: i64, ) -> Result<Vec<MemoryJobRow>>

List memory jobs with optional filters.

Source

pub async fn count_jobs( &self, namespace_id: i64, job_type: Option<&str>, status: Option<&str>, ) -> Result<i64>

Count memory jobs with optional filters.

Source

pub async fn count_jobs_by_status( &self, namespace_id: i64, job_type: Option<&str>, ) -> Result<Vec<(String, i64)>>

Count memory jobs grouped by status for a namespace.

Source

pub async fn purge_completed_jobs( &self, older_than: DateTime<Utc>, ) -> Result<u64>

Delete completed jobs that were last updated before the given timestamp.

Returns the number of rows removed.

Source

pub async fn purge_permanently_failed_jobs( &self, older_than: DateTime<Utc>, ) -> Result<u64>

Delete permanently failed jobs (attempts >= 5) that were last updated before the given timestamp.

Returns the number of rows removed.

Source

pub async fn list_digests( &self, namespace_id: i64, session_key: Option<&str>, limit: i64, offset: i64, ) -> Result<Vec<SessionDigestRow>>

List session digests with optional session_key filter.

Source

pub async fn count_digests( &self, namespace_id: i64, session_key: Option<&str>, ) -> Result<i64>

Count session digests for a namespace, optionally filtered by session_key.

Source

pub async fn count_evidence(&self, namespace_id: i64) -> Result<i64>

Count evidence edges for a namespace.

Source

pub async fn record_metric( &self, metric_name: &str, metric_value: f64, labels: &Value, ) -> Result<i64>

Record a system metric sample.

Source

pub async fn record_metrics_batch(&self, samples: &[MetricSample]) -> Result<()>

Persist multiple metric samples in a single transaction.

Source

pub async fn latest_metrics_for_namespace( &self, namespace_id: i64, metric_prefix: Option<&str>, limit: i64, ) -> Result<Vec<SystemMetricRow>>

Fetch the newest metric samples for a namespace and optional prefix.

Source

pub async fn count_by_cognitive_level( &self, namespace_id: i64, level: CognitiveLevel, ) -> Result<i64>

Count active memories for a namespace at one cognitive level.

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

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. 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<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