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