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/// A reviewer's verdict on two facts the overlap detector paired. Stored
74/// with both facts' content hashes: an edit to either one voids it.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum OverlapReviewVerdict {
77    /// Two different pieces of knowledge: never flag the pair again.
78    Distinct,
79    /// One attribute with two values that only the owner can settle.
80    Conflict,
81    /// Reviewed by background hygiene with no automatic action taken (e.g.
82    /// cross-scope or rank-guarded); keeps the UI hint visible while stopping
83    /// background hygiene from re-billing the unchanged pair.
84    Reviewed,
85}
86
87impl OverlapReviewVerdict {
88    pub fn as_str(self) -> &'static str {
89        match self {
90            Self::Distinct => "distinct",
91            Self::Conflict => "conflict",
92            Self::Reviewed => "reviewed",
93        }
94    }
95
96    pub fn parse(value: &str) -> Option<Self> {
97        match value.trim() {
98            "distinct" => Some(Self::Distinct),
99            "conflict" => Some(Self::Conflict),
100            "reviewed" => Some(Self::Reviewed),
101            _ => None,
102        }
103    }
104}
105
106/// Layer-2 facts storage and retrieval (including privacy + channel provenance).
107#[async_trait]
108pub trait FactStore: Send + Sync {
109    /// Reconcile an entity-aware personal-memory write atomically.
110    async fn reconcile_personal_memory(
111        &self,
112        _write: &PersonalMemoryWrite,
113        _source: &str,
114        _source_excerpt: Option<&str>,
115        _channel_id: Option<&str>,
116        _privacy: FactPrivacy,
117    ) -> anyhow::Result<PersonalMemoryWriteResult> {
118        anyhow::bail!("structured personal memory is not supported by this store")
119    }
120
121    /// Compatibility projection of active canonical facts and relationships.
122    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
123        Ok(Vec::new())
124    }
125
126    /// Record that these facts and episodes were shown to a model. Recall
127    /// counts drive Core Profile salience and decay, so only content that
128    /// actually reached a prompt or a tool result may count; fetching a
129    /// candidate that was then cut by a budget is not a recall.
130    async fn record_memory_recall(
131        &self,
132        _fact_ids: &[i64],
133        _episode_ids: &[i64],
134    ) -> anyhow::Result<()> {
135        Ok(())
136    }
137
138    /// Supersede active automated facts that restate another active fact in
139    /// the same category, keeping the most authoritative copy. Returns how
140    /// many rows were folded. Soft: superseded rows remain as history.
141    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
142        Ok(0)
143    }
144
145    /// Retire automated facts that hold an older or farther-sourced value of
146    /// the attribute another active fact holds (numbers differ, whole facts
147    /// nearly identical, one visibility class): see
148    /// [`crate::sqlite::plan_numeric_conflicts`]. Owner-stated facts are
149    /// never retired by an automated one, and two owner-stated values are
150    /// left for the owner. Returns how many rows were retired.
151    async fn resolve_numeric_fact_conflicts(&self) -> anyhow::Result<usize> {
152        Ok(0)
153    }
154
155    /// Reversibly archive background-extracted facts nobody has used: never
156    /// recalled, not updated for `min_idle_days`, outside the identity
157    /// categories. Owner-stated and quoted facts are never touched.
158    /// `min_idle_days <= 0` archives nothing. Returns how many were archived.
159    async fn archive_unused_automated_facts(
160        &self,
161        _now: chrono::DateTime<chrono::Utc>,
162        _min_idle_days: i64,
163    ) -> anyhow::Result<u64> {
164        Ok(0)
165    }
166
167    /// Fold one active automated fact into another active fact that keeps
168    /// its knowledge (a reviewed duplicate). Refuses an owner-stated
169    /// `folded_id`, a `kept_id` from a farther source, and a fold that would
170    /// hide the knowledge from an audience that could see it. Returns
171    /// whether the fold happened; [`FactStore::unfold_fact`] reverses it.
172    async fn fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
173        Ok(false)
174    }
175
176    /// Fold one active flat fact into another active flat fact on an explicit
177    /// owner action (e.g. tapping Merge in the Memory UI). Allows merging any
178    /// two active positive flat facts the owner selected, while preserving
179    /// recall counts, fold tombstones, overlap cleanup, and live projections.
180    async fn owner_fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
181        Ok(false)
182    }
183
184    /// Promote an active flat fact to owner-confirmed (`user_stated`) without
185    /// changing its value, so inferred/derived memories leave "Needs review"
186    /// in one tap. Returns the updated fact if found.
187    async fn confirm_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
188        Ok(None)
189    }
190
191    /// Bring a folded fact back as active, when no active fact holds its key.
192    async fn unfold_fact(&self, _folded_id: i64) -> anyhow::Result<Option<Fact>> {
193        Ok(None)
194    }
195
196    /// Replace an automated fact's value (a merged wording of duplicates).
197    /// Refuses owner-stated facts: their words are the owner's.
198    async fn refine_automated_fact_value(
199        &self,
200        _fact_id: i64,
201        _new_value: &str,
202    ) -> anyhow::Result<Option<Fact>> {
203        Ok(None)
204    }
205
206    /// Record a verdict on two overlapping facts, bound to their current
207    /// contents.
208    async fn record_overlap_review(
209        &self,
210        _fact_a_id: i64,
211        _fact_b_id: i64,
212        _verdict: OverlapReviewVerdict,
213        _reviewer: &str,
214    ) -> anyhow::Result<()> {
215        Ok(())
216    }
217
218    /// The verdict on this pair, if one was given and neither fact has
219    /// changed since.
220    async fn has_valid_overlap_review(
221        &self,
222        _fact_a_id: i64,
223        _fact_b_id: i64,
224    ) -> anyhow::Result<Option<OverlapReviewVerdict>> {
225        Ok(None)
226    }
227
228    /// Whether a fact with this id exists and is not retired (it may be
229    /// archived).
230    async fn fact_exists(&self, fact_id: i64) -> anyhow::Result<bool> {
231        Ok(self.get_fact_by_id(fact_id).await?.is_some())
232    }
233
234    /// The fact with this id, if it is not retired (it may be archived).
235    async fn get_fact_by_id(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
236        Ok(None)
237    }
238
239    /// When the named background memory job last ran.
240    async fn job_last_run_at(
241        &self,
242        _job_name: &str,
243    ) -> anyhow::Result<Option<chrono::DateTime<chrono::Utc>>> {
244        Ok(None)
245    }
246
247    /// Record that the named background memory job ran at `at`.
248    async fn record_job_run_at(
249        &self,
250        _job_name: &str,
251        _at: chrono::DateTime<chrono::Utc>,
252    ) -> anyhow::Result<()> {
253        Ok(())
254    }
255
256    /// Upsert a fact with channel provenance and privacy level.
257    async fn upsert_fact(
258        &self,
259        category: &str,
260        key: &str,
261        value: &str,
262        source: &str,
263        channel_id: Option<&str>,
264        privacy: FactPrivacy,
265    ) -> anyhow::Result<()> {
266        self.upsert_fact_with_provenance(
267            category, key, value, source, channel_id, privacy, None, None,
268        )
269        .await
270    }
271
272    /// Upsert a fact with full provenance data.
273    #[allow(clippy::too_many_arguments)]
274    async fn upsert_fact_with_provenance(
275        &self,
276        category: &str,
277        key: &str,
278        value: &str,
279        source: &str,
280        channel_id: Option<&str>,
281        privacy: FactPrivacy,
282        first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
283        source_excerpt: Option<&str>,
284    ) -> anyhow::Result<()>;
285
286    /// Get all facts, optionally filtered by category.
287    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;
288
289    /// Get facts semantically relevant to a query, falling back to `get_facts` on error.
290    async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
291        // Default: return all facts (capped). Implementations can override with semantic filtering.
292        let mut facts = self.get_facts(None).await?;
293        facts.truncate(max);
294        Ok(facts)
295    }
296
297    /// Get facts for a specific channel context, respecting privacy levels.
298    ///
299    /// `requester_is_owner` controls the DM short-circuit: only the owner sees the
300    /// full unfiltered graph (incl. Private + other-channel facts) in a 1:1 DM. A
301    /// non-owner (an allowlisted Guest) gets the same privacy filtering as a group
302    /// channel — Global + same-channel facts only, never Private or other-channel —
303    /// so owner secrets can't leak into a guest's prompt context.
304    async fn get_relevant_facts_for_channel(
305        &self,
306        query: &str,
307        max: usize,
308        _channel_id: Option<&str>,
309        _visibility: ChannelVisibility,
310        _requester_is_owner: bool,
311    ) -> anyhow::Result<Vec<Fact>> {
312        self.get_relevant_facts(query, max).await
313    }
314
315    /// Update a fact's privacy level (e.g., channel → global after approval).
316    async fn update_fact_privacy(
317        &self,
318        _fact_id: i64,
319        _privacy: FactPrivacy,
320    ) -> anyhow::Result<()> {
321        Ok(())
322    }
323
324    /// Record where the active fact at this key came from.
325    async fn stamp_fact_provenance(
326        &self,
327        _category: &str,
328        _key: &str,
329        _source: &str,
330        _first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
331        _source_excerpt: Option<&str>,
332    ) -> anyhow::Result<()> {
333        Ok(())
334    }
335
336    /// Soft-delete a fact by superseding it.
337    async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
338        Ok(())
339    }
340
341    /// Soft-delete a fact by category and key. Returns true if a fact was found and deleted.
342    async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
343        Ok(false)
344    }
345
346    /// Edit an active fact's value in place as an explicit owner update.
347    /// Supports both positive flat fact ids and negative canonical ids where
348    /// editable (owner facts and aliases). Returns the updated fact if found.
349    async fn update_fact_value(&self, _fact_id: i64, _value: &str) -> anyhow::Result<Option<Fact>> {
350        Ok(None)
351    }
352
353    /// Reversibly archive an active fact so it leaves passive recall without
354    /// permanent deletion. Returns true if an active fact was archived.
355    async fn archive_fact(&self, _fact_id: i64) -> anyhow::Result<bool> {
356        Ok(false)
357    }
358
359    /// Restore a previously archived fact back to active memory.
360    async fn restore_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
361        Ok(None)
362    }
363
364    /// Archived facts available for restore, newest first.
365    async fn get_archived_facts(&self, _limit: usize) -> anyhow::Result<Vec<Fact>> {
366        Ok(Vec::new())
367    }
368
369    /// Automatically archive active facts whose typed `expires_at` has passed.
370    async fn archive_expired_facts(
371        &self,
372        _now: chrono::DateTime<chrono::Utc>,
373    ) -> anyhow::Result<u64> {
374        Ok(0)
375    }
376
377    /// Map of active fact id -> another active fact id that looks like a
378    /// conceptual duplicate/overlap (for UI review hints).
379    async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
380        Ok(std::collections::HashMap::new())
381    }
382
383    /// Get all active facts with provenance info for memory management display.
384    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
385        self.get_facts(None).await
386    }
387
388    /// Explicit fact search: one ranked list plus query-relevant related
389    /// facts. Ranking lives in [`crate::search`]; a store only gathers facts
390    /// and scores. The default returns an empty report so stores without
391    /// search keep compiling.
392    async fn search_facts(
393        &self,
394        _query: &str,
395        _limit: usize,
396        _config: &crate::search::FactSearchConfig,
397    ) -> anyhow::Result<crate::search::FactSearchReport> {
398        Ok(crate::search::FactSearchReport::default())
399    }
400
401    /// Persist a model-extracted semantic graph for an already-written fact.
402    /// Implementations must validate the graph and retain claim provenance.
403    async fn project_extracted_fact_graph(
404        &self,
405        _category: &str,
406        _key: &str,
407        _source_excerpt: &str,
408        _graph: &ExtractedMemoryGraph,
409    ) -> anyhow::Result<()> {
410        Ok(())
411    }
412
413    /// Refresh canonical claim/vector projections for the active fact at this key.
414    async fn refresh_fact_memory(&self, _category: &str, _key: &str) -> anyhow::Result<()> {
415        Ok(())
416    }
417
418    async fn memory_health_report(&self) -> anyhow::Result<MemoryHealthReport> {
419        Ok(MemoryHealthReport::default())
420    }
421
422    async fn repair_memory_projections(&self) -> anyhow::Result<MemoryHealthReport> {
423        self.memory_health_report().await
424    }
425}
426
427/// Episodic memory storage and retrieval.
428#[async_trait]
429pub trait EpisodeStore: Send + Sync {
430    /// Refresh derived canonical-memory projections for an episode. Stores that
431    /// do not maintain secondary indexes may keep the default no-op.
432    async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
433        Ok(())
434    }
435
436    /// Get episodes relevant to a query.
437    async fn get_relevant_episodes(
438        &self,
439        _query: &str,
440        _limit: usize,
441    ) -> anyhow::Result<Vec<Episode>> {
442        Ok(vec![])
443    }
444
445    /// Get episodes for a specific channel context.
446    async fn get_relevant_episodes_for_channel(
447        &self,
448        _query: &str,
449        _limit: usize,
450        _channel_id: Option<&str>,
451    ) -> anyhow::Result<Vec<Episode>> {
452        Ok(vec![])
453    }
454
455    /// Get episodes only from one canonical session (used by untrusted
456    /// internal/sub-agent origins).
457    async fn get_relevant_episodes_for_session(
458        &self,
459        _query: &str,
460        _limit: usize,
461        _session_id: &str,
462    ) -> anyhow::Result<Vec<Episode>> {
463        Ok(vec![])
464    }
465
466    /// Where the session's most recent episode stopped, if it has one.
467    async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
468        Ok(None)
469    }
470
471    /// `(session id, latest episode end time)` for every session with an
472    /// episode.
473    async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
474        Ok(vec![])
475    }
476
477    /// Record a session episode; returns its id. A store that keeps
478    /// episodes also embeds the summary for recall.
479    async fn record_session_episode(
480        &self,
481        _episode: &crate::episodes::SessionEpisode,
482    ) -> anyhow::Result<i64> {
483        anyhow::bail!("this store does not record session episodes")
484    }
485}
486
487/// People persistence (social graph).
488#[async_trait]
489pub trait PeopleStore: Send + Sync {
490    /// Create or update a person record. Returns the person ID.
491    async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
492        Ok(0)
493    }
494
495    /// Get a person by their database ID.
496    async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
497        Ok(None)
498    }
499
500    /// Look up a person by a platform-qualified sender ID (e.g., "slack:U123").
501    async fn get_person_by_platform_id(
502        &self,
503        _platform_id: &str,
504    ) -> anyhow::Result<Option<Person>> {
505        Ok(None)
506    }
507
508    /// Find a person by name or alias (case-insensitive).
509    async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
510        Ok(None)
511    }
512
513    /// Get all people.
514    async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
515        Ok(vec![])
516    }
517
518    /// Delete a person and all their facts (cascade).
519    async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
520        Ok(())
521    }
522
523    /// Link a platform identity to a person.
524    async fn link_platform_id(
525        &self,
526        _person_id: i64,
527        _platform_id: &str,
528        _display_name: &str,
529    ) -> anyhow::Result<()> {
530        Ok(())
531    }
532
533    /// Update interaction tracking for a person.
534    async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
535        Ok(())
536    }
537
538    /// Create or update a fact about a person.
539    async fn upsert_person_fact(
540        &self,
541        _person_id: i64,
542        _category: &str,
543        _key: &str,
544        _value: &str,
545        _source: &str,
546        _confidence: f32,
547    ) -> anyhow::Result<()> {
548        Ok(())
549    }
550
551    /// Get facts about a person, optionally filtered by category.
552    async fn get_person_facts(
553        &self,
554        _person_id: i64,
555        _category: Option<&str>,
556    ) -> anyhow::Result<Vec<PersonFact>> {
557        Ok(vec![])
558    }
559
560    /// Delete a person fact by ID.
561    async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
562        Ok(())
563    }
564
565    /// Confirm an auto-extracted person fact (set confidence to 1.0).
566    async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
567        Ok(())
568    }
569
570    /// Get people with upcoming dates (birthdays, important dates) within N days.
571    async fn get_people_with_upcoming_dates(
572        &self,
573        _within_days: i32,
574    ) -> anyhow::Result<Vec<(Person, PersonFact)>> {
575        Ok(vec![])
576    }
577
578    /// Delete stale auto-extracted person facts older than N days with confidence < 1.0.
579    async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
580        Ok(0)
581    }
582
583    /// Get people who haven't interacted in more than N days.
584    async fn get_people_needing_reconnect(
585        &self,
586        _inactive_days: u32,
587    ) -> anyhow::Result<Vec<Person>> {
588        Ok(vec![])
589    }
590}
591
592/// An entity to create or merge in the memory graph.
593#[derive(Debug, Clone)]
594pub struct GraphEntityUpsert {
595    pub entity_type: String,
596    pub canonical_name: String,
597    pub display_name: String,
598    pub aliases: Vec<String>,
599    pub channel_id: Option<String>,
600    pub privacy: FactPrivacy,
601}
602
603#[derive(Debug, Clone)]
604pub struct GraphEdgeUpsert {
605    pub source_entity_id: i64,
606    pub target_entity_id: i64,
607    pub relation: String,
608    pub source_claim_id: i64,
609    pub confidence: f32,
610    pub channel_id: Option<String>,
611    pub privacy: FactPrivacy,
612}
613
614#[derive(Debug, Clone)]
615pub struct GraphSearchScope {
616    pub channel_id: Option<String>,
617    pub visibility: ChannelVisibility,
618    pub requester_is_owner: bool,
619}
620
621#[derive(Debug, Clone)]
622pub struct GraphNeighbor {
623    pub entity_id: i64,
624    pub display_name: String,
625    pub relation: String,
626    pub depth: usize,
627}
628
629/// The memory graph: entities and the relations between them, each edge
630/// backed by the claim (fact) that asserts it, so retracting the claim
631/// invalidates the edge.
632#[async_trait]
633pub trait MemoryGraphStore: Send + Sync {
634    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64>;
635    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()>;
636    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()>;
637    async fn neighbors(
638        &self,
639        start_entity_id: i64,
640        max_depth: usize,
641        scope: &GraphSearchScope,
642    ) -> anyhow::Result<Vec<GraphNeighbor>>;
643}
644
645/// How unrecalled memory fades. Facts not recalled for `fact_idle_days`
646/// lose `1 / fact_decay_divisor` of their recall count per pass (at least
647/// one); episodes not recalled for `episode_idle_days` lose one; behavior
648/// patterns not seen for `pattern_idle_days` lose `pattern_step`
649/// confidence (down to 0.1). Background-extracted facts never recalled
650/// and untouched for `unused_automated_fact_days` are archived (0 keeps
651/// them).
652#[derive(Debug, Clone, Copy, PartialEq)]
653pub struct DecayPolicy {
654    pub fact_idle_days: i64,
655    pub fact_decay_divisor: i64,
656    pub episode_idle_days: i64,
657    pub pattern_idle_days: i64,
658    pub pattern_step: f32,
659    pub unused_automated_fact_days: i64,
660}
661
662impl Default for DecayPolicy {
663    fn default() -> Self {
664        Self {
665            fact_idle_days: 14,
666            fact_decay_divisor: 10,
667            episode_idle_days: 30,
668            pattern_idle_days: 30,
669            pattern_step: 0.05,
670            unused_automated_fact_days: 60,
671        }
672    }
673}
674
675/// Fading of unrecalled memory, applied by the store.
676#[async_trait]
677pub trait MemoryDecay: Send + Sync {
678    async fn decay(
679        &self,
680        policy: &DecayPolicy,
681        now: chrono::DateTime<chrono::Utc>,
682    ) -> anyhow::Result<()>;
683}
684
685/// One maintenance pass: archive expired facts, merge restated facts,
686/// retire superseded numeric values, archive unused automated facts, then
687/// let unrecalled memory fade, so decay sees one active row per piece of
688/// knowledge. Runs every step each call; a caller that must not repeat a
689/// daily pass (a restart) checks [`FactStore::job_last_run_at`] first.
690pub async fn decay_memory<S>(store: &S, policy: &DecayPolicy) -> anyhow::Result<()>
691where
692    S: FactStore + MemoryDecay + ?Sized,
693{
694    let now = chrono::Utc::now();
695    if let Err(error) = store.archive_expired_facts(now).await {
696        tracing::warn!(%error, "Failed to archive expired facts");
697    }
698    if let Err(error) = store.fold_restated_facts().await {
699        tracing::warn!(%error, "Failed to fold restated facts");
700    }
701    if let Err(error) = store.resolve_numeric_fact_conflicts().await {
702        tracing::warn!(%error, "Failed to resolve numeric fact conflicts");
703    }
704    if policy.unused_automated_fact_days > 0
705        && let Err(error) = store
706            .archive_unused_automated_facts(now, policy.unused_automated_fact_days)
707            .await
708    {
709        tracing::warn!(%error, "Failed to archive unused automated facts");
710    }
711    store.decay(policy, now).await
712}
713
714/// Every store behind the daemon-shaped memory contract, as one handle.
715pub trait MemoryStores:
716    FactStore + EpisodeStore + PeopleStore + crate::LearningStore + MemoryGraphStore + MemoryDecay
717{
718}
719
720impl<T> MemoryStores for T where
721    T: FactStore
722        + EpisodeStore
723        + PeopleStore
724        + crate::LearningStore
725        + MemoryGraphStore
726        + MemoryDecay
727{
728}