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,
|
||||
},
|
||||
|
||||
@@ -30,6 +30,7 @@ pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
|
||||
service,
|
||||
store: None,
|
||||
workspace_root: default_workspace_root(),
|
||||
memory: None,
|
||||
},
|
||||
auth,
|
||||
)
|
||||
@@ -42,12 +43,14 @@ pub fn router_with_store(
|
||||
store: Arc<dyn Store>,
|
||||
auth: AuthConfig,
|
||||
workspace_root: std::path::PathBuf,
|
||||
memory: Option<Arc<crate::memory::MemoryService>>,
|
||||
) -> Router {
|
||||
build_router(
|
||||
AppState {
|
||||
service,
|
||||
store: Some(store),
|
||||
workspace_root,
|
||||
memory,
|
||||
},
|
||||
auth,
|
||||
)
|
||||
@@ -217,6 +220,9 @@ pub(crate) struct AppState {
|
||||
pub(crate) service: ChatService,
|
||||
pub(crate) store: Option<Arc<dyn Store>>,
|
||||
pub(crate) workspace_root: std::path::PathBuf,
|
||||
/// Long-term semantic memory service (remember/recall/forget). None when it
|
||||
/// could not be opened; the agent then runs without the memory tools.
|
||||
pub(crate) memory: Option<Arc<crate::memory::MemoryService>>,
|
||||
}
|
||||
|
||||
/// An OpenAI error with the HTTP status the code implies.
|
||||
|
||||
+52
-3
@@ -164,7 +164,27 @@ pub(crate) async fn patch_session(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if let Some(settings) = body.settings {
|
||||
if let Some(mut settings) = body.settings {
|
||||
// One-way memory latch: once enabled it can never be turned off (OR merge),
|
||||
// so even a partial settings payload cannot accidentally disable it.
|
||||
let want_on = settings.memory_enabled;
|
||||
settings.memory_enabled = sess.settings.memory_enabled || want_on;
|
||||
// A FRESH enable requires the memory service AND a reachable embedder, so
|
||||
// the latch only flips on when the capability actually works.
|
||||
if want_on && !sess.settings.memory_enabled {
|
||||
let Some(m) = st.memory.clone() else {
|
||||
return Err(Error::bad_request(t("error.memory_unavailable", &[])));
|
||||
};
|
||||
let ok = tokio::task::spawn_blocking(move || m.embedder_reachable())
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
return Err(Error::bad_request(t(
|
||||
"error.memory_embedder_unreachable",
|
||||
&[],
|
||||
)));
|
||||
}
|
||||
}
|
||||
with_store(&st, move |s| s.update_settings(&id, &settings)).await?;
|
||||
}
|
||||
Ok(StatusCode::OK)
|
||||
@@ -597,9 +617,14 @@ pub(crate) async fn session_chat(
|
||||
}
|
||||
|
||||
// Agent mode: drive the model↔shell_exec loop, streaming progress events.
|
||||
let memory_available = st.memory.is_some();
|
||||
let memory_on = memory_available && sess.settings.memory_enabled;
|
||||
if body.agent {
|
||||
let mut tools = agent::agent_tools();
|
||||
if let Some(arr) = tools.as_array_mut() {
|
||||
if memory_on {
|
||||
arr.extend(agent::memory::memory_tools());
|
||||
}
|
||||
arr.extend(mcp_decls);
|
||||
}
|
||||
req.tools = Some(tools);
|
||||
@@ -610,6 +635,7 @@ pub(crate) async fn session_chat(
|
||||
let sid = id.clone();
|
||||
let folder = sess.folder.clone();
|
||||
let ws_root = st.workspace_root.clone();
|
||||
let memory = if memory_on { st.memory.clone() } else { None };
|
||||
let tx_model = tx.clone();
|
||||
let svc_pw = st.service.clone();
|
||||
let store_pw = store.clone();
|
||||
@@ -684,6 +710,7 @@ pub(crate) async fn session_chat(
|
||||
store: store2,
|
||||
default_cwd: folder,
|
||||
workspace_root: Some(ws_root),
|
||||
memory,
|
||||
max_iters: agent::MAX_ITERS,
|
||||
progress: Some(tx.clone()),
|
||||
},
|
||||
@@ -696,7 +723,14 @@ pub(crate) async fn session_chat(
|
||||
message: env.error.message,
|
||||
});
|
||||
}
|
||||
schedule_prewarm(svc_pw, store_pw, sid.clone(), true, notepad_fp_pw);
|
||||
schedule_prewarm(
|
||||
svc_pw,
|
||||
store_pw,
|
||||
sid.clone(),
|
||||
true,
|
||||
notepad_fp_pw,
|
||||
memory_available,
|
||||
);
|
||||
});
|
||||
let events = UnboundedReceiverStream::new(rx)
|
||||
.map(|ev| {
|
||||
@@ -763,7 +797,14 @@ pub(crate) async fn session_chat(
|
||||
let tail = futures::stream::once(async move {
|
||||
let a = acc_end.lock().unwrap().clone();
|
||||
persist_assistant(&store, &sid, &a, prompt_len).await;
|
||||
schedule_prewarm(svc_pw, store.clone(), sid.clone(), agent_pw, notepad_fp_pw);
|
||||
schedule_prewarm(
|
||||
svc_pw,
|
||||
store.clone(),
|
||||
sid.clone(),
|
||||
agent_pw,
|
||||
notepad_fp_pw,
|
||||
memory_available,
|
||||
);
|
||||
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
|
||||
});
|
||||
Sse::new(events.chain(tail))
|
||||
@@ -800,6 +841,7 @@ pub(crate) async fn session_chat(
|
||||
id.clone(),
|
||||
body.agent,
|
||||
notepad_fp.clone(),
|
||||
memory_available,
|
||||
);
|
||||
Json(resp).into_response()
|
||||
}
|
||||
@@ -860,6 +902,7 @@ fn schedule_prewarm(
|
||||
sid: String,
|
||||
agent_mode: bool,
|
||||
notepad_fp: String,
|
||||
memory_available: bool,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
if !service.is_idle() {
|
||||
@@ -927,9 +970,15 @@ fn schedule_prewarm(
|
||||
messages: prefix,
|
||||
..Default::default()
|
||||
};
|
||||
// Match the NEXT turn's surface: the latch is read from the freshly loaded
|
||||
// session (service availability is stable for the server's lifetime).
|
||||
let memory_on = memory_available && sess.settings.memory_enabled;
|
||||
if agent_mode {
|
||||
let mut tools = agent::agent_tools();
|
||||
if let Some(arr) = tools.as_array_mut() {
|
||||
if memory_on {
|
||||
arr.extend(agent::memory::memory_tools());
|
||||
}
|
||||
arr.extend(mcp_decls);
|
||||
}
|
||||
req.tools = Some(tools);
|
||||
|
||||
@@ -120,6 +120,13 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub db_path: Option<String>,
|
||||
|
||||
/// Endpoint of the interim embedder service (vetta-embedder, BGE-M3 dense).
|
||||
/// A non-secret deployment endpoint, like `exe`/`host`/`port`. Defaults to the
|
||||
/// free-to-use Altair instance; the Sogliola `localhost:8091` instance is
|
||||
/// reserved for Iris and must not be used here.
|
||||
#[serde(default)]
|
||||
pub memory_embedder_url: Option<String>,
|
||||
|
||||
/// Keys we understand but don't act on yet are NOT listed above, so they
|
||||
/// arrive here untouched — the "ignore what isn't ours" guarantee.
|
||||
#[serde(flatten)]
|
||||
@@ -265,6 +272,19 @@ impl Config {
|
||||
self.workspace_root().join("uploads")
|
||||
}
|
||||
|
||||
/// Semantic index directory: `<root>/memory` (the Qdrant Edge shard, a
|
||||
/// rebuildable/disposable index over the authoritative Store records).
|
||||
pub fn memory_dir(&self) -> PathBuf {
|
||||
self.workspace_root().join("memory")
|
||||
}
|
||||
|
||||
/// Effective embedder endpoint: config > the free Altair instance (.18).
|
||||
pub fn memory_embedder_url(&self) -> String {
|
||||
self.memory_embedder_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| "http://192.168.50.18:8091".to_string())
|
||||
}
|
||||
|
||||
/// Effective language: config > `it`.
|
||||
pub fn language(&self) -> String {
|
||||
self.language.clone().unwrap_or_else(|| "it".to_string())
|
||||
@@ -445,9 +465,23 @@ mod tests {
|
||||
assert_eq!(cfg.sessions_dir(), PathBuf::from("/tmp/fwk/sessions"));
|
||||
assert_eq!(cfg.data_dir(), PathBuf::from("/tmp/fwk/data"));
|
||||
assert_eq!(cfg.upload_dir(), PathBuf::from("/tmp/fwk/uploads"));
|
||||
assert_eq!(cfg.memory_dir(), PathBuf::from("/tmp/fwk/memory"));
|
||||
assert_eq!(
|
||||
cfg.gui_db_path(),
|
||||
PathBuf::from("/tmp/fwk/data/sessions.db")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_embedder_url_default_and_override() {
|
||||
let cfg = Config::parse(r#"{"exe":"/x/e"}"#, "test").unwrap();
|
||||
// default is the free Altair instance, NOT localhost (reserved for Iris)
|
||||
assert_eq!(cfg.memory_embedder_url(), "http://192.168.50.18:8091");
|
||||
let cfg2 = Config::parse(
|
||||
r#"{"exe":"/x/e","memory_embedder_url":"http://10.0.0.9:8091"}"#,
|
||||
"test",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cfg2.memory_embedder_url(), "http://10.0.0.9:8091");
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ pub mod engine;
|
||||
pub mod i18n;
|
||||
pub mod inkling;
|
||||
pub mod mcp;
|
||||
pub mod memory;
|
||||
pub mod name;
|
||||
pub mod render;
|
||||
pub mod store;
|
||||
|
||||
+23
-1
@@ -199,7 +199,29 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
|
||||
if matches!(store.get_defaults(), Ok(None)) {
|
||||
let _ = store.set_defaults(&cfg.default_settings());
|
||||
}
|
||||
let app = router_with_store(svc, store, auth, cfg.workspace_root());
|
||||
// Open the semantic memory service: the authoritative Store plus a rebuildable
|
||||
// Qdrant Edge index under <root>/memory. Fail-open — if it cannot be opened the
|
||||
// agent simply runs without the remember/recall/forget tools; the rest of the
|
||||
// GUI and the /v1 API are unaffected.
|
||||
let memory = match strata_ctl::memory::MemoryService::open(
|
||||
store.clone(),
|
||||
&cfg.memory_dir(),
|
||||
&cfg.memory_embedder_url(),
|
||||
) {
|
||||
Ok(m) => {
|
||||
println!(
|
||||
"memory: {} (embedder {})",
|
||||
cfg.memory_dir().display(),
|
||||
cfg.memory_embedder_url()
|
||||
);
|
||||
Some(Arc::new(m))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "semantic memory unavailable; remember/recall disabled");
|
||||
None
|
||||
}
|
||||
};
|
||||
let app = router_with_store(svc, store, auth, cfg.workspace_root(), memory);
|
||||
let host = cfg.bind_host(cli_host);
|
||||
let port = cfg.bind_port(cli_port);
|
||||
if !is_loopback_host(&host) && cfg.api_key.is_none() {
|
||||
|
||||
+454
@@ -0,0 +1,454 @@
|
||||
//! The semantic memory service: the control-layer seam over `strata-memory`.
|
||||
//!
|
||||
//! Architecture (ratified): the relational [`Store`] owns the AUTHORITATIVE
|
||||
//! records; the Qdrant Edge [`MemoryIndex`] is a rebuildable/disposable semantic
|
||||
//! layer over them. This service keeps the two in step and fails OPEN: a record
|
||||
//! is always persisted to the Store first, and indexing is deferred (not lost)
|
||||
//! when the embedder is unreachable. Recall falls back to a keyword scan of the
|
||||
//! Store when semantic search cannot embed the query, so memory stays useful
|
||||
//! offline. Vectors never leave this layer — callers get text + score only.
|
||||
//!
|
||||
//! Sync by design (the Store and the index are sync); the agent loop calls it
|
||||
//! from `tokio::task::spawn_blocking`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use strata_memory::{
|
||||
Embedder, Hit, HttpEmbedder, IndexError, MemoryIndex, MemoryRecord, BGE_M3_DIM,
|
||||
};
|
||||
|
||||
use crate::store::Store;
|
||||
|
||||
/// Embedder tag persisted alongside the index. Switching the embedder (or its
|
||||
/// quantization) changes this tag and forces a rebuild rather than silently
|
||||
/// mixing incompatible vectors. The interim backend is BGE-M3 dense q8 on Altair.
|
||||
pub const MODEL_ID: &str = "bge-m3-q8";
|
||||
|
||||
/// Fields the agent supplies to `remember`. `id`/`timestamp` are assigned here.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RememberInput {
|
||||
pub category: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
pub keywords: Vec<String>,
|
||||
pub scope: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
/// The semantic memory service. Holds the authoritative Store and the rebuildable
|
||||
/// index; all methods are sync and fail-open on embedder transport errors.
|
||||
pub struct MemoryService {
|
||||
store: Arc<dyn Store>,
|
||||
index: MemoryIndex,
|
||||
}
|
||||
|
||||
impl MemoryService {
|
||||
/// Open (or create) the service: build the interim HTTP embedder, open the
|
||||
/// shard at `dir`, and reconcile any Store records missing from the index.
|
||||
///
|
||||
/// On an embedder-model mismatch the stale shard is discarded and rebuilt
|
||||
/// from the Store (the index is disposable by design). Reconciliation is
|
||||
/// best-effort: if the embedder is down, missing records stay in the Store
|
||||
/// and are indexed later — opening still succeeds.
|
||||
pub fn open(store: Arc<dyn Store>, dir: &Path, embedder_url: &str) -> Result<Self> {
|
||||
let embedder: Arc<dyn Embedder> =
|
||||
Arc::new(HttpEmbedder::new(embedder_url, MODEL_ID, BGE_M3_DIM));
|
||||
let index = match MemoryIndex::open(dir, BGE_M3_DIM, MODEL_ID, embedder.clone()) {
|
||||
Ok(ix) => ix,
|
||||
Err(IndexError::ModelMismatch { index: old, .. }) => {
|
||||
tracing::warn!(
|
||||
old_model = %old,
|
||||
new_model = MODEL_ID,
|
||||
"memory index built with a different embedder: rebuilding from the Store"
|
||||
);
|
||||
std::fs::remove_dir_all(dir)
|
||||
.with_context(|| format!("discarding stale memory index {}", dir.display()))?;
|
||||
MemoryIndex::open(dir, BGE_M3_DIM, MODEL_ID, embedder)
|
||||
.context("recreating the memory index")?
|
||||
}
|
||||
Err(e) => return Err(e).context("opening the memory index"),
|
||||
};
|
||||
let svc = Self { store, index };
|
||||
if let Err(e) = svc.reconcile() {
|
||||
tracing::warn!(error = %e, "memory index reconciliation failed (will retry on next open)");
|
||||
}
|
||||
Ok(svc)
|
||||
}
|
||||
|
||||
/// Wrap an already-built index (tests inject a stub embedder this way).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_index(store: Arc<dyn Store>, index: MemoryIndex) -> Self {
|
||||
Self { store, index }
|
||||
}
|
||||
|
||||
pub fn model_id(&self) -> &str {
|
||||
self.index.model_id()
|
||||
}
|
||||
|
||||
pub fn dim(&self) -> usize {
|
||||
self.index.dim()
|
||||
}
|
||||
|
||||
/// Whether the embedder responds — the gate for enabling memory on a session
|
||||
/// (the one-way opt-in latch only flips on when the capability actually works).
|
||||
pub fn embedder_reachable(&self) -> bool {
|
||||
self.index.embedder_reachable()
|
||||
}
|
||||
|
||||
/// Persist a new memory: authoritative Store write FIRST, then index it.
|
||||
/// Indexing failures (embedder unreachable) are logged and deferred, never
|
||||
/// losing the record — it remains in the Store and is reconciled later.
|
||||
pub fn remember(&self, input: RememberInput) -> Result<MemoryRecord> {
|
||||
let record = MemoryRecord {
|
||||
id: new_id("mem"),
|
||||
category: input.category,
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
keywords: input.keywords,
|
||||
scope: input.scope,
|
||||
timestamp: now_secs().to_string(),
|
||||
source: input.source,
|
||||
};
|
||||
self.store
|
||||
.upsert_memory_record(&record)
|
||||
.context("persisting the memory record to the Store")?;
|
||||
match self.index.upsert(&record) {
|
||||
Ok(()) => {
|
||||
let _ = self.index.flush();
|
||||
}
|
||||
Err(e) => tracing::warn!(
|
||||
error = %e, id = %record.id,
|
||||
"memory saved to the Store but indexing deferred (embedder unreachable?)"
|
||||
),
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Semantic recall. When the query cannot be embedded (embedder down), fall
|
||||
/// OPEN to a keyword scan of the authoritative Store so memory stays useful.
|
||||
pub fn recall(
|
||||
&self,
|
||||
query: &str,
|
||||
top_k: usize,
|
||||
threshold: f32,
|
||||
category: Option<&str>,
|
||||
scope: Option<&str>,
|
||||
) -> Result<Vec<Hit>> {
|
||||
match self.index.search(query, top_k, threshold, category, scope) {
|
||||
Ok(hits) => Ok(hits),
|
||||
Err(IndexError::Embed(e)) => {
|
||||
tracing::warn!(error = %e, "semantic recall unavailable: keyword fallback over the Store");
|
||||
self.keyword_fallback(query, top_k, category, scope)
|
||||
}
|
||||
Err(e) => Err(e).context("semantic recall"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget a memory: remove the authoritative record, then soft-delete its
|
||||
/// point (tombstone) so it is excluded from recall but retained for rebuild.
|
||||
pub fn forget(&self, id: &str) -> Result<bool> {
|
||||
let existed = self
|
||||
.store
|
||||
.delete_memory_record(id)
|
||||
.context("deleting the memory record from the Store")?;
|
||||
if existed {
|
||||
match self.index.mark_dead(id) {
|
||||
Ok(()) => {
|
||||
let _ = self.index.flush();
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, id, "memory deleted but tombstoning deferred"),
|
||||
}
|
||||
}
|
||||
Ok(existed)
|
||||
}
|
||||
|
||||
/// Forget a record ONLY if it belongs to `scope` (per-session isolation): a
|
||||
/// session must not be able to delete another session's memories by guessing
|
||||
/// an id. Returns false when the id is absent or owned by a different scope.
|
||||
pub fn forget_in_scope(&self, id: &str, scope: &str) -> Result<bool> {
|
||||
match self.store.get_memory_record(id)? {
|
||||
Some(r) if r.scope == scope => self.forget(id),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Index any Store records missing from the shard (saved while the embedder
|
||||
/// was down, or after a rebuild). Best-effort: stops on an embedder transport
|
||||
/// error rather than hammering an unreachable service; returns how many were
|
||||
/// indexed. Tombstoned ids count as present so they are not resurrected.
|
||||
pub fn reconcile(&self) -> Result<usize> {
|
||||
let indexed: HashSet<String> = self.index.indexed_ids()?.into_iter().collect();
|
||||
let mut n = 0usize;
|
||||
for record in self.store.list_memory_records()? {
|
||||
if indexed.contains(&record.id) {
|
||||
continue;
|
||||
}
|
||||
match self.index.upsert(&record) {
|
||||
Ok(()) => n += 1,
|
||||
Err(IndexError::Embed(e)) => {
|
||||
tracing::warn!(error = %e, "reconciliation paused: embedder unreachable");
|
||||
break;
|
||||
}
|
||||
Err(e) => return Err(e).context("reconciling the memory index"),
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
let _ = self.index.flush();
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Naive keyword recall over the authoritative Store (offline fallback).
|
||||
/// Scores by how many query terms appear in title + content + keywords.
|
||||
fn keyword_fallback(
|
||||
&self,
|
||||
query: &str,
|
||||
top_k: usize,
|
||||
category: Option<&str>,
|
||||
scope: Option<&str>,
|
||||
) -> Result<Vec<Hit>> {
|
||||
let terms: Vec<String> = query
|
||||
.to_lowercase()
|
||||
.split_whitespace()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let mut hits = Vec::new();
|
||||
for record in self.store.list_memory_records()? {
|
||||
if let Some(c) = category {
|
||||
if record.category != c {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(s) = scope {
|
||||
if record.scope != s {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let hay = format!(
|
||||
"{} {} {}",
|
||||
record.title,
|
||||
record.content,
|
||||
record.keywords.join(" ")
|
||||
)
|
||||
.to_lowercase();
|
||||
let score = terms.iter().filter(|t| hay.contains(t.as_str())).count();
|
||||
if score > 0 {
|
||||
hits.push(Hit {
|
||||
record,
|
||||
score: score as f32,
|
||||
});
|
||||
}
|
||||
}
|
||||
hits.sort_by(|a, b| {
|
||||
b.score
|
||||
.partial_cmp(&a.score)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
});
|
||||
hits.truncate(top_k);
|
||||
Ok(hits)
|
||||
}
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Unique, sortable-enough id without an extra dependency (nanos + counter),
|
||||
/// mirroring the Store's own generator.
|
||||
fn new_id(prefix: &str) -> String {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{prefix}_{nanos:016x}{n:08x}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::store::SqliteStore;
|
||||
use strata_memory::EmbedError;
|
||||
|
||||
/// Deterministic embedder: known texts map to orthogonal unit vectors.
|
||||
struct StubEmbedder;
|
||||
impl Embedder for StubEmbedder {
|
||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
Ok(texts
|
||||
.iter()
|
||||
.map(|t| match *t {
|
||||
"alpha" => vec![1.0, 0.0, 0.0, 0.0],
|
||||
"beta" => vec![0.0, 1.0, 0.0, 0.0],
|
||||
_ => vec![0.0, 0.0, 1.0, 0.0],
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
fn dim(&self) -> usize {
|
||||
4
|
||||
}
|
||||
fn model_id(&self) -> &str {
|
||||
"stub"
|
||||
}
|
||||
}
|
||||
|
||||
/// Always fails transport (simulates an unreachable embedder).
|
||||
struct DownEmbedder;
|
||||
impl Embedder for DownEmbedder {
|
||||
fn embed(&self, _: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
Err(EmbedError::Transport("connection refused".into()))
|
||||
}
|
||||
fn dim(&self) -> usize {
|
||||
4
|
||||
}
|
||||
fn model_id(&self) -> &str {
|
||||
"stub"
|
||||
}
|
||||
}
|
||||
|
||||
fn store() -> Arc<dyn Store> {
|
||||
Arc::new(SqliteStore::open_in_memory().unwrap())
|
||||
}
|
||||
|
||||
fn service(dir: &Path, embedder: Arc<dyn Embedder>) -> MemoryService {
|
||||
let index = MemoryIndex::open(dir, 4, "stub", embedder).unwrap();
|
||||
MemoryService::from_index(store(), index)
|
||||
}
|
||||
|
||||
fn input(content: &str) -> RememberInput {
|
||||
RememberInput {
|
||||
category: "facts".into(),
|
||||
title: content.into(),
|
||||
content: content.into(),
|
||||
keywords: vec![],
|
||||
scope: "global".into(),
|
||||
source: "test".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_persists_to_store_and_index() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let svc = service(tmp.path(), Arc::new(StubEmbedder));
|
||||
let rec = svc.remember(input("alpha")).unwrap();
|
||||
// Authoritative Store has it.
|
||||
assert!(svc.store.get_memory_record(&rec.id).unwrap().is_some());
|
||||
// Semantic recall finds it (cosine 1.0 for the identical text).
|
||||
let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].record.id, rec.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_fails_open_when_embedder_down() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let svc = service(tmp.path(), Arc::new(DownEmbedder));
|
||||
// Indexing fails, but the record is still persisted (fail-open).
|
||||
let rec = svc.remember(input("alpha")).unwrap();
|
||||
assert!(svc.store.get_memory_record(&rec.id).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recall_falls_back_to_keywords_when_embedder_down() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let svc = service(tmp.path(), Arc::new(DownEmbedder));
|
||||
// Seed the authoritative Store directly (no index, embedder is down).
|
||||
let rec = MemoryRecord {
|
||||
id: "m1".into(),
|
||||
category: "facts".into(),
|
||||
title: "Il gatto nero".into(),
|
||||
content: "Il gatto nero salta sul tavolo".into(),
|
||||
keywords: vec!["gatto".into()],
|
||||
scope: "global".into(),
|
||||
timestamp: "0".into(),
|
||||
source: "test".into(),
|
||||
};
|
||||
svc.store.upsert_memory_record(&rec).unwrap();
|
||||
// Semantic search cannot embed -> keyword fallback finds the record.
|
||||
let hits = svc.recall("gatto tavolo", 5, 0.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].record.id, "m1");
|
||||
assert!(hits[0].score >= 2.0, "both terms matched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forget_removes_from_store_and_excludes_from_recall() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let svc = service(tmp.path(), Arc::new(StubEmbedder));
|
||||
let rec = svc.remember(input("alpha")).unwrap();
|
||||
assert!(svc.forget(&rec.id).unwrap());
|
||||
assert!(svc.store.get_memory_record(&rec.id).unwrap().is_none());
|
||||
let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert!(hits.is_empty(), "forgotten record must be excluded");
|
||||
// Forgetting an absent id is a no-op (returns false).
|
||||
assert!(!svc.forget("nope").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_indexes_store_records_missing_from_index() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let svc = service(tmp.path(), Arc::new(StubEmbedder));
|
||||
// Put a record in the Store WITHOUT indexing it (as if saved while down).
|
||||
let rec = MemoryRecord {
|
||||
id: "m1".into(),
|
||||
category: "facts".into(),
|
||||
title: "alpha".into(),
|
||||
content: "alpha".into(),
|
||||
keywords: vec![],
|
||||
scope: "global".into(),
|
||||
timestamp: "0".into(),
|
||||
source: "test".into(),
|
||||
};
|
||||
svc.store.upsert_memory_record(&rec).unwrap();
|
||||
assert!(svc.recall("alpha", 5, 0.0, None, None).unwrap().is_empty());
|
||||
// Reconciliation indexes the missing record.
|
||||
assert_eq!(svc.reconcile().unwrap(), 1);
|
||||
let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
// Idempotent: nothing left to reconcile.
|
||||
assert_eq!(svc.reconcile().unwrap(), 0);
|
||||
}
|
||||
|
||||
/// End-to-end against the real Altair BGE-M3 embedder: open -> remember ->
|
||||
/// semantic recall (paraphrase) -> forget. Run with `--ignored` on the LAN.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_remember_recall_forget_altair() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
let svc = MemoryService::open(store, tmp.path(), "http://192.168.50.18:8091").unwrap();
|
||||
let rec = svc
|
||||
.remember(RememberInput {
|
||||
category: "project_fact".into(),
|
||||
title: "Embedder di riserva".into(),
|
||||
content:
|
||||
"Il servizio di embedding BGE-M3 di riserva gira su Altair alla porta 8091."
|
||||
.into(),
|
||||
keywords: vec!["embedder".into(), "altair".into()],
|
||||
scope: "global".into(),
|
||||
source: "test".into(),
|
||||
})
|
||||
.unwrap();
|
||||
// A natural-language paraphrase must retrieve the fact semantically.
|
||||
let hits = svc
|
||||
.recall("dove gira il modello di embedding?", 5, 0.3, None, None)
|
||||
.unwrap();
|
||||
assert!(!hits.is_empty(), "semantic recall should find the fact");
|
||||
assert_eq!(hits[0].record.id, rec.id);
|
||||
assert!(hits[0].score > 0.3, "score={}", hits[0].score);
|
||||
// Forget excludes it from subsequent recall.
|
||||
assert!(svc.forget(&rec.id).unwrap());
|
||||
let hits = svc
|
||||
.recall("dove gira il modello di embedding?", 5, 0.3, None, None)
|
||||
.unwrap();
|
||||
assert!(hits.iter().all(|h| h.record.id != rec.id));
|
||||
}
|
||||
}
|
||||
+167
@@ -60,6 +60,13 @@ pub struct SessionSettings {
|
||||
/// curated tool selection lives here, copy-on-create like other settings.
|
||||
#[serde(default)]
|
||||
pub mcp_enabled: BTreeMap<String, Vec<String>>,
|
||||
/// Per-session ONE-WAY opt-in for semantic memory (remember/recall/forget).
|
||||
/// Off by default; once enabled it can never be disabled (irreversible latch,
|
||||
/// like `name_locked`), because memories already written must stay recallable.
|
||||
/// Enabling is gated on the memory service being present and the embedder
|
||||
/// reachable. Copy-on-create like other settings; the global default is off.
|
||||
#[serde(default)]
|
||||
pub memory_enabled: bool,
|
||||
}
|
||||
|
||||
impl SessionSettings {
|
||||
@@ -85,6 +92,8 @@ impl SessionSettings {
|
||||
} else {
|
||||
self.mcp_enabled.clone()
|
||||
},
|
||||
// One-way latch: once on, stays on (OR merge).
|
||||
memory_enabled: self.memory_enabled || base.memory_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +305,15 @@ pub trait Store: Send + Sync {
|
||||
/// Persist the discovered tool surface (JSON array of rmcp `Tool`) for a
|
||||
/// connector, refreshed by live discovery. No-op if the connector is absent.
|
||||
fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()>;
|
||||
/// Upsert an authoritative semantic-memory record. The relational Store is
|
||||
/// the source of truth; the Qdrant Edge index is a rebuildable copy over it.
|
||||
fn upsert_memory_record(&self, record: &strata_memory::MemoryRecord) -> Result<()>;
|
||||
/// Fetch one memory record by id.
|
||||
fn get_memory_record(&self, id: &str) -> Result<Option<strata_memory::MemoryRecord>>;
|
||||
/// All memory records (used to rebuild the semantic index after an embedder swap).
|
||||
fn list_memory_records(&self) -> Result<Vec<strata_memory::MemoryRecord>>;
|
||||
/// Remove a memory record; returns whether it existed.
|
||||
fn delete_memory_record(&self, id: &str) -> Result<bool>;
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
@@ -375,6 +393,18 @@ CREATE TABLE IF NOT EXISTS mcp_connectors (
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS memory_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
category TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
keywords TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memory_cat_scope ON memory_records(category, scope);
|
||||
";
|
||||
|
||||
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
|
||||
@@ -970,6 +1000,70 @@ impl Store for SqliteStore {
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn upsert_memory_record(&self, record: &strata_memory::MemoryRecord) -> Result<()> {
|
||||
let keywords = serde_json::to_string(&record.keywords)?;
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"INSERT INTO memory_records (id, category, title, content, keywords, scope, timestamp, source, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
category=?2, title=?3, content=?4, keywords=?5, scope=?6, timestamp=?7, source=?8, updated_at=?9",
|
||||
params![
|
||||
record.id, record.category, record.title, record.content, keywords,
|
||||
record.scope, record.timestamp, record.source, now_secs()
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_memory_record(&self, id: &str) -> Result<Option<strata_memory::MemoryRecord>> {
|
||||
let conn = self.lock();
|
||||
conn.query_row(
|
||||
"SELECT id, category, title, content, keywords, scope, timestamp, source
|
||||
FROM memory_records WHERE id = ?1",
|
||||
params![id],
|
||||
row_to_memory,
|
||||
)
|
||||
.optional()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn list_memory_records(&self) -> Result<Vec<strata_memory::MemoryRecord>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, category, title, content, keywords, scope, timestamp, source
|
||||
FROM memory_records ORDER BY updated_at DESC",
|
||||
)?;
|
||||
let rows = stmt.query_map([], row_to_memory)?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
out.push(r?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn delete_memory_record(&self, id: &str) -> Result<bool> {
|
||||
let conn = self.lock();
|
||||
let n = conn.execute("DELETE FROM memory_records WHERE id = ?1", params![id])?;
|
||||
Ok(n > 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a `memory_records` row to the shared record shape (keywords is a JSON array).
|
||||
fn row_to_memory(row: &rusqlite::Row<'_>) -> rusqlite::Result<strata_memory::MemoryRecord> {
|
||||
let keywords_json: String = row.get(4)?;
|
||||
let keywords = serde_json::from_str(&keywords_json).unwrap_or_default();
|
||||
Ok(strata_memory::MemoryRecord {
|
||||
id: row.get(0)?,
|
||||
category: row.get(1)?,
|
||||
title: row.get(2)?,
|
||||
content: row.get(3)?,
|
||||
keywords,
|
||||
scope: row.get(5)?,
|
||||
timestamp: row.get(6)?,
|
||||
source: row.get(7)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1111,6 +1205,46 @@ mod tests {
|
||||
assert!(s.mcp_connectors().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_record_crud_and_upsert() {
|
||||
let s = store();
|
||||
assert!(s.list_memory_records().unwrap().is_empty());
|
||||
let rec = strata_memory::MemoryRecord {
|
||||
id: "mem_1".into(),
|
||||
category: "facts".into(),
|
||||
title: "Gatto".into(),
|
||||
content: "Il gatto nero salta sul tavolo".into(),
|
||||
keywords: vec!["gatto".into(), "tavolo".into()],
|
||||
scope: "global".into(),
|
||||
timestamp: "0".into(),
|
||||
source: "test".into(),
|
||||
};
|
||||
s.upsert_memory_record(&rec).unwrap();
|
||||
let got = s.get_memory_record("mem_1").unwrap().unwrap();
|
||||
assert_eq!(got, rec);
|
||||
assert_eq!(
|
||||
got.keywords,
|
||||
vec!["gatto".to_string(), "tavolo".to_string()]
|
||||
);
|
||||
|
||||
// Upsert updates in place, keeps a single row.
|
||||
let rec2 = strata_memory::MemoryRecord {
|
||||
content: "Il gatto dorme".into(),
|
||||
title: "Gatto 2".into(),
|
||||
..rec.clone()
|
||||
};
|
||||
s.upsert_memory_record(&rec2).unwrap();
|
||||
assert_eq!(s.list_memory_records().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
s.get_memory_record("mem_1").unwrap().unwrap().content,
|
||||
"Il gatto dorme"
|
||||
);
|
||||
|
||||
assert!(s.delete_memory_record("mem_1").unwrap());
|
||||
assert!(!s.delete_memory_record("mem_1").unwrap());
|
||||
assert!(s.get_memory_record("mem_1").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stats_breakdown_counts_tools_and_orders_sessions() {
|
||||
let s = store();
|
||||
@@ -1277,6 +1411,39 @@ mod tests {
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_latch_is_one_way_and_persists() {
|
||||
let s = store();
|
||||
let sess = s
|
||||
.create_session("Chat", "m", &SessionSettings::default())
|
||||
.unwrap();
|
||||
// Off by default.
|
||||
assert!(!sess.settings.memory_enabled);
|
||||
// Enable via the session's own settings instance.
|
||||
let mut on = sess.settings.clone();
|
||||
on.memory_enabled = true;
|
||||
s.update_settings(&sess.id, &on).unwrap();
|
||||
assert!(
|
||||
s.get_session(&sess.id)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.settings
|
||||
.memory_enabled
|
||||
);
|
||||
// Overlay is a one-way OR: a false override can never turn it back off.
|
||||
let off = SessionSettings {
|
||||
memory_enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(off.overlay(&on).memory_enabled);
|
||||
// Two fresh (off) settings stay off.
|
||||
assert!(
|
||||
!SessionSettings::default()
|
||||
.overlay(&SessionSettings::default())
|
||||
.memory_enabled
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_adds_columns_to_old_schema() {
|
||||
// Simulate a pre-existing database without the newer columns.
|
||||
|
||||
Reference in new issue
Block a user