aidaemon-memory 0.24.0

Swappable long-term memory for aidaemon agents: the MemoryStore traits plus SQLite and embedding implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! The daemon-shaped memory storage contract: facts (with privacy, channel
//! provenance and the extraction graph), episodes, exact history and
//! people. A store implements the slices it supports; every method has a
//! conservative default.

use std::collections::HashSet;

use aidaemon_core::ChannelVisibility;
use async_trait::async_trait;

use crate::records::*;

/// Exact-history operations exposed to the search tool through a domain port.
#[async_trait]
pub trait HistorySearchStore: Send + Sync {
    async fn history_snapshot_max_event_id(&self) -> anyhow::Result<i64>;
    async fn history_coverage(&self) -> anyhow::Result<HistoryCoverage>;
    async fn repair_history_projection(
        &self,
        max_batches: usize,
    ) -> anyhow::Result<ProjectionStats>;
    async fn search_history(
        &self,
        query: &str,
        scope: &HistoryScope,
        limit: usize,
        semantic_sessions: &HashSet<String>,
    ) -> anyhow::Result<Vec<HistoryMessage>>;
    async fn history_context(
        &self,
        event_id: i64,
        radius: usize,
        scope: &HistoryScope,
    ) -> anyhow::Result<Vec<HistoryMessage>>;
    async fn history_event_for_message_id(
        &self,
        message_id: &str,
        scope: &HistoryScope,
    ) -> anyhow::Result<Option<i64>>;
    async fn history_turn(
        &self,
        turn_id: &str,
        scope: &HistoryScope,
    ) -> anyhow::Result<Vec<HistoryMessage>>;
    /// The tool calls of a turn the scope may read; empty when it may not.
    async fn history_turn_tool_activity(
        &self,
        turn_id: &str,
        scope: &HistoryScope,
    ) -> anyhow::Result<Vec<HistoryToolActivity>>;
    /// Which of the session's last `turns` prior user turns ran tools, oldest
    /// first. Carries no message or tool content.
    async fn history_recent_tool_turns(
        &self,
        session_id: &str,
        turns: usize,
    ) -> anyhow::Result<Vec<RecentToolTurn>>;
    async fn history_page(
        &self,
        anchor: i64,
        older: bool,
        scope: &HistoryScope,
        limit: usize,
    ) -> anyhow::Result<Vec<HistoryMessage>>;
    async fn history_task_bookends(
        &self,
        task_id: Option<&str>,
        session_id: &str,
        scope: &HistoryScope,
    ) -> anyhow::Result<TaskBookends>;
}

/// Layer-2 facts storage and retrieval (including privacy + channel provenance).
#[async_trait]
pub trait FactStore: Send + Sync {
    /// Reconcile an entity-aware personal-memory write atomically.
    async fn reconcile_personal_memory(
        &self,
        _write: &PersonalMemoryWrite,
        _source: &str,
        _source_excerpt: Option<&str>,
        _channel_id: Option<&str>,
        _privacy: FactPrivacy,
    ) -> anyhow::Result<PersonalMemoryWriteResult> {
        anyhow::bail!("structured personal memory is not supported by this store")
    }

    /// Compatibility projection of active canonical facts and relationships.
    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
        Ok(Vec::new())
    }

    /// Record that these facts and episodes were shown to a model. Recall
    /// counts drive Core Profile salience and decay, so only content that
    /// actually reached a prompt or a tool result may count; fetching a
    /// candidate that was then cut by a budget is not a recall.
    async fn record_memory_recall(
        &self,
        _fact_ids: &[i64],
        _episode_ids: &[i64],
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Supersede active automated facts that restate another active fact in
    /// the same category, keeping the most authoritative copy. Returns how
    /// many rows were folded. Soft: superseded rows remain as history.
    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
        Ok(0)
    }

    /// Upsert a fact with channel provenance and privacy level.
    async fn upsert_fact(
        &self,
        category: &str,
        key: &str,
        value: &str,
        source: &str,
        channel_id: Option<&str>,
        privacy: FactPrivacy,
    ) -> anyhow::Result<()> {
        self.upsert_fact_with_provenance(
            category, key, value, source, channel_id, privacy, None, None,
        )
        .await
    }

    /// Upsert a fact with full provenance data.
    #[allow(clippy::too_many_arguments)]
    async fn upsert_fact_with_provenance(
        &self,
        category: &str,
        key: &str,
        value: &str,
        source: &str,
        channel_id: Option<&str>,
        privacy: FactPrivacy,
        first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
        source_excerpt: Option<&str>,
    ) -> anyhow::Result<()>;

    /// Get all facts, optionally filtered by category.
    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;

    /// Get facts semantically relevant to a query, falling back to `get_facts` on error.
    async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
        // Default: return all facts (capped). Implementations can override with semantic filtering.
        let mut facts = self.get_facts(None).await?;
        facts.truncate(max);
        Ok(facts)
    }

    /// Get facts for a specific channel context, respecting privacy levels.
    ///
    /// `requester_is_owner` controls the DM short-circuit: only the owner sees the
    /// full unfiltered graph (incl. Private + other-channel facts) in a 1:1 DM. A
    /// non-owner (an allowlisted Guest) gets the same privacy filtering as a group
    /// channel — Global + same-channel facts only, never Private or other-channel —
    /// so owner secrets can't leak into a guest's prompt context.
    async fn get_relevant_facts_for_channel(
        &self,
        query: &str,
        max: usize,
        _channel_id: Option<&str>,
        _visibility: ChannelVisibility,
        _requester_is_owner: bool,
    ) -> anyhow::Result<Vec<Fact>> {
        self.get_relevant_facts(query, max).await
    }

    /// Update a fact's privacy level (e.g., channel → global after approval).
    async fn update_fact_privacy(
        &self,
        _fact_id: i64,
        _privacy: FactPrivacy,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Record where the active fact at this key came from.
    async fn stamp_fact_provenance(
        &self,
        _category: &str,
        _key: &str,
        _source: &str,
        _first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
        _source_excerpt: Option<&str>,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Soft-delete a fact by superseding it.
    async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Soft-delete a fact by category and key. Returns true if a fact was found and deleted.
    async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Get all active facts with provenance info for memory management display.
    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
        self.get_facts(None).await
    }

    /// Explicit fact search: one ranked list plus query-relevant related
    /// facts. Ranking lives in [`crate::search`]; a store only gathers facts
    /// and scores. The default returns an empty report so stores without
    /// search keep compiling.
    async fn search_facts(
        &self,
        _query: &str,
        _limit: usize,
        _config: &crate::search::FactSearchConfig,
    ) -> anyhow::Result<crate::search::FactSearchReport> {
        Ok(crate::search::FactSearchReport::default())
    }

    /// Persist a model-extracted semantic graph for an already-written fact.
    /// Implementations must validate the graph and retain claim provenance.
    async fn project_extracted_fact_graph(
        &self,
        _category: &str,
        _key: &str,
        _source_excerpt: &str,
        _graph: &ExtractedMemoryGraph,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Refresh canonical claim/vector projections for the active fact at this key.
    async fn refresh_fact_memory(&self, _category: &str, _key: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn memory_health_report(&self) -> anyhow::Result<MemoryHealthReport> {
        Ok(MemoryHealthReport::default())
    }

    async fn repair_memory_projections(&self) -> anyhow::Result<MemoryHealthReport> {
        self.memory_health_report().await
    }
}

/// Episodic memory storage and retrieval.
#[async_trait]
pub trait EpisodeStore: Send + Sync {
    /// Refresh derived canonical-memory projections for an episode. Stores that
    /// do not maintain secondary indexes may keep the default no-op.
    async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get episodes relevant to a query.
    async fn get_relevant_episodes(
        &self,
        _query: &str,
        _limit: usize,
    ) -> anyhow::Result<Vec<Episode>> {
        Ok(vec![])
    }

    /// Get episodes for a specific channel context.
    async fn get_relevant_episodes_for_channel(
        &self,
        _query: &str,
        _limit: usize,
        _channel_id: Option<&str>,
    ) -> anyhow::Result<Vec<Episode>> {
        Ok(vec![])
    }

    /// Get episodes only from one canonical session (used by untrusted
    /// internal/sub-agent origins).
    async fn get_relevant_episodes_for_session(
        &self,
        _query: &str,
        _limit: usize,
        _session_id: &str,
    ) -> anyhow::Result<Vec<Episode>> {
        Ok(vec![])
    }

    /// Where the session's most recent episode stopped, if it has one.
    async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
        Ok(None)
    }

    /// `(session id, latest episode end time)` for every session with an
    /// episode.
    async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(vec![])
    }

    /// Record a session episode; returns its id. A store that keeps
    /// episodes also embeds the summary for recall.
    async fn record_session_episode(
        &self,
        _episode: &crate::episodes::SessionEpisode,
    ) -> anyhow::Result<i64> {
        anyhow::bail!("this store does not record session episodes")
    }
}

