Skip to main content

base/interface/
memory_contracts.rs

1//! Where memories live, how they are found, and who decides what to keep.
2//!
3//! Memory was one concrete struct with a fixed directory layout, one search
4//! that was a substring scan, and one retriever that was an LLM call written
5//! inline. Every part of that is a reasonable default and none of it was a
6//! choice: a host with memories in a database, a deployment that wants a
7//! vector index, a project whose recall should be deterministic in tests —
8//! none had anywhere to plug in.
9//!
10//! Four seams, matching the four things that are actually separable:
11//!
12//! * [`MemoryStorage`] — where the memories are.
13//! * [`MemoryRetriever`] — which ones this turn should see.
14//! * [`RetrievalHook`] — a look at the question before, and the answer after.
15//! * [`ExtractionPolicy`] — what the model is told about writing memories
16//!   down, which is the whole of the current extraction strategy.
17//!
18//! # The defaults
19//!
20//! The `memory` crate's `MemoryStore` implements the storage trait over the
21//! session's memory directories, and its `LlmRetriever` is an LLM selection
22//! call. A session that registers nothing gets those two.
23
24use std::collections::HashSet;
25
26use async_trait::async_trait;
27
28use crate::memory::{DurableMemory, MemoryError};
29
30/// Where durable memories are kept.
31///
32/// Deliberately narrow: the operations the engine performs, not the ones the
33/// file-backed implementation happens to expose. A backend that is not a
34/// directory should not have to grow a concept of an index file to satisfy
35/// this.
36pub trait MemoryStorage: Send + Sync {
37    /// Every memory, most recently seen first.
38    fn load_all(&self) -> Vec<DurableMemory>;
39
40    /// Memories matching `query`, however this backend matches. The shipped
41    /// implementation is a substring scan; a backend with an index is
42    /// expected to do better, and nothing depends on the ranking.
43    fn search(&self, query: &str) -> Vec<DurableMemory>;
44
45    /// Write these, returning how many landed.
46    fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError>;
47
48    /// Forget one by name; `false` if it was not there.
49    fn remove(&self, name: &str) -> Result<bool, MemoryError>;
50}
51
52/// Memories held in memory. The second implementation, and what a test that
53/// is about recall rather than about files should use.
54#[derive(Default)]
55pub struct InMemoryStorage {
56    memories: std::sync::Mutex<Vec<DurableMemory>>,
57}
58
59impl InMemoryStorage {
60    pub fn new(memories: Vec<DurableMemory>) -> Self {
61        Self {
62            memories: std::sync::Mutex::new(memories),
63        }
64    }
65}
66
67impl MemoryStorage for InMemoryStorage {
68    fn load_all(&self) -> Vec<DurableMemory> {
69        self.memories
70            .lock()
71            .unwrap_or_else(|e| e.into_inner())
72            .clone()
73    }
74
75    fn search(&self, query: &str) -> Vec<DurableMemory> {
76        self.load_all()
77            .into_iter()
78            .filter(|m| {
79                m.name.contains(query) || m.description.contains(query) || m.content.contains(query)
80            })
81            .collect()
82    }
83
84    fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError> {
85        let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
86        let n = memories.len();
87        for m in memories {
88            match held.iter_mut().find(|h| h.name == m.name) {
89                Some(existing) => *existing = m,
90                None => held.push(m),
91            }
92        }
93        Ok(n)
94    }
95
96    fn remove(&self, name: &str) -> Result<bool, MemoryError> {
97        let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
98        let before = held.len();
99        held.retain(|m| m.name != name);
100        Ok(held.len() != before)
101    }
102}
103
104/// What a turn is asking for.
105#[derive(Debug, Clone)]
106pub struct RetrievalRequest {
107    /// What the user said, which is what recall is about.
108    pub query: String,
109    pub limit: usize,
110    /// Already shown this session. Surfacing one twice spends context to tell
111    /// the model something it was told.
112    pub already_surfaced: HashSet<String>,
113    /// Tool names in play, so a memory whose name collides with a tool is not
114    /// pulled in by the ambiguity.
115    pub recent_tools: Vec<String>,
116    pub model_name: String,
117    pub session_id: Option<String>,
118}
119
120/// Which memories this turn should see.
121#[async_trait]
122pub trait MemoryRetriever: Send + Sync {
123    /// Returns memory *names*, best first. Names rather than whole memories
124    /// because the caller re-reads them from storage anyway, and a retriever
125    /// backed by an index has no reason to carry the bodies around.
126    async fn retrieve(
127        &self,
128        storage: &dyn MemoryStorage,
129        model: &dyn crate::interface::model::Model,
130        request: &RetrievalRequest,
131    ) -> Vec<String>;
132}
133
134/// Matches on substrings and spends nothing.
135///
136/// The second implementation, and the one a test wants: recall that is a pure
137/// function of the store is recall a test can assert on, where the model-based
138/// default is a judgement that may reasonably differ between runs.
139pub struct SubstringRetriever;
140
141#[async_trait]
142impl MemoryRetriever for SubstringRetriever {
143    async fn retrieve(
144        &self,
145        storage: &dyn MemoryStorage,
146        _model: &dyn crate::interface::model::Model,
147        request: &RetrievalRequest,
148    ) -> Vec<String> {
149        storage
150            .search(&request.query)
151            .into_iter()
152            .map(|m| m.name)
153            .filter(|name| !request.already_surfaced.contains(name))
154            .filter(|name| {
155                !request
156                    .recent_tools
157                    .iter()
158                    .any(|t| name.eq_ignore_ascii_case(t))
159            })
160            .take(request.limit)
161            .collect()
162    }
163}
164
165/// A look at the question before it is asked, and the answer before it is used.
166///
167/// Both halves are useful for the same reason and in opposite directions: a
168/// deployment knows things about its own vocabulary that the retriever does
169/// not (expand an acronym, add the current file's name), and knows things
170/// about its own policy that the retriever should not have to (drop anything
171/// from a scope this session must not see).
172pub trait RetrievalHook: Send + Sync {
173    /// Change the question. The default does nothing.
174    fn before_retrieve(&self, _request: &mut RetrievalRequest) {}
175
176    /// Change the answer — filter, reorder, truncate. The default does
177    /// nothing.
178    fn after_retrieve(&self, _request: &RetrievalRequest, _names: &mut Vec<String>) {}
179}
180
181/// Run a retrieval with its hooks around it.
182pub async fn retrieve_with_hooks(
183    retriever: &dyn MemoryRetriever,
184    hooks: &[std::sync::Arc<dyn RetrievalHook>],
185    storage: &dyn MemoryStorage,
186    model: &dyn crate::interface::model::Model,
187    mut request: RetrievalRequest,
188) -> Vec<String> {
189    for hook in hooks {
190        hook.before_retrieve(&mut request);
191    }
192    let mut names = retriever.retrieve(storage, model, &request).await;
193    for hook in hooks {
194        hook.after_retrieve(&request, &mut names);
195    }
196    names
197}
198
199/// What the model is told about writing memories down.
200///
201/// The engine's extraction strategy is a prompt: the model decides what is
202/// worth remembering, and the only lever anyone has is the wording. Making the
203/// wording replaceable is therefore the whole of "the extraction policy is
204/// replaceable" — anything more would be inventing a mechanism that does not
205/// exist to abstract over it.
206pub trait ExtractionPolicy: Send + Sync {
207    /// The instructions that go into the system prompt.
208    fn instructions(&self, memory_dir: &std::path::Path) -> String;
209}
210
211/// Says nothing, so the model is never told to write memories down.
212///
213/// The second implementation, and a real configuration: a deployment that
214/// curates memories itself does not want the model appending to them, and
215/// switching the feature off entirely also switches off recall of what is
216/// already there.
217pub struct NoExtraction;
218
219impl ExtractionPolicy for NoExtraction {
220    fn instructions(&self, _memory_dir: &std::path::Path) -> String {
221        String::new()
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use std::sync::Arc;
229
230    fn memory(name: &str, content: &str) -> DurableMemory {
231        DurableMemory {
232            name: name.to_string(),
233            description: String::new(),
234            memory_type: crate::memory::MemoryType::default(),
235            content: content.to_string(),
236            source_session_id: String::new(),
237            confidence: 0.8,
238            last_seen: String::new(),
239            recall_count: 0,
240        }
241    }
242
243    struct NeverCalledModel;
244
245    #[async_trait]
246    impl crate::interface::model::Model for NeverCalledModel {
247        fn api_type(&self) -> crate::provider::ApiType {
248            crate::provider::ApiType::Anthropic
249        }
250        async fn stream(
251            &self,
252            _p: Vec<crate::prompt::PromptBlock>,
253            _t: Vec<crate::interface::model::ToolDef>,
254            _m: Vec<crate::interface::model::ModelMessage>,
255            _s: crate::interface::model::StreamParams,
256            _c: tokio_util::sync::CancellationToken,
257        ) -> Result<crate::interface::model::ModelStream, crate::interface::model::ModelError>
258        {
259            panic!("a retriever that costs nothing must not call the model")
260        }
261    }
262
263    fn store() -> InMemoryStorage {
264        InMemoryStorage::new(vec![
265            memory("deploy-process", "we deploy on fridays"),
266            memory("Bash", "a memory whose name collides with a tool"),
267            memory("unrelated", "nothing to do with anything"),
268        ])
269    }
270
271    #[tokio::test]
272    async fn a_retriever_that_costs_nothing_can_replace_the_one_that_costs_a_call() {
273        let names = SubstringRetriever
274            .retrieve(
275                &store(),
276                &NeverCalledModel,
277                &RetrievalRequest {
278                    query: "deploy".into(),
279                    limit: 5,
280                    already_surfaced: HashSet::new(),
281                    recent_tools: Vec::new(),
282                    model_name: "test".into(),
283                    session_id: None,
284                },
285            )
286            .await;
287        assert_eq!(names, ["deploy-process"]);
288    }
289
290    #[tokio::test]
291    async fn recall_never_repeats_itself_or_shadows_a_tool() {
292        let names = SubstringRetriever
293            .retrieve(
294                &store(),
295                &NeverCalledModel,
296                &RetrievalRequest {
297                    query: "a".into(),
298                    limit: 5,
299                    already_surfaced: HashSet::from(["unrelated".to_string()]),
300                    recent_tools: vec!["bash".into()],
301                    model_name: "test".into(),
302                    session_id: None,
303                },
304            )
305            .await;
306        assert!(!names.contains(&"unrelated".to_string()), "{names:?}");
307        assert!(
308            !names.contains(&"Bash".to_string()),
309            "a memory named after a tool in play is an ambiguity, not a recall: {names:?}"
310        );
311    }
312
313    #[tokio::test]
314    async fn hooks_see_the_question_before_and_the_answer_after() {
315        struct Expands;
316        impl RetrievalHook for Expands {
317            fn before_retrieve(&self, request: &mut RetrievalRequest) {
318                if request.query == "ship" {
319                    request.query = "deploy".into();
320                }
321            }
322            fn after_retrieve(&self, _request: &RetrievalRequest, names: &mut Vec<String>) {
323                names.retain(|n| n != "deploy-process");
324            }
325        }
326
327        let hooks: Vec<Arc<dyn RetrievalHook>> = vec![Arc::new(Expands)];
328        let names = retrieve_with_hooks(
329            &SubstringRetriever,
330            &hooks,
331            &store(),
332            &NeverCalledModel,
333            RetrievalRequest {
334                query: "ship".into(),
335                limit: 5,
336                already_surfaced: HashSet::new(),
337                recent_tools: Vec::new(),
338                model_name: "test".into(),
339                session_id: None,
340            },
341        )
342        .await;
343        assert!(
344            names.is_empty(),
345            "the query rewrite found it and the result filter removed it: {names:?}"
346        );
347
348        // Without the filter the rewrite alone would have found it, which is
349        // what makes the assertion above about both halves rather than one.
350        let no_hooks: Vec<Arc<dyn RetrievalHook>> = Vec::new();
351        let names = retrieve_with_hooks(
352            &SubstringRetriever,
353            &no_hooks,
354            &store(),
355            &NeverCalledModel,
356            RetrievalRequest {
357                query: "deploy".into(),
358                limit: 5,
359                already_surfaced: HashSet::new(),
360                recent_tools: Vec::new(),
361                model_name: "test".into(),
362                session_id: None,
363            },
364        )
365        .await;
366        assert_eq!(names, ["deploy-process"]);
367    }
368
369    #[test]
370    fn an_in_memory_store_round_trips_and_forgets() {
371        let s = InMemoryStorage::default();
372        assert_eq!(s.persist_batch(vec![memory("a", "x")]).unwrap(), 1);
373        assert_eq!(s.load_all().len(), 1);
374        assert_eq!(s.persist_batch(vec![memory("a", "y")]).unwrap(), 1);
375        assert_eq!(s.load_all().len(), 1, "a rewrite is not a second memory");
376        assert_eq!(s.load_all()[0].content, "y");
377        assert!(s.remove("a").unwrap());
378        assert!(!s.remove("a").unwrap(), "forgetting twice is not an error");
379    }
380}