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 get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
204 self.get_facts(None).await
205 }
206
207 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 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 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#[async_trait]
248pub trait EpisodeStore: Send + Sync {
249 async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
252 Ok(())
253 }
254
255 async fn get_relevant_episodes(
257 &self,
258 _query: &str,
259 _limit: usize,
260 ) -> anyhow::Result<Vec<Episode>> {
261 Ok(vec![])
262 }
263
264 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 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 async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
287 Ok(None)
288 }
289
290 async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
293 Ok(vec![])
294 }
295
296 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#[async_trait]
308pub trait PeopleStore: Send + Sync {
309 async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
311 Ok(0)
312 }
313
314 async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
316 Ok(None)
317 }
318
319 async fn get_person_by_platform_id(
321 &self,
322 _platform_id: &str,
323 ) -> anyhow::Result<Option<Person>> {
324 Ok(None)
325 }
326
327 async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
329 Ok(None)
330 }
331
332 async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
334 Ok(vec![])
335 }
336
337 async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
339 Ok(())
340 }
341
342 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 async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
354 Ok(())
355 }
356
357 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 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 async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
381 Ok(())
382 }
383
384 async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
386 Ok(())
387 }
388
389 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 async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
399 Ok(0)
400 }
401
402 async fn get_people_needing_reconnect(
404 &self,
405 _inactive_days: u32,
406 ) -> anyhow::Result<Vec<Person>> {
407 Ok(vec![])
408 }
409}
410
411#[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#[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#[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#[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
500pub 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
512pub 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}