/// People persistence (social graph).
#[async_trait]
pub trait PeopleStore: Send + Sync {
    /// Create or update a person record. Returns the person ID.
    async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
        Ok(0)
    }

    /// Get a person by their database ID.
    async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
        Ok(None)
    }

    /// Look up a person by a platform-qualified sender ID (e.g., "slack:U123").
    async fn get_person_by_platform_id(
        &self,
        _platform_id: &str,
    ) -> anyhow::Result<Option<Person>> {
        Ok(None)
    }

    /// Find a person by name or alias (case-insensitive).
    async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
        Ok(None)
    }

    /// Get all people.
    async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
        Ok(vec![])
    }

    /// Delete a person and all their facts (cascade).
    async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Link a platform identity to a person.
    async fn link_platform_id(
        &self,
        _person_id: i64,
        _platform_id: &str,
        _display_name: &str,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Update interaction tracking for a person.
    async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Create or update a fact about a person.
    async fn upsert_person_fact(
        &self,
        _person_id: i64,
        _category: &str,
        _key: &str,
        _value: &str,
        _source: &str,
        _confidence: f32,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get facts about a person, optionally filtered by category.
    async fn get_person_facts(
        &self,
        _person_id: i64,
        _category: Option<&str>,
    ) -> anyhow::Result<Vec<PersonFact>> {
        Ok(vec![])
    }

    /// Delete a person fact by ID.
    async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Confirm an auto-extracted person fact (set confidence to 1.0).
    async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get people with upcoming dates (birthdays, important dates) within N days.
    async fn get_people_with_upcoming_dates(
        &self,
        _within_days: i32,
    ) -> anyhow::Result<Vec<(Person, PersonFact)>> {
        Ok(vec![])
    }

    /// Delete stale auto-extracted person facts older than N days with confidence < 1.0.
    async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
        Ok(0)
    }

    /// Get people who haven't interacted in more than N days.
    async fn get_people_needing_reconnect(
        &self,
        _inactive_days: u32,
    ) -> anyhow::Result<Vec<Person>> {
        Ok(vec![])
    }
}

