use std::collections::HashSet;
use async_trait::async_trait;
use crate::memory::{DurableMemory, MemoryError};
pub trait MemoryStorage: Send + Sync {
fn load_all(&self) -> Vec<DurableMemory>;
fn search(&self, query: &str) -> Vec<DurableMemory>;
fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError>;
fn remove(&self, name: &str) -> Result<bool, MemoryError>;
}
#[derive(Default)]
pub struct InMemoryStorage {
memories: std::sync::Mutex<Vec<DurableMemory>>,
}
impl InMemoryStorage {
pub fn new(memories: Vec<DurableMemory>) -> Self {
Self {
memories: std::sync::Mutex::new(memories),
}
}
}
impl MemoryStorage for InMemoryStorage {
fn load_all(&self) -> Vec<DurableMemory> {
self.memories
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
fn search(&self, query: &str) -> Vec<DurableMemory> {
self.load_all()
.into_iter()
.filter(|m| {
m.name.contains(query) || m.description.contains(query) || m.content.contains(query)
})
.collect()
}
fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError> {
let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
let n = memories.len();
for m in memories {
match held.iter_mut().find(|h| h.name == m.name) {
Some(existing) => *existing = m,
None => held.push(m),
}
}
Ok(n)
}
fn remove(&self, name: &str) -> Result<bool, MemoryError> {
let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
let before = held.len();
held.retain(|m| m.name != name);
Ok(held.len() != before)
}
}
#[derive(Debug, Clone)]
pub struct RetrievalRequest {
pub query: String,
pub limit: usize,
pub already_surfaced: HashSet<String>,
pub recent_tools: Vec<String>,
pub model_name: String,
pub session_id: Option<String>,
}
#[async_trait]
pub trait MemoryRetriever: Send + Sync {
async fn retrieve(
&self,
storage: &dyn MemoryStorage,
model: &dyn crate::interface::model::Model,
request: &RetrievalRequest,
) -> Vec<String>;
}
pub struct SubstringRetriever;
#[async_trait]
impl MemoryRetriever for SubstringRetriever {
async fn retrieve(
&self,
storage: &dyn MemoryStorage,
_model: &dyn crate::interface::model::Model,
request: &RetrievalRequest,
) -> Vec<String> {
storage
.search(&request.query)
.into_iter()
.map(|m| m.name)
.filter(|name| !request.already_surfaced.contains(name))
.filter(|name| {
!request
.recent_tools
.iter()
.any(|t| name.eq_ignore_ascii_case(t))
})
.take(request.limit)
.collect()
}
}
pub trait RetrievalHook: Send + Sync {
fn before_retrieve(&self, _request: &mut RetrievalRequest) {}
fn after_retrieve(&self, _request: &RetrievalRequest, _names: &mut Vec<String>) {}
}
pub async fn retrieve_with_hooks(
retriever: &dyn MemoryRetriever,
hooks: &[std::sync::Arc<dyn RetrievalHook>],
storage: &dyn MemoryStorage,
model: &dyn crate::interface::model::Model,
mut request: RetrievalRequest,
) -> Vec<String> {
for hook in hooks {
hook.before_retrieve(&mut request);
}
let mut names = retriever.retrieve(storage, model, &request).await;
for hook in hooks {
hook.after_retrieve(&request, &mut names);
}
names
}
pub trait ExtractionPolicy: Send + Sync {
fn instructions(&self, memory_dir: &std::path::Path) -> String;
}
pub struct NoExtraction;
impl ExtractionPolicy for NoExtraction {
fn instructions(&self, _memory_dir: &std::path::Path) -> String {
String::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn memory(name: &str, content: &str) -> DurableMemory {
DurableMemory {
name: name.to_string(),
description: String::new(),
memory_type: crate::memory::MemoryType::default(),
content: content.to_string(),
source_session_id: String::new(),
confidence: 0.8,
last_seen: String::new(),
recall_count: 0,
}
}
struct NeverCalledModel;
#[async_trait]
impl crate::interface::model::Model for NeverCalledModel {
fn api_type(&self) -> crate::provider::ApiType {
crate::provider::ApiType::Anthropic
}
async fn stream(
&self,
_p: Vec<crate::prompt::PromptBlock>,
_t: Vec<crate::interface::model::ToolDef>,
_m: Vec<crate::interface::model::ModelMessage>,
_s: crate::interface::model::StreamParams,
_c: tokio_util::sync::CancellationToken,
) -> Result<crate::interface::model::ModelStream, crate::interface::model::ModelError>
{
panic!("a retriever that costs nothing must not call the model")
}
}
fn store() -> InMemoryStorage {
InMemoryStorage::new(vec![
memory("deploy-process", "we deploy on fridays"),
memory("Bash", "a memory whose name collides with a tool"),
memory("unrelated", "nothing to do with anything"),
])
}
#[tokio::test]
async fn a_retriever_that_costs_nothing_can_replace_the_one_that_costs_a_call() {
let names = SubstringRetriever
.retrieve(
&store(),
&NeverCalledModel,
&RetrievalRequest {
query: "deploy".into(),
limit: 5,
already_surfaced: HashSet::new(),
recent_tools: Vec::new(),
model_name: "test".into(),
session_id: None,
},
)
.await;
assert_eq!(names, ["deploy-process"]);
}
#[tokio::test]
async fn recall_never_repeats_itself_or_shadows_a_tool() {
let names = SubstringRetriever
.retrieve(
&store(),
&NeverCalledModel,
&RetrievalRequest {
query: "a".into(),
limit: 5,
already_surfaced: HashSet::from(["unrelated".to_string()]),
recent_tools: vec!["bash".into()],
model_name: "test".into(),
session_id: None,
},
)
.await;
assert!(!names.contains(&"unrelated".to_string()), "{names:?}");
assert!(
!names.contains(&"Bash".to_string()),
"a memory named after a tool in play is an ambiguity, not a recall: {names:?}"
);
}
#[tokio::test]
async fn hooks_see_the_question_before_and_the_answer_after() {
struct Expands;
impl RetrievalHook for Expands {
fn before_retrieve(&self, request: &mut RetrievalRequest) {
if request.query == "ship" {
request.query = "deploy".into();
}
}
fn after_retrieve(&self, _request: &RetrievalRequest, names: &mut Vec<String>) {
names.retain(|n| n != "deploy-process");
}
}
let hooks: Vec<Arc<dyn RetrievalHook>> = vec![Arc::new(Expands)];
let names = retrieve_with_hooks(
&SubstringRetriever,
&hooks,
&store(),
&NeverCalledModel,
RetrievalRequest {
query: "ship".into(),
limit: 5,
already_surfaced: HashSet::new(),
recent_tools: Vec::new(),
model_name: "test".into(),
session_id: None,
},
)
.await;
assert!(
names.is_empty(),
"the query rewrite found it and the result filter removed it: {names:?}"
);
let no_hooks: Vec<Arc<dyn RetrievalHook>> = Vec::new();
let names = retrieve_with_hooks(
&SubstringRetriever,
&no_hooks,
&store(),
&NeverCalledModel,
RetrievalRequest {
query: "deploy".into(),
limit: 5,
already_surfaced: HashSet::new(),
recent_tools: Vec::new(),
model_name: "test".into(),
session_id: None,
},
)
.await;
assert_eq!(names, ["deploy-process"]);
}
#[test]
fn an_in_memory_store_round_trips_and_forgets() {
let s = InMemoryStorage::default();
assert_eq!(s.persist_batch(vec![memory("a", "x")]).unwrap(), 1);
assert_eq!(s.load_all().len(), 1);
assert_eq!(s.persist_batch(vec![memory("a", "y")]).unwrap(), 1);
assert_eq!(s.load_all().len(), 1, "a rewrite is not a second memory");
assert_eq!(s.load_all()[0].content, "y");
assert!(s.remove("a").unwrap());
assert!(!s.remove("a").unwrap(), "forgetting twice is not an error");
}
}