Skip to main content

aidaemon_memory/
stores.rs

1//! The daemon-shaped memory storage contract: facts (with privacy, channel
2//! provenance and the extraction graph), episodes, exact history and
3//! people. A store implements the slices it supports; every method has a
4//! conservative default.
5
6use std::collections::HashSet;
7
8use aidaemon_core::ChannelVisibility;
9use async_trait::async_trait;
10
11use crate::records::*;
12
13/// Exact-history operations exposed to the search tool through a domain port.
14#[async_trait]
15pub trait HistorySearchStore: Send + Sync {
16    async fn history_snapshot_max_event_id(&self) -> anyhow::Result<i64>;
17    async fn history_coverage(&self) -> anyhow::Result<HistoryCoverage>;
18    async fn repair_history_projection(
19        &self,
20        max_batches: usize,
21    ) -> anyhow::Result<ProjectionStats>;
22    async fn search_history(
23        &self,
24        query: &str,
25        scope: &HistoryScope,
26        limit: usize,
27        semantic_sessions: &HashSet<String>,
28    ) -> anyhow::Result<Vec<HistoryMessage>>;
29    async fn history_context(
30        &self,
31        event_id: i64,
32        radius: usize,
33        scope: &HistoryScope,
34    ) -> anyhow::Result<Vec<HistoryMessage>>;
35    async fn history_event_for_message_id(
36        &self,
37        message_id: &str,
38        scope: &HistoryScope,
39    ) -> anyhow::Result<Option<i64>>;
40    async fn history_turn(
41        &self,
42        turn_id: &str,
43        scope: &HistoryScope,
44    ) -> anyhow::Result<Vec<HistoryMessage>>;
45    /// The tool calls of a turn the scope may read; empty when it may not.
46    async fn history_turn_tool_activity(
47        &self,
48        turn_id: &str,
49        scope: &HistoryScope,
50    ) -> anyhow::Result<Vec<HistoryToolActivity>>;
51    /// Which of the session's last `turns` prior user turns ran tools, oldest
52    /// first. Carries no message or tool content.
53    async fn history_recent_tool_turns(
54        &self,
55        session_id: &str,
56        turns: usize,
57    ) -> anyhow::Result<Vec<RecentToolTurn>>;
58    async fn history_page(
59        &self,
60        anchor: i64,
61        older: bool,
62        scope: &HistoryScope,
63        limit: usize,
64    ) -> anyhow::Result<Vec<HistoryMessage>>;
65    async fn history_task_bookends(
66        &self,
67        task_id: Option<&str>,
68        session_id: &str,
69        scope: &HistoryScope,
70    ) -> anyhow::Result<TaskBookends>;
71}
72
73/// Layer-2 facts storage and retrieval (including privacy + channel provenance).
74#[async_trait]
75pub trait FactStore: Send + Sync {
76    /// Reconcile an entity-aware personal-memory write atomically.
77    async fn reconcile_personal_memory(
78        &self,
79        _write: &PersonalMemoryWrite,
80        _source: &str,
81        _source_excerpt: Option<&str>,
82        _channel_id: Option<&str>,
83        _privacy: FactPrivacy,
84    ) -> anyhow::Result<PersonalMemoryWriteResult> {
85        anyhow::bail!("structured personal memory is not supported by this store")
86    }
87
88    /// Compatibility projection of active canonical facts and relationships.
89    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
90        Ok(Vec::new())
91    }
92
93    /// Record that these facts and episodes were shown to a model. Recall
94    /// counts drive Core Profile salience and decay, so only content that
95    /// actually reached a prompt or a tool result may count; fetching a
96    /// candidate that was then cut by a budget is not a recall.
97    async fn record_memory_recall(
98        &self,
99        _fact_ids: &[i64],
100        _episode_ids: &[i64],
101    ) -> anyhow::Result<()> {
102        Ok(())
103    }
104
105    /// Supersede active automated facts that restate another active fact in
106    /// the same category, keeping the most authoritative copy. Returns how
107    /// many rows were folded. Soft: superseded rows remain as history.
108    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
109        Ok(0)
110    }
111
112    /// Upsert a fact with channel provenance and privacy level.
113    async fn upsert_fact(
114        &self,
115        category: &str,
116        key: &str,
117        value: &str,
118        source: &str,
119        channel_id: Option<&str>,
120        privacy: FactPrivacy,
121    ) -> anyhow::Result<()> {
122        self.upsert_fact_with_provenance(
123            category, key, value, source, channel_id, privacy, None, None,
124        )
125        .await
126    }
127
128    /// Upsert a fact with full provenance data.
129    #[allow(clippy::too_many_arguments)]
130    async fn upsert_fact_with_provenance(
131        &self,
132        category: &str,
133        key: &str,
134        value: &str,
135        source: &str,
136        channel_id: Option<&str>,
137        privacy: FactPrivacy,
138        first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
139        source_excerpt: Option<&str>,
140    ) -> anyhow::Result<()>;
141
142    /// Get all facts, optionally filtered by category.
143    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;
144
145    /// Get facts semantically relevant to a query, falling back to `get_facts` on error.
146    async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
147        // Default: return all facts (capped). Implementations can override with semantic filtering.
148        let mut facts = self.get_facts(None).await?;
149        facts.truncate(max);
150        Ok(facts)
151    }
152
153    /// Get facts for a specific channel context, respecting privacy levels.
154    ///
155    /// `requester_is_owner` controls the DM short-circuit: only the owner sees the
156    /// full unfiltered graph (incl. Private + other-channel facts) in a 1:1 DM. A
157    /// non-owner (an allowlisted Guest) gets the same privacy filtering as a group
158    /// channel — Global + same-channel facts only, never Private or other-channel —
159    /// so owner secrets can't leak into a guest's prompt context.
160    async fn get_relevant_facts_for_channel(
161        &self,
162        query: &str,
163        max: usize,
164        _channel_id: Option<&str>,
165        _visibility: ChannelVisibility,
166        _requester_is_owner: bool,
167    ) -> anyhow::Result<Vec<Fact>> {
168        self.get_relevant_facts(query, max).await
169    }
170
171    /// Update a fact's privacy level (e.g., channel → global after approval).
172    async fn update_fact_privacy(
173        &self,
174        _fact_id: i64,
175        _privacy: FactPrivacy,
176    ) -> anyhow::Result<()> {
177        Ok(())
178    }
179
180    /// Record where the active fact at this key came from.
181    async fn stamp_fact_provenance(
182        &self,
183        _category: &str,
184        _key: &str,
185        _source: &str,
186        _first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
187        _source_excerpt: Option<&str>,
188    ) -> anyhow::Result<()> {
189        Ok(())
190    }
191
192    /// Soft-delete a fact by superseding it.
193    async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
194        Ok(())
195    }
196
197    /// Soft-delete a fact by category and key. Returns true if a fact was found and deleted.
198    async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
199        Ok(false)
200    }
201
202    /// Get all active facts with provenance info for memory management display.
203    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
204        self.get_facts(None).await
205    }
206
207    /// Explicit fact search: one ranked list plus query-relevant related
208    /// facts. Ranking lives in [`crate::search`]; a store only gathers facts
209    /// and scores. The default returns an empty report so stores without
210    /// search keep compiling.
211    async fn search_facts(
212        &self,
213        _query: &str,
214        _limit: usize,
215        _config: &crate::search::FactSearchConfig,
216    ) -> anyhow::Result<crate::search::FactSearchReport> {
217        Ok(crate::search::FactSearchReport::default())
218    }
219
220    /// Persist a model-extracted semantic graph for an already-written fact.
221    /// Implementations must validate the graph and retain claim provenance.
222    async fn project_extracted_fact_graph(
223        &self,
224        _category: &str,
225        _key: &str,
226        _source_excerpt: &str,
227        _graph: &ExtractedMemoryGraph,
228    ) -> anyhow::Result<()> {
229        Ok(())
230    }
231
232    /// Refresh canonical claim/vector projections for the active fact at this key.
233    async fn refresh_fact_memory(&self, _category: &str, _key: &str) -> anyhow::Result<()> {
234        Ok(())
235    }
236
237    async fn memory_health_report(&self) -> anyhow::Result<MemoryHealthReport> {
238        Ok(MemoryHealthReport::default())
239    }
240
241    async fn repair_memory_projections(&self) -> anyhow::Result<MemoryHealthReport> {
242        self.memory_health_report().await
243    }
244}
245
246/// Episodic memory storage and retrieval.
247#[async_trait]
248pub trait EpisodeStore: Send + Sync {
249    /// Refresh derived canonical-memory projections for an episode. Stores that
250    /// do not maintain secondary indexes may keep the default no-op.
251    async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
252        Ok(())
253    }
254
255    /// Get episodes relevant to a query.
256    async fn get_relevant_episodes(
257        &self,
258        _query: &str,
259        _limit: usize,
260    ) -> anyhow::Result<Vec<Episode>> {
261        Ok(vec![])
262    }
263
264    /// Get episodes for a specific channel context.
265    async fn get_relevant_episodes_for_channel(
266        &self,
267        _query: &str,
268        _limit: usize,
269        _channel_id: Option<&str>,
270    ) -> anyhow::Result<Vec<Episode>> {
271        Ok(vec![])
272    }
273
274    /// Get episodes only from one canonical session (used by untrusted
275    /// internal/sub-agent origins).
276    async fn get_relevant_episodes_for_session(
277        &self,
278        _query: &str,
279        _limit: usize,
280        _session_id: &str,
281    ) -> anyhow::Result<Vec<Episode>> {
282        Ok(vec![])
283    }
284
285    /// Where the session's most recent episode stopped, if it has one.
286    async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
287        Ok(None)
288    }
289
290    /// `(session id, latest episode end time)` for every session with an
291    /// episode.
292    async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
293        Ok(vec![])
294    }
295
296    /// Record a session episode; returns its id. A store that keeps
297    /// episodes also embeds the summary for recall.
298    async fn record_session_episode(
299        &self,
300        _episode: &crate::episodes::SessionEpisode,
301    ) -> anyhow::Result<i64> {
302        anyhow::bail!("this store does not record session episodes")
303    }
304}
305
306/// People persistence (social graph).
307#[async_trait]
308pub trait PeopleStore: Send + Sync {
309    /// Create or update a person record. Returns the person ID.
310    async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
311        Ok(0)
312    }
313
314    /// Get a person by their database ID.
315    async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
316        Ok(None)
317    }
318
319    /// Look up a person by a platform-qualified sender ID (e.g., "slack:U123").
320    async fn get_person_by_platform_id(
321        &self,
322        _platform_id: &str,
323    ) -> anyhow::Result<Option<Person>> {
324        Ok(None)
325    }
326
327    /// Find a person by name or alias (case-insensitive).
328    async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
329        Ok(None)
330    }
331
332    /// Get all people.
333    async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
334        Ok(vec![])
335    }
336
337    /// Delete a person and all their facts (cascade).
338    async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
339        Ok(())
340    }
341
342    /// Link a platform identity to a person.
343    async fn link_platform_id(
344        &self,
345        _person_id: i64,
346        _platform_id: &str,
347        _display_name: &str,
348    ) -> anyhow::Result<()> {
349        Ok(())
350    }
351
352    /// Update interaction tracking for a person.
353    async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
354        Ok(())
355    }
356
357    /// Create or update a fact about a person.
358    async fn upsert_person_fact(
359        &self,
360        _person_id: i64,
361        _category: &str,
362        _key: &str,
363        _value: &str,
364        _source: &str,
365        _confidence: f32,
366    ) -> anyhow::Result<()> {
367        Ok(())
368    }
369
370    /// Get facts about a person, optionally filtered by category.
371    async fn get_person_facts(
372        &self,
373        _person_id: i64,
374        _category: Option<&str>,
375    ) -> anyhow::Result<Vec<PersonFact>> {
376        Ok(vec![])
377    }
378
379    /// Delete a person fact by ID.
380    async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
381        Ok(())
382    }
383
384    /// Confirm an auto-extracted person fact (set confidence to 1.0).
385    async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
386        Ok(())
387    }
388
389    /// Get people with upcoming dates (birthdays, important dates) within N days.
390    async fn get_people_with_upcoming_dates(
391        &self,
392        _within_days: i32,
393    ) -> anyhow::Result<Vec<(Person, PersonFact)>> {
394        Ok(vec![])
395    }
396
397    /// Delete stale auto-extracted person facts older than N days with confidence < 1.0.
398    async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
399        Ok(0)
400    }
401
402    /// Get people who haven't interacted in more than N days.
403    async fn get_people_needing_reconnect(
404        &self,
405        _inactive_days: u32,
406    ) -> anyhow::Result<Vec<Person>> {
407        Ok(vec![])
408    }
409}
410
411/// An entity to create or merge in the memory graph.
412#[derive(Debug, Clone)]
413pub struct GraphEntityUpsert {
414    pub entity_type: String,
415    pub canonical_name: String,
416    pub display_name: String,
417    pub aliases: Vec<String>,
418    pub channel_id: Option<String>,
419    pub privacy: FactPrivacy,
420}
421
422#[derive(Debug, Clone)]
423pub struct GraphEdgeUpsert {
424    pub source_entity_id: i64,
425    pub target_entity_id: i64,
426    pub relation: String,
427    pub source_claim_id: i64,
428    pub confidence: f32,
429    pub channel_id: Option<String>,
430    pub privacy: FactPrivacy,
431}
432
433#[derive(Debug, Clone)]
434pub struct GraphSearchScope {
435    pub channel_id: Option<String>,
436    pub visibility: ChannelVisibility,
437    pub requester_is_owner: bool,
438}
439
440#[derive(Debug, Clone)]
441pub struct GraphNeighbor {
442    pub entity_id: i64,
443    pub display_name: String,
444    pub relation: String,
445    pub depth: usize,
446}
447
448/// The memory graph: entities and the relations between them, each edge
449/// backed by the claim (fact) that asserts it, so retracting the claim
450/// invalidates the edge.
451#[async_trait]
452pub trait MemoryGraphStore: Send + Sync {
453    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64>;
454    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()>;
455    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()>;
456    async fn neighbors(
457        &self,
458        start_entity_id: i64,
459        max_depth: usize,
460        scope: &GraphSearchScope,
461    ) -> anyhow::Result<Vec<GraphNeighbor>>;
462}
463
464/// How unrecalled memory fades. Facts not recalled for `fact_idle_days`
465/// lose `1 / fact_decay_divisor` of their recall count per pass (at least
466/// one); episodes not recalled for `episode_idle_days` lose one; behavior
467/// patterns not seen for `pattern_idle_days` lose `pattern_step`
468/// confidence (down to 0.1).
469#[derive(Debug, Clone, Copy, PartialEq)]
470pub struct DecayPolicy {
471    pub fact_idle_days: i64,
472    pub fact_decay_divisor: i64,
473    pub episode_idle_days: i64,
474    pub pattern_idle_days: i64,
475    pub pattern_step: f32,
476}
477
478impl Default for DecayPolicy {
479    fn default() -> Self {
480        Self {
481            fact_idle_days: 14,
482            fact_decay_divisor: 10,
483            episode_idle_days: 30,
484            pattern_idle_days: 30,
485            pattern_step: 0.05,
486        }
487    }
488}
489
490/// Fading of unrecalled memory, applied by the store.
491#[async_trait]
492pub trait MemoryDecay: Send + Sync {
493    async fn decay(
494        &self,
495        policy: &DecayPolicy,
496        now: chrono::DateTime<chrono::Utc>,
497    ) -> anyhow::Result<()>;
498}
499
500/// One maintenance pass: merge restated facts, then let unrecalled memory
501/// fade, so decay sees one row per piece of knowledge.
502pub async fn decay_memory<S>(store: &S, policy: &DecayPolicy) -> anyhow::Result<()>
503where
504    S: FactStore + MemoryDecay + ?Sized,
505{
506    if let Err(error) = store.fold_restated_facts().await {
507        tracing::warn!(%error, "Failed to fold restated facts");
508    }
509    store.decay(policy, chrono::Utc::now()).await
510}
511
512/// Every store behind the daemon-shaped memory contract, as one handle.
513pub trait MemoryStores:
514    FactStore + EpisodeStore + PeopleStore + crate::LearningStore + MemoryGraphStore + MemoryDecay
515{
516}
517
518impl<T> MemoryStores for T where
519    T: FactStore
520        + EpisodeStore
521        + PeopleStore
522        + crate::LearningStore
523        + MemoryGraphStore
524        + MemoryDecay
525{
526}