aidaemon_memory/store/mod.rs
1//! The [`MemoryStore`] extension point and the two bundled stores.
2
3mod in_memory;
4mod migrations;
5mod sqlite;
6
7use std::collections::HashMap;
8
9use async_trait::async_trait;
10use chrono::{DateTime, Utc};
11
12use crate::error::Result;
13use crate::neighborhood::{entity_mentioned_as_words, fact_namespace};
14use crate::scoring::term_overlap;
15use crate::types::{
16 DecayReport, Episode, EpisodeRecord, Fact, FactAccess, FactRecord, MemoryStats, NewEpisode,
17 NewFact, RecordKind, RetentionConfig, ScoredEpisode, ScoredFact, StaleEmbedding,
18 StoredEmbedding, UpsertOutcome,
19};
20
21pub use in_memory::InMemoryMemoryStore;
22pub use migrations::{MIGRATIONS, Migration, latest_version};
23pub use sqlite::SqliteMemoryStore;
24
25/// Strength of two facts sharing a key namespace (`alice_rivera:*`).
26const SAME_NAMESPACE_LINK: f32 = 1.0;
27/// Strength of one fact naming the other's subject.
28const MENTION_LINK: f32 = 0.6;
29/// A value longer than this reads as a sentence, not as something named.
30const MAX_ENTITY_WORDS: usize = 4;
31/// A fact whose subject turns up in more facts than this is not naming
32/// anything specific ("yes", a common city), so its mentions carry no signal.
33const MAX_MENTION_FANOUT: usize = 8;
34
35/// Key-namespace and co-mention links from each seed to the other active
36/// facts, by fact id: the graph a store gets without keeping edges. Purely
37/// structural (keys and whole-word mentions), so stores can share it.
38pub fn related_fact_scores(active: &[Fact], seed_ids: &[String]) -> HashMap<String, f32> {
39 let mut scores: HashMap<String, f32> = HashMap::new();
40 let mut raise = |id: &str, score: f32| {
41 let entry = scores.entry(id.to_string()).or_insert(0.0);
42 *entry = entry.max(score);
43 };
44 for seed in active.iter().filter(|f| seed_ids.contains(&f.id)) {
45 let others = active.iter().filter(|f| f.id != seed.id);
46 let mut mentions = Vec::new();
47 for other in others {
48 if share_namespace(seed, other) {
49 raise(&other.id, SAME_NAMESPACE_LINK);
50 } else if names_subject_of(seed, other) || names_subject_of(other, seed) {
51 mentions.push(other.id.as_str());
52 }
53 }
54 if mentions.len() <= MAX_MENTION_FANOUT {
55 mentions.into_iter().for_each(|id| raise(id, MENTION_LINK));
56 }
57 }
58 scores
59}
60
61fn share_namespace(a: &Fact, b: &Fact) -> bool {
62 fact_namespace(&a.key)
63 .zip(fact_namespace(&b.key))
64 .is_some_and(|(a, b)| a.eq_ignore_ascii_case(b))
65}
66
67/// `other`'s key or value names what `fact` is about: its key namespace, or
68/// its value when that is short enough to be a name.
69fn names_subject_of(fact: &Fact, other: &Fact) -> bool {
70 let haystack = format!("{} {}", other.key, other.value);
71 let short_named_value = fact.value.split_whitespace().count() <= MAX_ENTITY_WORDS
72 && fact.value.chars().any(char::is_alphabetic);
73 fact_namespace(&fact.key).is_some_and(|ns| entity_mentioned_as_words(&haystack, ns))
74 || (short_named_value && entity_mentioned_as_words(&haystack, &fact.value))
75}
76
77/// Persistence for facts and episodes. **This is the extension point** for
78/// bringing your own backend (pgvector, Qdrant, a document store, ...).
79/// [`crate::Memory`] holds an `Arc<dyn MemoryStore>`; the trait is
80/// object-safe.
81///
82/// Contract:
83/// - Facts are keyed by `(scope, category, key)` (already normalized when
84/// they arrive) and at most one is active per key.
85/// - `upsert_fact` with a different value marks the active row superseded
86/// (sets `superseded_at`) and inserts a new one; with the same value
87/// (see [`crate::same_value`]) it refreshes `updated_at`, keeps the higher
88/// confidence and returns [`UpsertOutcome::Reinforced`].
89/// - Superseded facts are never returned by `active_facts` or searches, but
90/// remain in `fact_history` until retention deletes them.
91/// - Scopes are hard boundaries: never return another scope's rows.
92///
93/// Lexical scoring and searching have defaults, so a minimal store only
94/// stores rows. A store with its own ranking (vector DB, hybrid search
95/// engine) overrides [`MemoryStore::search_facts`] /
96/// [`MemoryStore::search_episodes`] and the [`crate::Scorer`] is bypassed.
97///
98/// Near-duplicate merging needs nothing from a store: [`crate::Memory`] finds
99/// the duplicate and writes through [`MemoryStore::upsert_fact_with_access`]
100/// on the existing key, which keeps history by the rules above.
101///
102/// Access levels are optional too. A store that keeps the default
103/// [`MemoryStore::fact_access`] cannot say who may see a record, so
104/// [`crate::Memory`] shows its records only to the owner in a direct
105/// conversation and never in a shared channel.
106#[async_trait]
107pub trait MemoryStore: Send + Sync {
108 /// Insert, reinforce or supersede (see the trait docs). `embedding`
109 /// describes the new value's search text, when one was computed.
110 async fn upsert_fact(
111 &self,
112 fact: NewFact,
113 embedding: Option<StoredEmbedding>,
114 now: DateTime<Utc>,
115 ) -> Result<UpsertOutcome>;
116
117 /// [`MemoryStore::upsert_fact`] that records who may see the fact,
118 /// atomically with the write. A reinforced fact keeps the narrowest of
119 /// its access and `access` ([`FactAccess::narrowest`]); a new version
120 /// takes `access`. The default ignores `access`, which leaves the fact
121 /// unclassified and so private.
122 async fn upsert_fact_with_access(
123 &self,
124 fact: NewFact,
125 embedding: Option<StoredEmbedding>,
126 _access: &FactAccess,
127 now: DateTime<Utc>,
128 ) -> Result<UpsertOutcome> {
129 self.upsert_fact(fact, embedding, now).await
130 }
131
132 /// Who may see these facts, by id, for ids in `scope` the store knows. A
133 /// fact absent from the map is unclassified and treated as private.
134 async fn fact_access(
135 &self,
136 _scope: &str,
137 _ids: &[String],
138 ) -> Result<HashMap<String, FactAccess>> {
139 Ok(HashMap::new())
140 }
141
142 /// Mark the active fact for this key superseded. `false` if none.
143 async fn supersede_fact(
144 &self,
145 scope: &str,
146 category: &str,
147 key: &str,
148 now: DateTime<Utc>,
149 ) -> Result<bool>;
150
151 /// Every active fact in `scope`, with embeddings.
152 async fn active_facts(&self, scope: &str) -> Result<Vec<FactRecord>>;
153
154 /// All versions of one key, oldest first, superseded ones included.
155 async fn fact_history(&self, scope: &str, category: &str, key: &str) -> Result<Vec<Fact>>;
156
157 /// Lexical relevance (0.0-1.0) of active facts to `query`, by fact id.
158 /// Facts absent from the map score 0. The default is word overlap over
159 /// [`Fact::search_text`].
160 async fn fact_lexical_scores(&self, scope: &str, query: &str) -> Result<HashMap<String, f32>> {
161 Ok(self
162 .active_facts(scope)
163 .await?
164 .into_iter()
165 .map(|r| {
166 let score = term_overlap(query, &r.fact.search_text());
167 (r.fact.id, score)
168 })
169 .filter(|(_, s)| *s > 0.0)
170 .collect())
171 }
172
173 /// How related each active fact in `scope` is to the `seed_ids` (facts
174 /// that matched the query), 0.0-1.0 by fact id. The default has no graph:
175 /// an empty map leaves the graph signal at 0 and ranking as it was. A
176 /// store that keeps no edges can use [`related_fact_scores`].
177 async fn fact_graph_scores(
178 &self,
179 _scope: &str,
180 _seed_ids: &[String],
181 ) -> Result<HashMap<String, f32>> {
182 Ok(HashMap::new())
183 }
184
185 /// Native ranked search. Return `Some` to bypass the scorer: the result
186 /// is used as is (already filtered, ordered, at most `limit`). The
187 /// default `None` lets [`crate::Memory`] score candidates itself.
188 async fn search_facts(
189 &self,
190 _scope: &str,
191 _query: &str,
192 _query_embedding: Option<&StoredEmbedding>,
193 _limit: usize,
194 ) -> Result<Option<Vec<ScoredFact>>> {
195 Ok(None)
196 }
197
198 /// Bump `recall_count` and set `last_recalled_at` for these facts.
199 async fn record_fact_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()>;
200
201 async fn insert_episode(
202 &self,
203 episode: NewEpisode,
204 embedding: Option<StoredEmbedding>,
205 now: DateTime<Utc>,
206 ) -> Result<Episode>;
207
208 /// [`MemoryStore::insert_episode`] that records who may see the episode.
209 /// The default ignores `access`, leaving the episode private.
210 async fn insert_episode_with_access(
211 &self,
212 episode: NewEpisode,
213 embedding: Option<StoredEmbedding>,
214 _access: &FactAccess,
215 now: DateTime<Utc>,
216 ) -> Result<Episode> {
217 self.insert_episode(episode, embedding, now).await
218 }
219
220 /// Who may see these episodes; see [`MemoryStore::fact_access`].
221 async fn episode_access(
222 &self,
223 _scope: &str,
224 _ids: &[String],
225 ) -> Result<HashMap<String, FactAccess>> {
226 Ok(HashMap::new())
227 }
228
229 /// Every episode in `scope`, with embeddings.
230 async fn episodes(&self, scope: &str) -> Result<Vec<EpisodeRecord>>;
231
232 /// Lexical relevance of episodes; default word overlap.
233 async fn episode_lexical_scores(
234 &self,
235 scope: &str,
236 query: &str,
237 ) -> Result<HashMap<String, f32>> {
238 Ok(self
239 .episodes(scope)
240 .await?
241 .into_iter()
242 .map(|r| {
243 let score = term_overlap(query, &r.episode.search_text());
244 (r.episode.id, score)
245 })
246 .filter(|(_, s)| *s > 0.0)
247 .collect())
248 }
249
250 /// Native ranked episode search; see [`MemoryStore::search_facts`].
251 async fn search_episodes(
252 &self,
253 _scope: &str,
254 _query: &str,
255 _query_embedding: Option<&StoredEmbedding>,
256 _limit: usize,
257 ) -> Result<Option<Vec<ScoredEpisode>>> {
258 Ok(None)
259 }
260
261 async fn record_episode_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()>;
262
263 /// Apply recall decay and retention (see [`RetentionConfig`]). The
264 /// default does nothing, for stores whose backend handles expiry.
265 async fn decay(&self, _now: DateTime<Utc>, _config: &RetentionConfig) -> Result<DecayReport> {
266 Ok(DecayReport::default())
267 }
268
269 /// Up to `limit` records of `kind` with no vector or a vector from a
270 /// model other than `model`, in ascending id order after `after_id`.
271 /// Superseded facts are excluded: they are never compared. The default
272 /// finds none, so such a store keeps lexical recall for old rows.
273 async fn stale_embeddings(
274 &self,
275 _model: &str,
276 _kind: RecordKind,
277 _after_id: Option<&str>,
278 _limit: usize,
279 ) -> Result<Vec<StaleEmbedding>> {
280 Ok(Vec::new())
281 }
282
283 /// Replace a stale record's vector, only if it still has the model
284 /// `stale` reported; `false` otherwise. Changes nothing else about the
285 /// record: `updated_at` feeds ranking and this is not a new statement.
286 async fn replace_embedding(
287 &self,
288 _stale: &StaleEmbedding,
289 _embedding: StoredEmbedding,
290 ) -> Result<bool> {
291 Ok(false)
292 }
293
294 async fn stats(&self) -> Result<MemoryStats>;
295}