memory: per-session semantic memory (strata-memory crate, Qdrant Edge + BGE-M3)
remember/recall/forget agent tools, one-way opt-in latch with embedder gate, fail-open Store-authoritative design, keyword fallback, model-id rebuild, GUI toggle + i18n; docs updated; split-debuginfo=unpacked
This commit is contained in:
1 parent
6898cdf113
commit
f74d53e446
24 files changed
+4853
-67
No files matched your search
@@ -0,0 +1,400 @@
|
||||
//! 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<Json> {
|
||||
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<MemoryService>,
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<Vec<Vec<f32>>, 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::<f32>().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<MemoryService>, tempfile::TempDir) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store: Arc<dyn Store> = 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 <id> (...)".
|
||||
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}");
|
||||
}
|
||||
}
|
||||
+38
-3
@@ -9,6 +9,7 @@
|
||||
//! [`run_loop`] is pure orchestration — generic over the "model step" — so it is
|
||||
//! testable without the engine and independent of the concrete runner.
|
||||
|
||||
pub mod memory;
|
||||
pub mod notepad;
|
||||
pub mod share;
|
||||
pub mod shell;
|
||||
@@ -88,6 +89,7 @@ async fn execute_tool(
|
||||
tc: &ToolCall,
|
||||
default_cwd: Option<&str>,
|
||||
workspace_root: Option<&std::path::Path>,
|
||||
memory: Option<&Arc<crate::memory::MemoryService>>,
|
||||
) -> String {
|
||||
let args: Json = match serde_json::from_str(&tc.function.arguments) {
|
||||
Ok(v) => v,
|
||||
@@ -107,6 +109,10 @@ async fn execute_tool(
|
||||
}
|
||||
"notepad" => notepad::execute(store, session_id, &args).await,
|
||||
"share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await,
|
||||
"remember" | "recall" | "forget" => match memory {
|
||||
Some(m) => memory::execute(m, session_id, &tc.function.name, &args).await,
|
||||
None => "error: semantic memory is not available".into(),
|
||||
},
|
||||
name if mcp::is_mcp_tool(name) => execute_mcp(store, session_id, name, &args).await,
|
||||
other => format!("error: unknown tool '{other}'"),
|
||||
}
|
||||
@@ -214,6 +220,9 @@ pub struct LoopContext {
|
||||
/// Parent of the per-session folders and the shared uploads dir; the second
|
||||
/// root `share_file` may expose files from. None in tests without a workspace.
|
||||
pub workspace_root: Option<std::path::PathBuf>,
|
||||
/// Long-term semantic memory (remember/recall/forget). None when the memory
|
||||
/// service could not be opened or in tests without memory.
|
||||
pub memory: Option<Arc<crate::memory::MemoryService>>,
|
||||
pub max_iters: usize,
|
||||
pub progress: Option<UnboundedSender<AgentEvent>>,
|
||||
}
|
||||
@@ -239,6 +248,7 @@ where
|
||||
store,
|
||||
default_cwd,
|
||||
workspace_root,
|
||||
memory,
|
||||
max_iters,
|
||||
progress,
|
||||
} = ctx;
|
||||
@@ -336,6 +346,7 @@ where
|
||||
tc,
|
||||
default_cwd.as_deref(),
|
||||
workspace_root.as_deref(),
|
||||
memory.as_ref(),
|
||||
)
|
||||
.await;
|
||||
emit(
|
||||
@@ -494,6 +505,7 @@ mod tests {
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
memory: None,
|
||||
max_iters: 8,
|
||||
progress: Some(tx),
|
||||
},
|
||||
@@ -575,6 +587,7 @@ mod tests {
|
||||
store,
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
memory: None,
|
||||
max_iters: 3,
|
||||
progress: None,
|
||||
},
|
||||
@@ -607,6 +620,7 @@ mod tests {
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
memory: None,
|
||||
max_iters: MAX_ITERS,
|
||||
progress: None,
|
||||
},
|
||||
@@ -642,7 +656,7 @@ mod tests {
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
};
|
||||
let out = execute_tool(&runner, &store, &sess.id, &tc, None, None).await;
|
||||
let out = execute_tool(&runner, &store, &sess.id, &tc, None, None, None).await;
|
||||
assert!(out.contains("unknown tool"));
|
||||
}
|
||||
|
||||
@@ -681,14 +695,33 @@ mod tests {
|
||||
&call("mcp__gmail__gmail_send"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("not enabled"), "{out}");
|
||||
// An unknown connector is refused.
|
||||
let out = execute_tool(&runner, &store, &sess.id, &call("mcp__nope__x"), None, None).await;
|
||||
let out = execute_tool(
|
||||
&runner,
|
||||
&store,
|
||||
&sess.id,
|
||||
&call("mcp__nope__x"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("unknown MCP connector"), "{out}");
|
||||
// A malformed namespaced name is refused.
|
||||
let out = execute_tool(&runner, &store, &sess.id, &call("mcp__gmail"), None, None).await;
|
||||
let out = execute_tool(
|
||||
&runner,
|
||||
&store,
|
||||
&sess.id,
|
||||
&call("mcp__gmail"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("malformed"), "{out}");
|
||||
}
|
||||
|
||||
@@ -738,6 +771,7 @@ mod tests {
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
memory: None,
|
||||
max_iters: 8,
|
||||
progress: None,
|
||||
},
|
||||
@@ -803,6 +837,7 @@ mod tests {
|
||||
store: store.clone(),
|
||||
default_cwd: Some("/tmp".into()),
|
||||
workspace_root: None,
|
||||
memory: None,
|
||||
max_iters: 8,
|
||||
progress: None,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user