//! The agent's long-term semantic memory tools: `remember`, `recall`, `forget`. //! //! These sit on top of [`crate::memory::MemoryService`] (authoritative Store + //! rebuildable Qdrant Edge index). The model only ever sees TEXT + a relevance //! score — never raw vectors (the symbolic-vector principle). Results are //! rendered compactly and bounded so recall cannot blow up the context window. //! //! Unlike the per-session notepad (single-task state), memory is durable facts, //! decisions, preferences and pitfalls worth recalling later. It is PER-SESSION: //! each session remembers/recalls only its own pool (the framework forces the //! record scope to the session id; the model never chooses it). A shared/common //! memory across sessions is a later capability. use std::sync::Arc; use serde_json::{json, Value as Json}; use crate::memory::{MemoryService, RememberInput}; /// Default recall breadth and relevance floor (cosine). The floor is calibrated /// from the BGE-M3 fitness probe on our content: true matches scored >=0.52 while /// unrelated queries peaked at 0.42, so 0.45 keeps the hits and rejects the noise. /// The model can still tune `threshold` per query. const DEFAULT_TOP_K: usize = 5; const DEFAULT_THRESHOLD: f32 = 0.45; /// Per-hit content cap in the rendered result (unicode-aware), so one long /// memory cannot dominate the context. const MAX_HIT_CONTENT_CHARS: usize = 400; /// The three memory tool declarations, offered when the service is available. pub fn memory_tools() -> Vec { vec![ remember_declaration(), recall_declaration(), forget_declaration(), ] } pub fn remember_declaration() -> Json { json!({ "type": "function", "function": { "name": "remember", "description": "Save a durable fact, decision, preference or pitfall to this session's \ long-term semantic memory (survives the sliding context window; private to this \ session). Use for knowledge worth recalling later, NOT single-task ephemera (use \ the notepad for that). `content` is required and should be self-contained; \ `category` groups related memories (e.g. user_preference, project_fact, decision, \ pitfall). Returns the new memory id.", "parameters": { "type": "object", "properties": { "content": { "type": "string", "description": "The memory text to store (required). Concise and self-contained." }, "title": { "type": "string", "description": "Short label; defaults to the first line of content." }, "category": { "type": "string", "description": "Grouping label (e.g. user_preference, project_fact, decision, pitfall). Defaults to 'general'." }, "keywords": { "type": "array", "items": { "type": "string" }, "description": "Optional search keywords." } }, "required": ["content"] } } }) } pub fn recall_declaration() -> Json { json!({ "type": "function", "function": { "name": "recall", "description": "Search this session's long-term semantic memory by meaning. Returns \ the most relevant memories as text with a relevance score (never raw vectors). Use \ before answering questions that may depend on past facts, decisions or preferences. \ `query` is required; optionally filter by category and tune top_k/threshold.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "What to look for, phrased naturally (required)." }, "top_k": { "type": "integer", "description": "Max results (default 5, clamped 1..20)." }, "category": { "type": "string", "description": "Restrict to this category (optional)." }, "threshold": { "type": "number", "description": "Minimum cosine relevance 0..1 (default 0.45)." } }, "required": ["query"] } } }) } pub fn forget_declaration() -> Json { json!({ "type": "function", "function": { "name": "forget", "description": "Delete a memory by its id (as returned by remember/recall). Use to \ remove outdated or incorrect memories. `id` is required.", "parameters": { "type": "object", "properties": { "id": { "type": "string", "description": "The memory id to delete (required)." } }, "required": ["id"] } } }) } /// Execute a memory tool call, returning the text the model reads. All Store + /// index work runs off the async runtime (the service is sync). pub async fn execute( memory: &Arc, session_id: &str, name: &str, args: &Json, ) -> String { let mem = memory.clone(); let scope = session_id.to_string(); let name = name.to_string(); let args = args.clone(); let res = tokio::task::spawn_blocking(move || match name.as_str() { "remember" => do_remember(&mem, &scope, &args), "recall" => do_recall(&mem, &scope, &args), "forget" => do_forget(&mem, &scope, &args), other => Ok(format!("error: unknown memory tool '{other}'")), }) .await; match res { Ok(Ok(msg)) => msg, Ok(Err(e)) => format!("error: {e}"), Err(e) => format!("error: memory task failed: {e}"), } } fn do_remember(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { let content = str_arg(args, "content").unwrap_or_default(); if content.trim().is_empty() { return Ok("error: remember requires non-empty 'content'".into()); } let title = str_arg(args, "title").unwrap_or_else(|| first_line(&content)); let category = str_arg(args, "category").unwrap_or_else(|| "general".into()); let keywords = args .get("keywords") .and_then(|v| v.as_array()) .map(|a| { a.iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) .collect() }) .unwrap_or_default(); let rec = mem.remember(RememberInput { category: category.clone(), title, content, keywords, scope: scope.to_string(), source: "agent".into(), })?; Ok(format!("Saved memory {} (category={category}).", rec.id)) } fn do_recall(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { let query = str_arg(args, "query").unwrap_or_default(); if query.trim().is_empty() { return Ok("error: recall requires non-empty 'query'".into()); } let top_k = args .get("top_k") .and_then(|v| v.as_u64()) .map(|n| (n as usize).clamp(1, 20)) .unwrap_or(DEFAULT_TOP_K); let threshold = args .get("threshold") .and_then(|v| v.as_f64()) .map(|t| (t as f32).clamp(0.0, 1.0)) .unwrap_or(DEFAULT_THRESHOLD); let category = str_arg(args, "category"); let hits = mem.recall(&query, top_k, threshold, category.as_deref(), Some(scope))?; if hits.is_empty() { return Ok("No matching memories.".into()); } let mut out = format!( "Found {} memor{}:\n", hits.len(), if hits.len() == 1 { "y" } else { "ies" } ); for (i, hit) in hits.iter().enumerate() { let r = &hit.record; out.push_str(&format!( "{}. [{:.2}] ({}) {}: {}\n id: {}\n", i + 1, hit.score, r.category, r.title, truncate_chars(&r.content, MAX_HIT_CONTENT_CHARS), r.id )); } Ok(out) } fn do_forget(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { let id = str_arg(args, "id").unwrap_or_default(); if id.trim().is_empty() { return Ok("error: forget requires non-empty 'id'".into()); } if mem.forget_in_scope(&id, scope)? { Ok(format!("Forgot memory {id}.")) } else { Ok(format!("No memory {id} in this session (nothing removed).")) } } /// A trimmed, non-empty string argument (None when absent/blank). fn str_arg(args: &Json, key: &str) -> Option { args.get(key) .and_then(|v| v.as_str()) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) } fn first_line(s: &str) -> String { truncate_chars(s.lines().next().unwrap_or(s), 80) } fn truncate_chars(s: &str, max: usize) -> String { if s.chars().count() <= max { return s.to_string(); } let mut out: String = s.chars().take(max).collect(); out.push('…'); out } #[cfg(test)] mod tests { use super::*; use crate::store::{SqliteStore, Store}; use strata_memory::{EmbedError, Embedder, MemoryIndex}; struct StubEmbedder; impl Embedder for StubEmbedder { fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { Ok(texts .iter() .map(|t| { let mut v = vec![0.0f32; 4]; // Cheap deterministic hashing into a unit-ish vector so // identical texts match and different ones mostly don't. for (i, b) in t.bytes().enumerate() { v[i % 4] += b as f32; } let n = v.iter().map(|x| x * x).sum::().sqrt(); if n > 0.0 { for x in &mut v { *x /= n; } } v }) .collect()) } fn dim(&self) -> usize { 4 } fn model_id(&self) -> &str { "stub" } } fn service() -> (Arc, tempfile::TempDir) { let tmp = tempfile::tempdir().unwrap(); let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); let index = MemoryIndex::open(tmp.path(), 4, "stub", Arc::new(StubEmbedder)).unwrap(); (Arc::new(MemoryService::from_index(store, index)), tmp) } #[test] fn declarations_shape() { let tools = memory_tools(); assert_eq!(tools.len(), 3); assert_eq!(tools[0]["function"]["name"], "remember"); assert_eq!(tools[1]["function"]["name"], "recall"); assert_eq!(tools[2]["function"]["name"], "forget"); assert_eq!(tools[0]["function"]["parameters"]["required"][0], "content"); assert_eq!(tools[1]["function"]["parameters"]["required"][0], "query"); } #[tokio::test] async fn remember_then_recall_roundtrip() { let (mem, _tmp) = service(); let out = execute( &mem, "sess_a", "remember", &json!({"content":"Il gatto nero salta sul tavolo","category":"facts"}), ) .await; assert!(out.contains("Saved memory"), "{out}"); let out = execute( &mem, "sess_a", "recall", &json!({"query":"Il gatto nero salta sul tavolo"}), ) .await; assert!(out.contains("gatto"), "{out}"); assert!(out.contains("id:"), "{out}"); // The rendered result must NOT leak a raw vector array. assert!(!out.contains("[0."), "no vector floats in context: {out}"); } #[tokio::test] async fn per_session_isolation() { let (mem, _tmp) = service(); // Session A remembers a fact. let out = execute( &mem, "sess_a", "remember", &json!({"content":"Il gatto nero salta sul tavolo"}), ) .await; let id = out.split_whitespace().nth(2).unwrap().to_string(); // Session B cannot recall it (different scope). let out = execute( &mem, "sess_b", "recall", &json!({"query":"Il gatto nero salta sul tavolo"}), ) .await; assert!(out.contains("No matching memories"), "{out}"); // Session B cannot forget A's record by id. let out = execute(&mem, "sess_b", "forget", &json!({"id": id})).await; assert!(out.contains("nothing removed"), "{out}"); // A still recalls its own. let out = execute( &mem, "sess_a", "recall", &json!({"query":"Il gatto nero salta sul tavolo"}), ) .await; assert!(out.contains("gatto"), "{out}"); } #[tokio::test] async fn validation_errors() { let (mem, _tmp) = service(); assert!(execute(&mem, "sess_a", "remember", &json!({})) .await .contains("content")); assert!(execute(&mem, "sess_a", "recall", &json!({})) .await .contains("query")); assert!(execute(&mem, "sess_a", "forget", &json!({})) .await .contains("id")); assert!(execute(&mem, "sess_a", "bogus", &json!({})) .await .contains("unknown")); } #[tokio::test] async fn forget_roundtrip() { let (mem, _tmp) = service(); let out = execute(&mem, "sess_a", "remember", &json!({"content":"alpha"})).await; // Extract the id from "Saved memory (...)". let id = out.split_whitespace().nth(2).unwrap().to_string(); let out = execute(&mem, "sess_a", "forget", &json!({"id": id})).await; assert!(out.contains("Forgot"), "{out}"); let out = execute(&mem, "sess_a", "forget", &json!({"id": id})).await; assert!(out.contains("nothing removed"), "{out}"); } }