1use std::collections::HashSet;
7
8use aidaemon_core::ChannelVisibility;
9use async_trait::async_trait;
10
11use crate::records::*;
12
13#[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 async fn history_turn_tool_activity(
47 &self,
48 turn_id: &str,
49 scope: &HistoryScope,
50 ) -> anyhow::Result<Vec<HistoryToolActivity>>;
51 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum OverlapReviewVerdict {
77 Distinct,
79 Conflict,
81 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#[async_trait]
108pub trait FactStore: Send + Sync {
109 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 async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
123 Ok(Vec::new())
124 }
125
126 async fn record_memory_recall(
131 &self,
132 _fact_ids: &[i64],
133 _episode_ids: &[i64],
134 ) -> anyhow::Result<()> {
135 Ok(())
136 }
137
138 async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
142 Ok(0)
143 }
144
145 async fn resolve_numeric_fact_conflicts(&self) -> anyhow::Result<usize> {
152 Ok(0)
153 }
154
155 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 async fn fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
173 Ok(false)
174 }
175
176 async fn owner_fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
181 Ok(false)
182 }
183
184 async fn confirm_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
188 Ok(None)
189 }
190
191 async fn unfold_fact(&self, _folded_id: i64) -> anyhow::Result<Option<Fact>> {
193 Ok(None)
194 }
195
196 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 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 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 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 async fn get_fact_by_id(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
236 Ok(None)
237 }
238
239 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 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 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 #[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 async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;
288
289 async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
291 let mut facts = self.get_facts(None).await?;
293 facts.truncate(max);
294 Ok(facts)
295 }
296
297 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 async fn update_fact_privacy(
317 &self,
318 _fact_id: i64,
319 _privacy: FactPrivacy,
320 ) -> anyhow::Result<()> {
321 Ok(())
322 }
323
324 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 async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
338 Ok(())
339 }
340
341 async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
343 Ok(false)
344 }
345
346 async fn update_fact_value(&self, _fact_id: i64, _value: &str) -> anyhow::Result<Option<Fact>> {
350 Ok(None)
351 }
352
353 async fn archive_fact(&self, _fact_id: i64) -> anyhow::Result<bool> {
356 Ok(false)
357 }
358
359 async fn restore_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
361 Ok(None)
362 }
363
364 async fn get_archived_facts(&self, _limit: usize) -> anyhow::Result<Vec<Fact>> {
366 Ok(Vec::new())
367 }
368
369 async fn archive_expired_facts(
371 &self,
372 _now: chrono::DateTime<chrono::Utc>,
373 ) -> anyhow::Result<u64> {
374 Ok(0)
375 }
376
377 async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
380 Ok(std::collections::HashMap::new())
381 }
382
383 async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
385 self.get_facts(None).await
386 }
387
388 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 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 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#[async_trait]
429pub trait EpisodeStore: Send + Sync {
430 async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
433 Ok(())
434 }
435
436 async fn get_relevant_episodes(
438 &self,
439 _query: &str,
440 _limit: usize,
441 ) -> anyhow::Result<Vec<Episode>> {
442 Ok(vec![])
443 }
444
445 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 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 async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
468 Ok(None)
469 }
470
471 async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
474 Ok(vec![])
475 }
476
477 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#[async_trait]
489pub trait PeopleStore: Send + Sync {
490 async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
492 Ok(0)
493 }
494
495 async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
497 Ok(None)
498 }
499
500 async fn get_person_by_platform_id(
502 &self,
503 _platform_id: &str,
504 ) -> anyhow::Result<Option<Person>> {
505 Ok(None)
506 }
507
508 async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
510 Ok(None)
511 }
512
513 async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
515 Ok(vec![])
516 }
517
518 async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
520 Ok(())
521 }
522
523 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 async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
535 Ok(())
536 }
537
538 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 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 async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
562 Ok(())
563 }
564
565 async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
567 Ok(())
568 }
569
570 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 async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
580 Ok(0)
581 }
582
583 async fn get_people_needing_reconnect(
585 &self,
586 _inactive_days: u32,
587 ) -> anyhow::Result<Vec<Person>> {
588 Ok(vec![])
589 }
590}
591
592#[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#[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#[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#[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
685pub 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
714pub 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}