use std::time::Duration;
use crate::episodic::episode::{Episode, EpisodeKind};
use crate::episodic::store::EpisodicStore;
use crate::error::MemoryError;
use crate::id::{AgentId, SessionId, Tag};
#[derive(Debug, Default, Clone)]
pub struct MemoryQuery {
pub agent_id: Option<AgentId>,
pub session_id: Option<SessionId>,
pub tags: Vec<Tag>,
pub since: Option<Duration>,
pub limit: Option<usize>,
pub kind: Option<EpisodeKind>,
}
impl MemoryQuery {
pub fn new() -> Self {
Self::default()
}
pub fn with_agent(mut self, agent_id: AgentId) -> Self {
self.agent_id = Some(agent_id);
self
}
pub fn with_session(mut self, session_id: SessionId) -> Self {
self.session_id = Some(session_id);
self
}
pub fn with_tag(mut self, tag: Tag) -> Self {
self.tags.push(tag);
self
}
pub fn since(mut self, duration: Duration) -> Self {
self.since = Some(duration);
self
}
pub fn limit(mut self, n: usize) -> Self {
self.limit = Some(n);
self
}
pub fn with_kind(mut self, kind: EpisodeKind) -> Self {
self.kind = Some(kind);
self
}
pub async fn execute<S: EpisodicStore>(
&self,
store: &S,
) -> Result<Vec<Episode>, MemoryError> {
let all = store.all().await?;
let cutoff = self.since.map(|d| {
chrono::Utc::now()
- chrono::Duration::from_std(d).unwrap_or(chrono::Duration::MAX)
});
let mut results: Vec<Episode> = all
.into_iter()
.filter(|ep| {
if let Some(ref aid) = self.agent_id {
if &ep.agent_id != aid {
return false;
}
}
if let Some(ref sid) = self.session_id {
if &ep.session_id != sid {
return false;
}
}
if !self.tags.is_empty() && !self.tags.iter().any(|t| ep.tags.contains(t)) {
return false;
}
if let Some(cutoff_ts) = cutoff {
if ep.timestamp < cutoff_ts {
return false;
}
}
if let Some(ref k) = self.kind {
if &ep.kind != k {
return false;
}
}
true
})
.collect();
if let Some(lim) = self.limit {
results.truncate(lim);
}
Ok(results)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::episodic::episode::EpisodeKind;
use crate::episodic::store::InMemoryEpisodicStore;
use crate::id::{AgentId, SessionId, Tag};
use chrono::Utc;
fn ep(
store: &InMemoryEpisodicStore,
agent: AgentId,
session: SessionId,
kind: EpisodeKind,
tags: Vec<Tag>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>> {
let ep = crate::episodic::episode::Episode::new(
agent, session, kind, "content", 0.8, tags,
)
.unwrap();
Box::pin(async move {
store.record(ep).await.unwrap();
})
}
#[tokio::test]
async fn test_memory_query_builder_no_filter_returns_all() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s = SessionId::new();
ep(&store, a.clone(), s.clone(), EpisodeKind::Observation, vec![]).await;
ep(&store, a.clone(), s.clone(), EpisodeKind::Action, vec![]).await;
let results = MemoryQuery::new().execute(&store).await.unwrap();
assert_eq!(results.len(), 2);
}
#[tokio::test]
async fn test_memory_query_builder_filters_by_agent() {
let store = InMemoryEpisodicStore::new();
let a1 = AgentId::new();
let a2 = AgentId::new();
let s = SessionId::new();
ep(&store, a1.clone(), s.clone(), EpisodeKind::Observation, vec![]).await;
ep(&store, a2.clone(), s.clone(), EpisodeKind::Observation, vec![]).await;
let results = MemoryQuery::new()
.with_agent(a1.clone())
.execute(&store)
.await
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].agent_id, a1);
}
#[tokio::test]
async fn test_memory_query_builder_filters_by_tag() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s = SessionId::new();
let t = Tag::new("hot");
ep(&store, a.clone(), s.clone(), EpisodeKind::Observation, vec![t.clone()]).await;
ep(&store, a.clone(), s.clone(), EpisodeKind::Observation, vec![]).await;
let results = MemoryQuery::new()
.with_tag(t)
.execute(&store)
.await
.unwrap();
assert_eq!(results.len(), 1);
}
#[tokio::test]
async fn test_memory_query_limit_caps_results() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s = SessionId::new();
for _ in 0..5 {
ep(&store, a.clone(), s.clone(), EpisodeKind::Observation, vec![]).await;
}
let results = MemoryQuery::new().limit(3).execute(&store).await.unwrap();
assert_eq!(results.len(), 3);
}
#[tokio::test]
async fn test_memory_query_filters_by_kind() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s = SessionId::new();
ep(&store, a.clone(), s.clone(), EpisodeKind::Action, vec![]).await;
ep(&store, a.clone(), s.clone(), EpisodeKind::Inference, vec![]).await;
let results = MemoryQuery::new()
.with_kind(EpisodeKind::Action)
.execute(&store)
.await
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].kind, EpisodeKind::Action);
}
#[tokio::test]
async fn test_memory_query_filters_by_session() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s1 = SessionId::new();
let s2 = SessionId::new();
ep(&store, a.clone(), s1.clone(), EpisodeKind::Observation, vec![]).await;
ep(&store, a.clone(), s2.clone(), EpisodeKind::Observation, vec![]).await;
let results = MemoryQuery::new()
.with_session(s1.clone())
.execute(&store)
.await
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].session_id, s1);
}
#[tokio::test]
async fn test_memory_query_since_excludes_old_episodes() {
let store = InMemoryEpisodicStore::new();
let a = AgentId::new();
let s = SessionId::new();
let recent = crate::episodic::episode::Episode::with_timestamp(
a.clone(),
s.clone(),
EpisodeKind::Observation,
"recent",
0.8,
vec![],
Utc::now(),
)
.unwrap();
let old_ts = Utc::now() - chrono::Duration::days(10);
let old = crate::episodic::episode::Episode::with_timestamp(
a.clone(),
s.clone(),
EpisodeKind::Observation,
"old",
0.8,
vec![],
old_ts,
)
.unwrap();
store.record(recent).await.unwrap();
store.record(old).await.unwrap();
let results = MemoryQuery::new()
.since(Duration::from_secs(60)) .execute(&store)
.await
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].content, "recent");
}
}