1use std::collections::HashSet;
25
26use async_trait::async_trait;
27
28use crate::memory::{DurableMemory, MemoryError};
29
30pub trait MemoryStorage: Send + Sync {
37 fn load_all(&self) -> Vec<DurableMemory>;
39
40 fn search(&self, query: &str) -> Vec<DurableMemory>;
44
45 fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError>;
47
48 fn remove(&self, name: &str) -> Result<bool, MemoryError>;
50}
51
52#[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#[derive(Debug, Clone)]
106pub struct RetrievalRequest {
107 pub query: String,
109 pub limit: usize,
110 pub already_surfaced: HashSet<String>,
113 pub recent_tools: Vec<String>,
116 pub model_name: String,
117 pub session_id: Option<String>,
118}
119
120#[async_trait]
122pub trait MemoryRetriever: Send + Sync {
123 async fn retrieve(
127 &self,
128 storage: &dyn MemoryStorage,
129 model: &dyn crate::interface::model::Model,
130 request: &RetrievalRequest,
131 ) -> Vec<String>;
132}
133
134pub 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
165pub trait RetrievalHook: Send + Sync {
173 fn before_retrieve(&self, _request: &mut RetrievalRequest) {}
175
176 fn after_retrieve(&self, _request: &RetrievalRequest, _names: &mut Vec<String>) {}
179}
180
181pub 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
199pub trait ExtractionPolicy: Send + Sync {
207 fn instructions(&self, memory_dir: &std::path::Path) -> String;
209}
210
211pub 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 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}