Skip to main content

ambi_memory/provider/
summary.rs

1//! Rolling summary memory provider for anti-amnesia on context eviction.
2//!
3//! When the FIFO eviction algorithm drops old conversation turns, this provider
4//! persists compressed summaries so the agent can reconstruct distant context.
5
6use crate::error::Result;
7use async_trait::async_trait;
8use std::collections::HashMap;
9use std::sync::Arc;
10use tokio::sync::RwLock;
11
12/// Rolling summary memory interface.
13#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
14#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
15pub trait SummaryMemoryProvider: Send + Sync {
16    /// Overwrite the rolling summary for a session with a new compressed version.
17    async fn update_summary(&self, session_id: &str, new_summary: &str) -> Result<()>;
18
19    /// Retrieve the currently held rolling summary for a session.
20    async fn get_summary(&self, session_id: &str) -> Result<Option<String>>;
21}
22
23/// In-memory implementation of `SummaryMemoryProvider` (for testing and single-node deployments).
24#[derive(Clone, Default)]
25pub struct InMemorySummaryProvider {
26    store: Arc<RwLock<HashMap<String, String>>>,
27}
28
29impl InMemorySummaryProvider {
30    /// Creates an empty in-memory summary store.
31    pub fn new() -> Self {
32        Self {
33            store: Arc::new(RwLock::new(HashMap::new())),
34        }
35    }
36}
37
38#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
39#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
40impl SummaryMemoryProvider for InMemorySummaryProvider {
41    async fn update_summary(&self, session_id: &str, new_summary: &str) -> Result<()> {
42        self.store
43            .write()
44            .await
45            .insert(session_id.to_string(), new_summary.to_string());
46        Ok(())
47    }
48    async fn get_summary(&self, session_id: &str) -> Result<Option<String>> {
49        Ok(self.store.read().await.get(session_id).cloned())
50    }
51}