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#[async_trait]
75pub trait FactStore: Send + Sync {
76 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 async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
90 Ok(Vec::new())
91 }
92
93 async fn record_memory_recall(
98 &self,
99 _fact_ids: &[i64],
100 _episode_ids: &[i64],
101 ) -> anyhow::Result<()> {
102 Ok(())
103 }
104
105 async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
109 Ok(0)
110 }
111
112 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 #[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 async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;
144
145 async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
147 let mut facts = self.get_facts(None).await?;
149 facts.truncate(max);
150 Ok(facts)
151 }
152
153 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 async fn update_fact_privacy(
173 &self,
174 _fact_id: i64,
175 _privacy: FactPrivacy,
176 ) -> anyhow::Result<()> {
177 Ok(())
178 }
179
180 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 async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
194 Ok(())
195 }
196
197 async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
199 Ok(false)
200 }
201
202 async fn update_fact_value(&self, _fact_id: i64, _value: &str) -> anyhow::Result<Option<Fact>> {
206 Ok(None)
207 }
208
209 async fn archive_fact(&self, _fact_id: i64) -> anyhow::Result<bool> {
212 Ok(false)
213 }
214
215 async fn restore_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
217 Ok(None)
218 }
219
220 async fn get_archived_facts(&self, _limit: usize) -> anyhow::Result<Vec<Fact>> {
222 Ok(Vec::new())
223 }
224
225 async fn archive_expired_facts(
227 &self,
228 _now: chrono::DateTime<chrono::Utc>,
229 ) -> anyhow::Result<u64> {
230 Ok(0)
231 }
232
233 async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
236 Ok(std::collections::HashMap::new())
237 }
238
239 async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
241 self.get_facts(None).await
242 }
243
244 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 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 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#[async_trait]
285pub trait EpisodeStore: Send + Sync {
286 async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
289 Ok(())
290 }
291
292 async fn get_relevant_episodes(
294 &self,
295 _query: &str,
296 _limit: usize,
297 ) -> anyhow::Result<Vec<Episode>> {
298 Ok(vec![])
299 }
300
301 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 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 async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
324 Ok(None)
325 }
326
327 async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
330 Ok(vec![])
331 }
332
333 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#[async_trait]
345pub trait PeopleStore: Send + Sync {
346 async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
348 Ok(0)
349 }
350
351 async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
353 Ok(None)
354 }
355
356 async fn get_person_by_platform_id(
358 &self,
359 _platform_id: &str,
360 ) -> anyhow::Result<Option<Person>> {
361 Ok(None)
362 }
363
364 async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
366 Ok(None)
367 }
368
369 async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
371 Ok(vec![])
372 }
373
374 async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
376 Ok(())
377 }
378
379 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 async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
391 Ok(())
392 }
393
394 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 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 async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
418 Ok(())
419 }
420
421 async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
423 Ok(())
424 }
425
426 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 async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
436 Ok(0)
437 }
438
439 async fn get_people_needing_reconnect(
441 &self,
442 _inactive_days: u32,
443 ) -> anyhow::Result<Vec<Person>> {
444 Ok(vec![])
445 }
446}
447
448#[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#[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#[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#[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
537pub 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
554pub 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}