Skip to main content

aidaemon_policies/
memory.rs

1//! Memory as pluggable seams: a whole [`MemorySystem`] contributes hooks and
2//! tools to each turn, and [`MemoryInjection`] is a `before_model` hook over
3//! a [`Recall`] backend.
4
5use std::collections::{HashMap, HashSet};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex};
8
9use aidaemon_core::{Hook, HookContext, Message, ModelRequest, Service, Tool};
10use async_trait::async_trait;
11
12use crate::{insert_after_system, last_user_message_index};
13
14/// A whole long-term memory system, replaceable as one unit.
15///
16/// The host (an app built on the SDK) decides who may see what: it resolves
17/// the turn's [`MemoryTurn::scope`] and permissions from its own notion of
18/// users and channels. The memory system only decides how to remember and
19/// recall within that scope, by returning the hooks and tools it wants on
20/// the turn. `aidaemon-memory` is one implementation; any other backend
21/// (a vector database, a hosted memory service, an external memory server)
22/// implements this trait in its own crate.
23#[async_trait]
24pub trait MemorySystem: Send + Sync {
25    /// The hooks and tools this memory system adds to `turn`.
26    async fn turn(&self, turn: &MemoryTurn) -> MemoryParts;
27
28    /// Standing instructions for the model on how this memory system works.
29    /// Memory systems differ, so the host says nothing about remembering
30    /// except what this returns. It should not change between turns.
31    fn guidance(&self) -> Option<String> {
32        None
33    }
34
35    /// Learn from the host's retained conversations, oldest first, in
36    /// batches. This is how a system starts out knowing what a previous one
37    /// knew: memory systems share no record format, but any of them can read
38    /// a conversation. The host resumes where the last batch ended.
39    async fn absorb_history(&self, _messages: &[PastMessage]) -> Result<HistoryIntake, String> {
40        Ok(HistoryIntake::NotSupported)
41    }
42
43    /// The background work this memory system needs (consolidation, expiry,
44    /// indexing). The host runs these in place of its own memory jobs.
45    fn services(&self) -> Vec<Arc<dyn Service>> {
46        Vec::new()
47    }
48}
49
50/// Who said a [`PastMessage`].
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PastRole {
53    User,
54    Assistant,
55}
56
57/// One message from the host's retained conversations.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PastMessage {
60    pub session_id: String,
61    /// The memory it belongs to, as the host would scope a turn today.
62    pub scope: String,
63    pub role: PastRole,
64    pub text: String,
65    /// RFC 3339.
66    pub at: String,
67}
68
69/// What became of a batch given to [`MemorySystem::absorb_history`].
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum HistoryIntake {
72    Absorbed,
73    /// This system does not learn from history. The host stops offering.
74    NotSupported,
75}
76
77/// What a [`MemorySystem`] may do on one turn, as the host decided it.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct MemoryTurn {
80    /// The conversation the turn belongs to.
81    pub session_id: String,
82    /// The memory the turn reads and writes, shared by every session the
83    /// host maps to it (for example one scope for the owner's direct
84    /// messages, and one per group conversation).
85    pub scope: String,
86    /// The turn may read memory (recall, injection).
87    pub read: bool,
88    /// The turn may write memory.
89    pub write: bool,
90    /// Writes come only from explicit tool calls: no background learning
91    /// from the transcript (worker and child sessions).
92    pub explicit_writes_only: bool,
93    /// Whether the turn may be learned from. Read it when about to learn
94    /// (at run end, in background work), not when the turn starts: the
95    /// user or the model may opt the turn out while it runs.
96    pub learning: TurnLearning,
97    /// The project the turn works in, when the host placed it in one and
98    /// the turn may keep project memory (the owner's own private turns). A
99    /// memory system keeps what the turn learns about the project apart
100    /// from the scope's memory, keyed by [`ProjectRef::id`]. `None` on every
101    /// other turn.
102    ///
103    /// [`ProjectRef::id`]: aidaemon_core::ProjectRef::id
104    pub project: Option<aidaemon_core::ProjectRef>,
105    /// What the host knows about the turn beyond the above, for a memory
106    /// system built to read it (see [`HostTurn`]). Empty by default.
107    pub host: HostTurn,
108}
109
110impl MemoryTurn {
111    /// The owner's turn in `session_id`: the `"owner"` memory, read and
112    /// written, learned from at run end.
113    pub fn owner(session_id: impl Into<String>) -> Self {
114        Self {
115            session_id: session_id.into(),
116            scope: "owner".to_string(),
117            read: true,
118            write: true,
119            explicit_writes_only: false,
120            learning: Default::default(),
121            project: None,
122            host: Default::default(),
123        }
124    }
125}
126
127/// Host-specific facts about a turn, for a memory system that knows its
128/// host's types (the turn's full audience, a diagnostics sink). A system
129/// that does not ask for them works from the [`MemoryTurn`] fields alone.
130/// Not compared: two turns with the same fields are equal whatever they
131/// carry here.
132#[derive(Clone, Default)]
133pub struct HostTurn(Option<Arc<dyn std::any::Any + Send + Sync>>);
134
135impl HostTurn {
136    pub fn new<T: std::any::Any + Send + Sync>(facts: T) -> Self {
137        Self(Some(Arc::new(facts)))
138    }
139
140    /// The facts, if the host gave a `T`.
141    pub fn get<T: std::any::Any>(&self) -> Option<&T> {
142        self.0.as_deref().and_then(|facts| facts.downcast_ref())
143    }
144}
145
146impl std::fmt::Debug for HostTurn {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.write_str(if self.0.is_some() {
149            "HostTurn(..)"
150        } else {
151            "HostTurn(none)"
152        })
153    }
154}
155
156impl PartialEq for HostTurn {
157    fn eq(&self, _other: &Self) -> bool {
158        true
159    }
160}
161
162impl Eq for HostTurn {}
163
164/// Whether a turn may be learned from.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
166pub enum Learning {
167    #[default]
168    Allowed,
169    /// "Don't remember this": nothing from the turn may become long-term
170    /// memory (facts, episodes, procedures, people, skills), now or later.
171    /// Recall is unaffected, and so are writes the turn makes on purpose
172    /// with a memory tool.
173    OptedOut,
174}
175
176/// A turn's [`Learning`], shared by the host and the memory system for the
177/// whole turn. The host opts the turn out (an explicit command before the
178/// message, or the model's call to the host's opt-out tool); a memory system
179/// checks [`TurnLearning::allowed`] before it learns anything from the turn.
180/// Opting out cannot be undone within the turn.
181#[derive(Clone, Default)]
182pub struct TurnLearning(Arc<AtomicBool>);
183
184impl TurnLearning {
185    pub fn new(learning: Learning) -> Self {
186        let handle = Self::default();
187        if learning == Learning::OptedOut {
188            handle.opt_out();
189        }
190        handle
191    }
192
193    pub fn get(&self) -> Learning {
194        if self.0.load(Ordering::Acquire) {
195            Learning::OptedOut
196        } else {
197            Learning::Allowed
198        }
199    }
200
201    pub fn allowed(&self) -> bool {
202        self.get() == Learning::Allowed
203    }
204
205    /// Opt the turn out. Returns whether this call changed it.
206    pub fn opt_out(&self) -> bool {
207        !self.0.swap(true, Ordering::AcqRel)
208    }
209}
210
211impl std::fmt::Debug for TurnLearning {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        f.debug_tuple("TurnLearning").field(&self.get()).finish()
214    }
215}
216
217/// Compares the current values.
218impl PartialEq for TurnLearning {
219    fn eq(&self, other: &Self) -> bool {
220        self.get() == other.get()
221    }
222}
223
224impl Eq for TurnLearning {}
225
226/// What a [`MemorySystem`] adds to one turn.
227#[derive(Default)]
228pub struct MemoryParts {
229    pub hooks: Vec<Arc<dyn Hook>>,
230    pub tools: Vec<Arc<dyn Tool>>,
231}
232
233impl std::fmt::Debug for MemoryParts {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct("MemoryParts")
236            .field("hooks", &self.hooks.len())
237            .field(
238                "tools",
239                &self
240                    .tools
241                    .iter()
242                    .map(|tool| tool.spec().name)
243                    .collect::<Vec<_>>(),
244            )
245            .finish()
246    }
247}
248
249/// A memory backend: return up to `limit` snippets relevant to `query`.
250#[async_trait]
251pub trait Recall: Send + Sync {
252    async fn recall(&self, session_id: &str, query: &str, limit: usize) -> Vec<String>;
253
254    /// The system note [`MemoryInjection`] adds for `query`, or `None` for no
255    /// note. The default lists the [`Recall::recall`] snippets under a
256    /// "may be outdated" banner; a backend with its own layout (sections,
257    /// authoritative profile facts) overrides this.
258    async fn render(&self, session_id: &str, query: &str, limit: usize) -> Option<String> {
259        let snippets = self.recall(session_id, query, limit).await;
260        if snippets.is_empty() {
261            return None;
262        }
263        let mut note = String::from(
264            "[Recalled memory — background that may be outdated or irrelevant. Use it only if it \
265             helps with the current request, and prefer what the user says now.]",
266        );
267        for snippet in snippets.iter().take(limit) {
268            note.push_str("\n- ");
269            note.push_str(snippet.trim());
270        }
271        Some(note)
272    }
273}
274
275/// Injects recalled snippets for the latest user message as a system note
276/// placed after the leading system messages. Request only: the stored
277/// transcript never contains the note.
278///
279/// The query is the latest message the *user* wrote (harness feedback is
280/// skipped). Results are cached per session and query, so the backend is
281/// asked once per user message, not once per turn.
282pub struct MemoryInjection<R: Recall> {
283    recall: R,
284    limit: usize,
285    cache: Mutex<HashMap<String, (String, Option<String>)>>,
286}
287
288impl<R: Recall> MemoryInjection<R> {
289    pub fn new(recall: R) -> Self {
290        Self {
291            recall,
292            limit: 5,
293            cache: Mutex::new(HashMap::new()),
294        }
295    }
296
297    pub fn limit(mut self, limit: usize) -> Self {
298        self.limit = limit;
299        self
300    }
301
302    pub fn backend(&self) -> &R {
303        &self.recall
304    }
305
306    async fn note(&self, session_id: &str, query: &str) -> Option<String> {
307        if let Some((cached_query, note)) = self
308            .cache
309            .lock()
310            .ok()
311            .and_then(|c| c.get(session_id).cloned())
312            && cached_query == query
313        {
314            return note;
315        }
316        let note = self.recall.render(session_id, query, self.limit).await;
317        if let Ok(mut cache) = self.cache.lock() {
318            cache.insert(session_id.to_string(), (query.to_string(), note.clone()));
319        }
320        note
321    }
322}
323
324#[async_trait]
325impl<R: Recall> Hook for MemoryInjection<R> {
326    async fn before_model(&self, ctx: &HookContext<'_>, request: &mut ModelRequest) {
327        let Some(index) = last_user_message_index(ctx.messages) else {
328            return;
329        };
330        let query = ctx.messages[index].content.clone();
331        if let Some(note) = self.note(ctx.session_id, &query).await {
332            insert_after_system(&mut request.messages, Message::hook_note(note));
333        }
334    }
335}
336
337/// A tiny in-process [`Recall`] with word-overlap scoring, for tests and
338/// examples. Entries are per session, plus global entries visible to all.
339#[derive(Default)]
340pub struct InMemoryRecall {
341    entries: Mutex<Vec<(Option<String>, String)>>,
342    queries: Mutex<u32>,
343}
344
345impl InMemoryRecall {
346    pub fn new() -> Self {
347        Self::default()
348    }
349
350    /// Remember `text` for one session.
351    pub fn remember(&self, session_id: &str, text: impl Into<String>) {
352        if let Ok(mut e) = self.entries.lock() {
353            e.push((Some(session_id.to_string()), text.into()));
354        }
355    }
356
357    /// Remember `text` for every session.
358    pub fn remember_global(&self, text: impl Into<String>) {
359        if let Ok(mut e) = self.entries.lock() {
360            e.push((None, text.into()));
361        }
362    }
363
364    /// How many times `recall` was called.
365    pub fn query_count(&self) -> u32 {
366        self.queries.lock().map(|q| *q).unwrap_or(0)
367    }
368}
369
370fn words(text: &str) -> HashSet<String> {
371    text.split(|c: char| !c.is_alphanumeric())
372        .filter(|w| w.chars().count() >= 3)
373        .map(str::to_lowercase)
374        .collect()
375}
376
377#[async_trait]
378impl Recall for InMemoryRecall {
379    async fn recall(&self, session_id: &str, query: &str, limit: usize) -> Vec<String> {
380        if let Ok(mut q) = self.queries.lock() {
381            *q += 1;
382        }
383        let query_words = words(query);
384        let entries = self.entries.lock().map(|e| e.clone()).unwrap_or_default();
385        let mut scored: Vec<(usize, usize, String)> = entries
386            .into_iter()
387            .enumerate()
388            .filter(|(_, (session, _))| session.as_deref().is_none_or(|s| s == session_id))
389            .map(|(i, (_, text))| (words(&text).intersection(&query_words).count(), i, text))
390            .filter(|(score, _, _)| *score > 0)
391            .collect();
392        scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
393        scored.into_iter().take(limit).map(|(_, _, t)| t).collect()
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn opting_out_is_shared_by_every_holder_of_the_turn() {
403        let host = TurnLearning::default();
404        let system = host.clone();
405        assert_eq!(system.get(), Learning::Allowed);
406        assert!(host.opt_out());
407        assert!(!host.opt_out(), "already opted out");
408        assert_eq!(system.get(), Learning::OptedOut);
409        assert!(!system.allowed());
410        assert!(!TurnLearning::new(Learning::OptedOut).allowed());
411    }
412
413    #[tokio::test]
414    async fn word_overlap_ranks_and_scopes_by_session() {
415        let recall = InMemoryRecall::new();
416        recall.remember(
417            "telegram:synthetic-user-1",
418            "Alice Rivera prefers window seats",
419        );
420        recall.remember(
421            "telegram:synthetic-user-1",
422            "Alice Rivera's daughters are Mia and Zoe",
423        );
424        recall.remember(
425            "telegram:synthetic-user-2",
426            "Jordan Lee prefers aisle seats",
427        );
428        recall.remember_global("Acme Corp travel policy requires economy seats");
429
430        let got = recall
431            .recall("telegram:synthetic-user-1", "Book seats for Alice", 5)
432            .await;
433        assert_eq!(got[0], "Alice Rivera prefers window seats");
434        assert!(got.contains(&"Acme Corp travel policy requires economy seats".to_string()));
435        assert!(!got.iter().any(|s| s.contains("Jordan")));
436        assert!(
437            recall
438                .recall("telegram:synthetic-user-1", "zzz", 5)
439                .await
440                .is_empty()
441        );
442    }
443}