/// An entity to create or merge in the memory graph.
#[derive(Debug, Clone)]
pub struct GraphEntityUpsert {
    pub entity_type: String,
    pub canonical_name: String,
    pub display_name: String,
    pub aliases: Vec<String>,
    pub channel_id: Option<String>,
    pub privacy: FactPrivacy,
}

#[derive(Debug, Clone)]
pub struct GraphEdgeUpsert {
    pub source_entity_id: i64,
    pub target_entity_id: i64,
    pub relation: String,
    pub source_claim_id: i64,
    pub confidence: f32,
    pub channel_id: Option<String>,
    pub privacy: FactPrivacy,
}

#[derive(Debug, Clone)]
pub struct GraphSearchScope {
    pub channel_id: Option<String>,
    pub visibility: ChannelVisibility,
    pub requester_is_owner: bool,
}

#[derive(Debug, Clone)]
pub struct GraphNeighbor {
    pub entity_id: i64,
    pub display_name: String,
    pub relation: String,
    pub depth: usize,
}

/// The memory graph: entities and the relations between them, each edge
/// backed by the claim (fact) that asserts it, so retracting the claim
/// invalidates the edge.
#[async_trait]
pub trait MemoryGraphStore: Send + Sync {
    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64>;
    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()>;
    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()>;
    async fn neighbors(
        &self,
        start_entity_id: i64,
        max_depth: usize,
        scope: &GraphSearchScope,
    ) -> anyhow::Result<Vec<GraphNeighbor>>;
}

/// How unrecalled memory fades. Facts not recalled for `fact_idle_days`
/// lose `1 / fact_decay_divisor` of their recall count per pass (at least
/// one); episodes not recalled for `episode_idle_days` lose one; behavior
/// patterns not seen for `pattern_idle_days` lose `pattern_step`
/// confidence (down to 0.1).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecayPolicy {
    pub fact_idle_days: i64,
    pub fact_decay_divisor: i64,
    pub episode_idle_days: i64,
    pub pattern_idle_days: i64,
    pub pattern_step: f32,
}

impl Default for DecayPolicy {
    fn default() -> Self {
        Self {
            fact_idle_days: 14,
            fact_decay_divisor: 10,
            episode_idle_days: 30,
            pattern_idle_days: 30,
            pattern_step: 0.05,
        }
    }
}

/// Fading of unrecalled memory, applied by the store.
#[async_trait]
pub trait MemoryDecay: Send + Sync {
    async fn decay(
        &self,
        policy: &DecayPolicy,
        now: chrono::DateTime<chrono::Utc>,
    ) -> anyhow::Result<()>;
}

/// One maintenance pass: merge restated facts, then let unrecalled memory
/// fade, so decay sees one row per piece of knowledge.
pub async fn decay_memory<S>(store: &S, policy: &DecayPolicy) -> anyhow::Result<()>
where
    S: FactStore + MemoryDecay + ?Sized,
{
    if let Err(error) = store.fold_restated_facts().await {
        tracing::warn!(%error, "Failed to fold restated facts");
    }
    store.decay(policy, chrono::Utc::now()).await
}

/// Every store behind the daemon-shaped memory contract, as one handle.
pub trait MemoryStores:
    FactStore + EpisodeStore + PeopleStore + crate::LearningStore + MemoryGraphStore + MemoryDecay
{
}

impl<T> MemoryStores for T where
    T: FactStore
        + EpisodeStore
        + PeopleStore
        + crate::LearningStore
        + MemoryGraphStore
        + MemoryDecay
{
}