mod in_memory;
mod migrations;
mod sqlite;
use std::collections::HashMap;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use crate::error::Result;
use crate::neighborhood::{entity_mentioned_as_words, fact_namespace};
use crate::scoring::term_overlap;
use crate::types::{
DecayReport, Episode, EpisodeRecord, Fact, FactAccess, FactRecord, MemoryStats, NewEpisode,
NewFact, RecordKind, RetentionConfig, ScoredEpisode, ScoredFact, StaleEmbedding,
StoredEmbedding, UpsertOutcome,
};
pub use in_memory::InMemoryMemoryStore;
pub use migrations::{MIGRATIONS, Migration, latest_version};
pub use sqlite::SqliteMemoryStore;
const SAME_NAMESPACE_LINK: f32 = 1.0;
const MENTION_LINK: f32 = 0.6;
const MAX_ENTITY_WORDS: usize = 4;
const MAX_MENTION_FANOUT: usize = 8;
pub fn related_fact_scores(active: &[Fact], seed_ids: &[String]) -> HashMap<String, f32> {
let mut scores: HashMap<String, f32> = HashMap::new();
let mut raise = |id: &str, score: f32| {
let entry = scores.entry(id.to_string()).or_insert(0.0);
*entry = entry.max(score);
};
for seed in active.iter().filter(|f| seed_ids.contains(&f.id)) {
let others = active.iter().filter(|f| f.id != seed.id);
let mut mentions = Vec::new();
for other in others {
if share_namespace(seed, other) {
raise(&other.id, SAME_NAMESPACE_LINK);
} else if names_subject_of(seed, other) || names_subject_of(other, seed) {
mentions.push(other.id.as_str());
}
}
if mentions.len() <= MAX_MENTION_FANOUT {
mentions.into_iter().for_each(|id| raise(id, MENTION_LINK));
}
}
scores
}
fn share_namespace(a: &Fact, b: &Fact) -> bool {
fact_namespace(&a.key)
.zip(fact_namespace(&b.key))
.is_some_and(|(a, b)| a.eq_ignore_ascii_case(b))
}
fn names_subject_of(fact: &Fact, other: &Fact) -> bool {
let haystack = format!("{} {}", other.key, other.value);
let short_named_value = fact.value.split_whitespace().count() <= MAX_ENTITY_WORDS
&& fact.value.chars().any(char::is_alphabetic);
fact_namespace(&fact.key).is_some_and(|ns| entity_mentioned_as_words(&haystack, ns))
|| (short_named_value && entity_mentioned_as_words(&haystack, &fact.value))
}
#[async_trait]
pub trait MemoryStore: Send + Sync {
async fn upsert_fact(
&self,
fact: NewFact,
embedding: Option<StoredEmbedding>,
now: DateTime<Utc>,
) -> Result<UpsertOutcome>;
async fn upsert_fact_with_access(
&self,
fact: NewFact,
embedding: Option<StoredEmbedding>,
_access: &FactAccess,
now: DateTime<Utc>,
) -> Result<UpsertOutcome> {
self.upsert_fact(fact, embedding, now).await
}
async fn fact_access(
&self,
_scope: &str,
_ids: &[String],
) -> Result<HashMap<String, FactAccess>> {
Ok(HashMap::new())
}
async fn supersede_fact(
&self,
scope: &str,
category: &str,
key: &str,
now: DateTime<Utc>,
) -> Result<bool>;
async fn active_facts(&self, scope: &str) -> Result<Vec<FactRecord>>;
async fn fact_history(&self, scope: &str, category: &str, key: &str) -> Result<Vec<Fact>>;
async fn fact_lexical_scores(&self, scope: &str, query: &str) -> Result<HashMap<String, f32>> {
Ok(self
.active_facts(scope)
.await?
.into_iter()
.map(|r| {
let score = term_overlap(query, &r.fact.search_text());
(r.fact.id, score)
})
.filter(|(_, s)| *s > 0.0)
.collect())
}
async fn fact_graph_scores(
&self,
_scope: &str,
_seed_ids: &[String],
) -> Result<HashMap<String, f32>> {
Ok(HashMap::new())
}
async fn search_facts(
&self,
_scope: &str,
_query: &str,
_query_embedding: Option<&StoredEmbedding>,
_limit: usize,
) -> Result<Option<Vec<ScoredFact>>> {
Ok(None)
}
async fn record_fact_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()>;
async fn insert_episode(
&self,
episode: NewEpisode,
embedding: Option<StoredEmbedding>,
now: DateTime<Utc>,
) -> Result<Episode>;
async fn insert_episode_with_access(
&self,
episode: NewEpisode,
embedding: Option<StoredEmbedding>,
_access: &FactAccess,
now: DateTime<Utc>,
) -> Result<Episode> {
self.insert_episode(episode, embedding, now).await
}
async fn episode_access(
&self,
_scope: &str,
_ids: &[String],
) -> Result<HashMap<String, FactAccess>> {
Ok(HashMap::new())
}
async fn episodes(&self, scope: &str) -> Result<Vec<EpisodeRecord>>;
async fn episode_lexical_scores(
&self,
scope: &str,
query: &str,
) -> Result<HashMap<String, f32>> {
Ok(self
.episodes(scope)
.await?
.into_iter()
.map(|r| {
let score = term_overlap(query, &r.episode.search_text());
(r.episode.id, score)
})
.filter(|(_, s)| *s > 0.0)
.collect())
}
async fn search_episodes(
&self,
_scope: &str,
_query: &str,
_query_embedding: Option<&StoredEmbedding>,
_limit: usize,
) -> Result<Option<Vec<ScoredEpisode>>> {
Ok(None)
}
async fn record_episode_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()>;
async fn decay(&self, _now: DateTime<Utc>, _config: &RetentionConfig) -> Result<DecayReport> {
Ok(DecayReport::default())
}
async fn stale_embeddings(
&self,
_model: &str,
_kind: RecordKind,
_after_id: Option<&str>,
_limit: usize,
) -> Result<Vec<StaleEmbedding>> {
Ok(Vec::new())
}
async fn replace_embedding(
&self,
_stale: &StaleEmbedding,
_embedding: StoredEmbedding,
) -> Result<bool> {
Ok(false)
}
async fn stats(&self) -> Result<MemoryStats>;
}