//! Long-term memory: memory index and recall tools, explicit owner notes, saved and private memory, //! Brain knowledge base, context compaction. pub mod brain; pub mod compaction; pub mod embed; pub mod index; pub mod notes; pub mod private; pub mod saved; pub mod tools; mod ui; use std::path::PathBuf; use std::sync::{Arc, Weak}; use std::time::Duration; use anyhow::Result; use capri_agent::tools::Tool; use capri_core::{Section, SettingsStore}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use tokio::sync::Notify; pub use notes::{owner_note_request, recall_owner_note, save_owner_note, NoteRequest, Saved}; pub use ui::settings_ui; const POLL: Duration = Duration::from_millis(1500); const SESSION_DELTA_MESSAGES: usize = 50; const SESSION_DELTA_BYTES: usize = 100_000; /// Settings section `memory` in settings.json. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct MemorySettings { /// Index current and archived conversations for `memory_search`. pub remember_across_conversations: bool, /// Brain: use local knowledge documents. pub brain_enabled: bool, /// Brain: allow excerpts in requests to an external API provider. pub brain_share_with_api: bool, } impl Default for MemorySettings { fn default() -> Self { Self { remember_across_conversations: true, brain_enabled: true, brain_share_with_api: false } } } impl Section for MemorySettings { const NAME: &'static str = "memory"; } pub(crate) fn sha256_hex(bytes: &[u8]) -> String { hex::encode(Sha256::digest(bytes)) } /// Longest prefix of `s` that is at most `max` UTF-16 code units (Capri counts JavaScript lengths). pub(crate) fn truncate_utf16(s: &str, max: usize) -> &str { let mut units = 0; for (i, c) in s.char_indices() { units += c.len_utf16(); if units > max { return &s[..i]; } } s } pub type MemoryHandle = Arc; pub struct MemoryService { store: Arc, workspace: PathBuf, pub index: Arc, pub brain: Arc, pub vault: Arc, wake: Arc, session_delta: Mutex<(usize, usize)>, runtime: tokio::runtime::Handle, ui: Mutex, } impl MemoryService { /// Opens the stores and starts background indexing. Call from inside the Tokio runtime. pub fn start(store: Arc) -> Result { let paths = store.paths().clone(); paths.ensure()?; let workspace = std::fs::canonicalize(paths.workspace())?; let index = index::MemoryIndex::open(&paths.data.join("agent").join("memory.sqlite"), workspace.clone(), paths.agent_db())?; let service = Arc::new(Self { brain: Arc::new(brain::Brain::new(&std::fs::canonicalize(&paths.data)?, &paths.state())?), vault: Arc::new(private::PrivateVault::new(paths.state().join("private-memory.enc.json"))), index: Arc::new(index), workspace, store, wake: Arc::new(Notify::new()), session_delta: Mutex::new((0, 0)), runtime: tokio::runtime::Handle::current(), ui: Default::default(), }); tokio::spawn(background(Arc::downgrade(&service), service.wake.clone())); Ok(service) } pub fn workspace(&self) -> &std::path::Path { &self.workspace } pub fn settings(&self) -> MemorySettings { self.store.section() } /// `memory_search` and `memory_get`. pub fn tools(&self) -> Vec> { vec![ Arc::new(tools::MemorySearch { index: self.index.clone(), store: self.store.clone() }), Arc::new(tools::MemoryGet { workspace: self.workspace.clone() }), ] } /// `[Local Brain excerpts` block for the turn envelope; `remote` means the reply goes to an /// external API provider. pub fn knowledge_context(&self, query: &str, remote: bool) -> String { let s = self.settings(); if !s.brain_enabled || (remote && !s.brain_share_with_api) { return String::new(); } self.brain.context(query) } /// Re-indexes soon (debounced by the background loop). pub fn request_sync(&self) { self.index.mark_dirty(); self.wake.notify_one(); } /// Call after each committed turn with the number and size of the appended session messages. pub fn on_session_messages(&self, messages: usize, bytes: usize) { let mut delta = self.session_delta.lock(); delta.0 += messages; delta.1 += bytes; if delta.0 >= SESSION_DELTA_MESSAGES || delta.1 >= SESSION_DELTA_BYTES { *delta = (0, 0); self.request_sync(); } } /// Call after a compaction or a conversation reset was committed. pub fn after_compaction(&self) { *self.session_delta.lock() = (0, 0); self.request_sync(); } /// Saves an explicit owner note (chat fast path and Settings "Save memory"). pub fn save_note(&self, note: &str) -> Result { let saved = notes::save_owner_note(&self.workspace, note)?; self.request_sync(); Ok(saved) } pub fn recall_note(&self, text: &str) -> Option { notes::recall_owner_note(&self.workspace, text) } pub fn saved_memory(&self) -> saved::SavedMemory { saved::read_saved_memory(&self.workspace) } /// "Clear long-term memory": owner notes and profile files, then the derived index. pub fn clear_long_term_memory(&self) -> Result<()> { saved::clear_saved_memory(&self.workspace)?; self.index.reset()?; self.wake.notify_one(); Ok(()) } /// Settings window hidden: lock private memory and wipe private fields. pub fn on_settings_hidden(&self) { self.vault.lock(); self.ui.lock().wipe_private(); } } async fn background(service: Weak, wake: Arc) { let mut forced = true; let mut last_fingerprint = String::new(); let mut brain_seen = String::new(); loop { let Some(svc) = service.upgrade() else { return }; svc.vault.expire(); let fingerprint = svc.index.fingerprint(); // A file change is indexed once its fingerprint is stable for one poll (1.5 s debounce). if svc.index.needs_sync() && (forced || fingerprint == last_fingerprint) { let settings = svc.store.get(); let sessions = settings.section::().remember_across_conversations; if let Err(e) = svc.index.sync(&settings.ollama_base_url(), sessions, true).await { tracing::warn!("memory: indexing failed: {e:#}"); } } last_fingerprint = fingerprint; if svc.settings().brain_enabled { let seen = svc.brain.fingerprint(); if seen != brain_seen { brain_seen = seen; let brain = svc.brain.clone(); if let Ok(Err(e)) = tokio::task::spawn_blocking(move || brain.refresh()).await { tracing::warn!("{e:#}"); } } } drop(svc); forced = tokio::select! { _ = wake.notified() => true, _ = tokio::time::sleep(POLL) => false, }; } } #[cfg(test)] mod tests { use super::*; use capri_core::{Paths, Settings}; #[test] fn utf16_truncation_respects_boundaries() { assert_eq!(truncate_utf16("héllo", 2), "hé"); assert_eq!(truncate_utf16("a😀b", 2), "a"); assert_eq!(truncate_utf16("a😀b", 3), "a😀"); } #[tokio::test] async fn service_wires_notes_tools_and_brain() { let dir = tempfile::tempdir().unwrap(); let paths = Paths::under(dir.path().to_path_buf()); paths.ensure().unwrap(); let mut settings = Settings { ollama_url: Some("http://127.0.0.1:9".into()), ..Default::default() }; settings.set_section(&MemorySettings { brain_share_with_api: false, ..Default::default() }); let memory = MemoryService::start(SettingsStore::new(paths.clone(), settings)).unwrap(); let names: Vec = memory.tools().iter().map(|t| t.name().to_string()).collect(); assert_eq!(names, ["memory_search", "memory_get"]); let Some(NoteRequest::Save(note)) = owner_note_request("Remember that my favourite tea is oolong.") else { panic!() }; memory.save_note(¬e).unwrap(); assert_eq!(memory.recall_note("What is my favourite tea?").as_deref(), Some("oolong")); assert_eq!(memory.saved_memory().items[0].text, "my favourite tea is oolong"); std::fs::write(memory.brain.folder.join("tea.md"), "Oolong is brewed at 90 degrees.").unwrap(); memory.brain.refresh().unwrap(); assert!(memory.knowledge_context("oolong", false).contains("tea.md")); assert_eq!(memory.knowledge_context("oolong", true), "", "no external sharing by default"); memory.clear_long_term_memory().unwrap(); assert!(memory.saved_memory().items.is_empty()); assert_eq!(memory.recall_note("What is my favourite tea?"), None); } }