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    /// Edit an active fact's value in place as an explicit owner update.
203    /// Supports both positive flat fact ids and negative canonical ids where
204    /// editable (owner facts and aliases). Returns the updated fact if found.
205    async fn update_fact_value(&self, _fact_id: i64, _value: &str) -> anyhow::Result<Option<Fact>> {
206        Ok(None)
207    }
208
209    /// Reversibly archive an active fact so it leaves passive recall without
210    /// permanent deletion. Returns true if an active fact was archived.
211    async fn archive_fact(&self, _fact_id: i64) -> anyhow::Result<bool> {
212        Ok(false)
213    }
214
215    /// Restore a previously archived fact back to active memory.
216    async fn restore_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
217        Ok(None)
218    }
219
220    /// Archived facts available for restore, newest first.
221    async fn get_archived_facts(&self, _limit: usize) -> anyhow::Result<Vec<Fact>> {
222        Ok(Vec::new())
223    }
224
225    /// Automatically archive active facts whose typed `expires_at` has passed.
226    async fn archive_expired_facts(
227        &self,
228        _now: chrono::DateTime<chrono::Utc>,
229    ) -> anyhow::Result<u64> {
230        Ok(0)
231    }
232
233    /// Map of active fact id -> another active fact id that looks like a
234    /// conceptual duplicate/overlap (for UI review hints).
235    async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
236        Ok(std::collections::HashMap::new())
237    }
238
239    /// Get all active facts with provenance info for memory management display.
240    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
241        self.get_facts(None).await
242    }
243
244    /// Explicit fact search: one ranked list plus query-relevant related
245    /// facts. Ranking lives in [`crate::search`]; a store only gathers facts
246    /// and scores. The default returns an empty report so stores without
247    /// search keep compiling.
248    async fn search_facts(
249        &self,
250        _query: &str,
251        _limit: usize,
252        _config: &crate::search::FactSearchConfig,
253    ) -> anyhow::Result<crate::search::FactSearchReport> {
254        Ok(crate::search::FactSearchReport::default())
255    }
256
257    /// Persist a model-extracted semantic graph for an already-written fact.
258    /// Implementations must validate the graph and retain claim provenance.
259    async fn project_extracted_fact_graph(
260        &self,
261        _category: &str,
262        _key: &str,
263        _source_excerpt: &str,
264        _graph: &ExtractedMemoryGraph,
265    ) -> anyhow::Result<()> {
266        Ok(())
267    }
268
269    /// Refresh canonical claim/vector projections for the active fact at this key.
270    async fn refresh_fact_memory(&self, _category: &str, _key: &str) -> anyhow::Result<()> {
271        Ok(())
272    }
273
274    async fn memory_health_report(&self) -> anyhow::Result<MemoryHealthReport> {
275        Ok(MemoryHealthReport::default())
276    }
277
278    async fn repair_memory_projections(&self) -> anyhow::Result<MemoryHealthReport> {
279        self.memory_health_report().await
280    }
281}
282
283/// Episodic memory storage and retrieval.
284#[async_trait]
285pub trait EpisodeStore: Send + Sync {
286    /// Refresh derived canonical-memory projections for an episode. Stores that
287    /// do not maintain secondary indexes may keep the default no-op.
288    async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
289        Ok(())
290    }
291
292    /// Get episodes relevant to a query.
293    async fn get_relevant_episodes(
294        &self,
295        _query: &str,
296        _limit: usize,
297    ) -> anyhow::Result<Vec<Episode>> {
298        Ok(vec![])
299    }
300
301    /// Get episodes for a specific channel context.
302    async fn get_relevant_episodes_for_channel(
303        &self,
304        _query: &str,
305        _limit: usize,
306        _channel_id: Option<&str>,
307    ) -> anyhow::Result<Vec<Episode>> {
308        Ok(vec![])
309    }
310
311    /// Get episodes only from one canonical session (used by untrusted
312    /// internal/sub-agent origins).
313    async fn get_relevant_episodes_for_session(
314        &self,
315        _query: &str,
316        _limit: usize,
317        _session_id: &str,
318    ) -> anyhow::Result<Vec<Episode>> {
319        Ok(vec![])
320    }
321
322    /// Where the session's most recent episode stopped, if it has one.
323    async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
324        Ok(None)
325    }
326
327    /// `(session id, latest episode end time)` for every session with an
328    /// episode.
329    async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
330        Ok(vec![])
331    }
332
333    /// Record a session episode; returns its id. A store that keeps
334    /// episodes also embeds the summary for recall.
335    async fn record_session_episode(
336        &self,
337        _episode: &crate::episodes::SessionEpisode,
338    ) -> anyhow::Result<i64> {
339        anyhow::bail!("this store does not record session episodes")
340    }
341}
342
343/// People persistence (social graph).
344#[async_trait]
345pub trait PeopleStore: Send + Sync {
346    /// Create or update a person record. Returns the person ID.
347    async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
348        Ok(0)
349    }
350
351    /// Get a person by their database ID.
352    async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
353        Ok(None)
354    }
355
356    /// Look up a person by a platform-qualified sender ID (e.g., "slack:U123").
357    async fn get_person_by_platform_id(
358        &self,
359        _platform_id: &str,
360    ) -> anyhow::Result<Option<Person>> {
361        Ok(None)
362    }
363
364    /// Find a person by name or alias (case-insensitive).
365    async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
366        Ok(None)
367    }
368
369    /// Get all people.
370    async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
371        Ok(vec![])
372    }
373
374    /// Delete a person and all their facts (cascade).
375    async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
376        Ok(())
377    }
378
379    /// Link a platform identity to a person.
380    async fn link_platform_id(
381        &self,
382        _person_id: i64,
383        _platform_id: &str,
384        _display_name: &str,
385    ) -> anyhow::Result<()> {
386        Ok(())
387    }
388
389    /// Update interaction tracking for a person.
390    async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
391        Ok(())
392    }
393
394    /// Create or update a fact about a person.
395    async fn upsert_person_fact(
396        &self,
397        _person_id: i64,
398        _category: &str,
399        _key: &str,
400        _value: &str,
401        _source: &str,
402        _confidence: f32,
403    ) -> anyhow::Result<()> {
404        Ok(())
405    }
406
407    /// Get facts about a person, optionally filtered by category.
408    async fn get_person_facts(
409        &self,
410        _person_id: i64,
411        _category: Option<&str>,
412    ) -> anyhow::Result<Vec<PersonFact>> {
413        Ok(vec![])
414    }
415
416    /// Delete a person fact by ID.
417    async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
418        Ok(())
419    }
420
421    /// Confirm an auto-extracted person fact (set confidence to 1.0).
422    async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
423        Ok(())
424    }
425
426    /// Get people with upcoming dates (birthdays, important dates) within N days.
427    async fn get_people_with_upcoming_dates(
428        &self,
429        _within_days: i32,
430    ) -> anyhow::Result<Vec<(Person, PersonFact)>> {
431        Ok(vec![])
432    }
433
434    /// Delete stale auto-extracted person facts older than N days with confidence < 1.0.
435    async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
436        Ok(0)
437    }
438
439    /// Get people who haven't interacted in more than N days.
440    async fn get_people_needing_reconnect(
441        &self,
442        _inactive_days: u32,
443    ) -> anyhow::Result<Vec<Person>> {
444        Ok(vec![])
445    }
446}
447
448/// An entity to create or merge in the memory graph.
449#[derive(Debug, Clone)]
450pub struct GraphEntityUpsert {
451    pub entity_type: String,
452    pub canonical_name: String,
453    pub display_name: String,
454    pub aliases: Vec<String>,
455    pub channel_id: Option<String>,
456    pub privacy: FactPrivacy,
457}
458
459#[derive(Debug, Clone)]
460pub struct GraphEdgeUpsert {
461    pub source_entity_id: i64,
462    pub target_entity_id: i64,
463    pub relation: String,
464    pub source_claim_id: i64,
465    pub confidence: f32,
466    pub channel_id: Option<String>,
467    pub privacy: FactPrivacy,
468}
469
470#[derive(Debug, Clone)]
471pub struct GraphSearchScope {
472    pub channel_id: Option<String>,
473    pub visibility: ChannelVisibility,
474    pub requester_is_owner: bool,
475}
476
477#[derive(Debug, Clone)]
478pub struct GraphNeighbor {
479    pub entity_id: i64,
480    pub display_name: String,
481    pub relation: String,
482    pub depth: usize,
483}
484
485/// The memory graph: entities and the relations between them, each edge
486/// backed by the claim (fact) that asserts it, so retracting the claim
487/// invalidates the edge.
488#[async_trait]
489pub trait MemoryGraphStore: Send + Sync {
490    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64>;
491    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()>;
492    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()>;
493    async fn neighbors(
494        &self,
495        start_entity_id: i64,
496        max_depth: usize,
497        scope: &GraphSearchScope,
498    ) -> anyhow::Result<Vec<GraphNeighbor>>;
499}
500
501/// How unrecalled memory fades. Facts not recalled for `fact_idle_days`
502/// lose `1 / fact_decay_divisor` of their recall count per pass (at least
503/// one); episodes not recalled for `episode_idle_days` lose one; behavior
504/// patterns not seen for `pattern_idle_days` lose `pattern_step`
505/// confidence (down to 0.1).
506#[derive(Debug, Clone, Copy, PartialEq)]
507pub struct DecayPolicy {
508    pub fact_idle_days: i64,
509    pub fact_decay_divisor: i64,
510    pub episode_idle_days: i64,
511    pub pattern_idle_days: i64,
512    pub pattern_step: f32,
513}
514
515impl Default for DecayPolicy {
516    fn default() -> Self {
517        Self {
518            fact_idle_days: 14,
519            fact_decay_divisor: 10,
520            episode_idle_days: 30,
521            pattern_idle_days: 30,
522            pattern_step: 0.05,
523        }
524    }
525}
526
527/// Fading of unrecalled memory, applied by the store.
528#[async_trait]
529pub trait MemoryDecay: Send + Sync {
530    async fn decay(
531        &self,
532        policy: &DecayPolicy,
533        now: chrono::DateTime<chrono::Utc>,
534    ) -> anyhow::Result<()>;
535}
536
537/// One maintenance pass: archive expired facts, merge restated facts, then
538/// let unrecalled memory fade, so decay sees one active row per piece of
539/// knowledge.
540pub async fn decay_memory<S>(store: &S, policy: &DecayPolicy) -> anyhow::Result<()>
541where
542    S: FactStore + MemoryDecay + ?Sized,
543{
544    let now = chrono::Utc::now();
545    if let Err(error) = store.archive_expired_facts(now).await {
546        tracing::warn!(%error, "Failed to archive expired facts");
547    }
548    if let Err(error) = store.fold_restated_facts().await {
549        tracing::warn!(%error, "Failed to fold restated facts");
550    }
551    store.decay(policy, now).await
552}
553
554/// Every store behind the daemon-shaped memory contract, as one handle.
555pub trait MemoryStores:
556    FactStore + EpisodeStore + PeopleStore + crate::LearningStore + MemoryGraphStore + MemoryDecay
557{
558}
559
560impl<T> MemoryStores for T where
561    T: FactStore
562        + EpisodeStore
563        + PeopleStore
564        + crate::LearningStore
565        + MemoryGraphStore
566        + MemoryDecay
567{
568}