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:
adm committed 2026-11-30 11:37:48 +01:00
1 parent 6898cdf113
commit f74d53e446
24 files changed
+4853 -67

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
/target
.idea/
/upstream
Generated
+1930 -13
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -5,6 +5,14 @@ edition = "2021"
description = "Rust control layer for the Strata inference engine: OpenAI-compatible HTTP API over the engine's line protocol"
license = "MIT"
[workspace]
# strata-ctl is both the root package and the workspace root. `strata-memory` is a
# co-located crate (promotable to its own repo later without a rewrite). `upstream/`
# is the reference Strata checkout and must never be pulled into the build.
members = ["strata-memory"]
exclude = ["upstream"]
resolver = "2"
[dependencies]
anyhow = "1"
thiserror = "2"
@@ -29,8 +37,21 @@ rust-embed = "8"
pulldown-cmark = "0.13.6"
pulldown-latex = "0.8.0"
rmcp = { version = "3.12.0", default-features = false, features = ["client", "transport-streamable-http-client-reqwest", "reqwest"] }
# Semantic memory capability (embedder seam + Qdrant Edge index + symbolic vector
# workspace). Co-located workspace crate; strata-ctl is its consumer.
strata-memory = { path = "strata-memory" }
[dev-dependencies]
http-body-util = "0.1.5"
tempfile = "3"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["util"] }
# Keep FULL debuginfo, but in separate .dwo files written once per crate instead of
# duplicated into every linked binary. This workspace statically links a heavy tree
# (qdrant-edge, tokenizers, crypto/regex natives) into 50+ test/example binaries; with
# embedded debuginfo each link wrote hundreds of MB, hammering the NVMe. `unpacked`
# preserves IDE debugging while cutting per-link write volume dramatically. Applies
# to the `test` profile too (it inherits `dev`).
[profile.dev]
split-debuginfo = "unpacked"
+64 -46
View File
@@ -201,17 +201,20 @@ advanced settings to grow on top.
**Framework root.** All persistent state lives under `~/.strata-ctl/` (the Linux
user's home; override with `workspace_root`), separated by content type:
`sessions/<name>/` (agent workspace folders), `data/` (the SQLite database),
`uploads/` (uploaded files). A legacy DB at `~/.config/strata-ctl/sessions.db` is
`uploads/` (uploaded files), `memory/` (the rebuildable semantic index). A legacy
DB at `~/.config/strata-ctl/sessions.db` is
copied into `data/` once on first run (the original is left in place).
## Agent mode
The GUI model can **act**, not just chat. Tools are **always on** — there is no
toggle, because the framework could not function without them. The agent's tool
The GUI model can **act**, not just chat. The core tools are **always on** — there
is no toggle, because the framework could not function without them. The agent's tool
surface is small and deliberate: **`shell_exec`** (a shell is universal: file ops,
programs, system inspection, web via curl, git, …), **`notepad`** (agent-curated
persistent memory, see below) and **`share_file`** (hand the user a download link
for a file on its filesystem, see below). A bounded server-side loop drives
for a file on its filesystem, see below). A session that opts into **semantic
memory** additionally gets `remember` / `recall` / `forget` (see **Semantic vector
memory** below). A bounded server-side loop drives
`model → shell_exec → result → model → … → final answer`, persisting the whole
trajectory and streaming progress events — `delta` (the model's thinking and final
answer, token by token), `tool_call` / `tool_result` (every command and its output
@@ -264,6 +267,12 @@ shared JSON config ──► InklingFormatter ──► Engine supervisor ──
per-turn `[SPEAKER]` provenance (prompt-only).
- `render` — server-side Markdown → sanitized HTML with LaTeX → native MathML
(`pulldown-cmark` + `pulldown-latex`) for assistant replies.
- `agent` — the bounded server-side tool loop: `shell_exec`, `notepad`,
`share_file`, MCP connectors and the per-session memory tools.
- `memory` — the semantic memory service: the authoritative `Store` plus a
rebuildable vector index, kept in step and fail-open. Backed by the
**`strata-memory`** workspace crate (swappable `Embedder` trait, HTTP BGE-M3
client, embedded Qdrant Edge index).
## Building and running
@@ -290,8 +299,9 @@ The config is the same JSON the other Strata tools use. Keys acted on here inclu
`max_new` (default generation budget, see below), `sampling`, `api_key`,
`allowed_hosts`, `db_path` (GUI session database), `workspace_root` (framework
root), `system_prompt` (general default), `language` (UI/prompt catalog, default
`it`), and the optional `startup_timeout_secs` / `silence_timeout_secs`. Everything
else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported
`it`), `memory_embedder_url` (semantic-memory embedder endpoint, default the free
Altair instance), and the optional `startup_timeout_secs` / `silence_timeout_secs`.
Everything else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported
as ignored — unknown keys never break startup.
**Generation budget (`max_new`).** When neither the request nor the session sets
@@ -318,7 +328,8 @@ later adaptation round.
## Status
Working and tested (191 tests, plus 3 real-file tests run on demand). Text, images,
Working and tested (238 tests passing; 6 ignored tests exercise the real engine,
embedder or files and run on demand). Text, images,
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
context, streaming, stats, **file/image upload**, **file download** (`share_file`
→ containment-checked attachment endpoint), assistant **Markdown/LaTeX
@@ -330,7 +341,10 @@ verified against the real chat template. A per-session **notepad** (agent-curate
`<NOTEPAD>` entries via the `notepad` tool) and a **sliding DIALOG window**
(message-count main area + buffer headroom, stepped KV-cache-friendly eviction at
turn boundaries, `window_start` persisted per session, full history never deleted)
are implemented and dogfooded live. A best-effort **cache pre-warm** (`GEN 0` over
are implemented and dogfooded live. Per-session **semantic memory**
(`remember` / `recall` / `forget` over an embedded Qdrant Edge index with BGE-M3
embeddings) is implemented and validated live against the Altair embedder. A
best-effort **cache pre-warm** (`GEN 0` over
the next turn's shared prefix during idle GPU time) hides the re-prefill on a
pending window rotation **or a notepad change** (pre-warm-on-change: the model
always sees a fresh notepad, no frozen header, no schema migration). The joint
@@ -365,22 +379,41 @@ routing, images via Vision) work. Per-tool host/container sandboxing was
## Roadmap
**Important TODO (suspended) — semantic vector memory.** A Qoder-style vector
database giving the agent long-term, cross-session semantic recall, useful well
beyond coding: embed and index conversation chunks, session notes, uploaded
documents and learned facts, then retrieve by similarity to inject the relevant
context into a turn, plus explicit *remember* / *semantic search* tools.
**Suspended on purpose** while we refine what already ships: the embedder/store
choice is costly to reverse, the leading candidate (vetta / BGE-M3) emits extra
modalities this application may not use and its suitability is unverified — so
the decision stays open rather than rushed.
### Semantic vector memory — implemented
Decided so far — requirements, not products:
The agent has long-term **semantic memory**: explicit `remember` / `recall` /
`forget` tools backed by dense-vector search, shipped as the `strata-memory`
workspace crate plus the control-layer seam (`src/memory.rs`). The ratified
choices:
- **One general engine + one general embedder.** A single multilingual,
domain-agnostic embedding model and a single vector engine must decently cover
any need; specialization lives *above* the index, never in a second engine or
model.
- **Embedder: BGE-M3 dense (1024-d)** via the team's `vetta-embedder` over HTTP
(`memory_embedder_url`, default the free Altair instance at
`http://192.168.50.18:8091`; C++/ggml, no Python/ONNX, no model bundled). The
`Embedder` trait keeps the backend swappable — an in-process embedder can
replace HTTP later without touching callers. Chosen after a live **fitness
probe** (representative memory corpus, labeled positive/negative queries:
top-1 20/20, MRR 1.000, clean positive/negative separation), which also
calibrated the default recall threshold to **0.45** cosine.
- **Index: Qdrant Edge** (`qdrant-edge`, embedded in-process — no server, single
binary preserved) under `~/.strata-ctl/memory/`. The SQLite `Store` stays
**authoritative**: the shard is a disposable semantic layer, rebuilt from the
Store whenever the persisted model-id sidecar (`strata_model.json`) mismatches
the current embedder — swapping embedders never mixes incompatible vectors.
- **Fail-open.** `remember` persists to the Store first; if the embedder is
unreachable, indexing is deferred and reconciled on the next open. `recall`
falls back to a keyword scan of the Store, so memory stays useful offline.
Vectors never leave the service — the model sees text + score only.
- **Per-session, one-way opt-in.** Memory is off by default (casual chat needs
none); each session's memories are **scoped to its id** — recall and forget
never cross sessions. Enabling it (GUI checkbox or `PATCH /api/sessions/{id}`)
is an **irreversible latch** like `name_locked`, so indexed memories are never
silently orphaned, and it requires the embedder to be reachable. The memory
tools are declared to the model only on memory-enabled sessions.
Still on the roadmap for memory:
- **Common / cross-session memory.** A shared scope on top of the per-session
one, when the isolation model has proven itself in use.
- **Layered directives.** An always-on **common core** (knowledge lifecycle:
recall when relevant, record durable lessons, verify against current evidence,
one topic per memory, prune duplicates) plus **enable-able domain guideline
@@ -389,28 +422,13 @@ Decided so far — requirements, not products:
carries structured config (categories/tags, chunking strategy, retrieval
filters/boosts, exposed tools) so the same general engine serves specialized
retrieval. Packs integrate with the per-session settings (copy-on-create) and
never override the core (core > pack).
- **Per-session, one-way opt-in.** Vector memory is off by default (casual chat
needs none); enabling it for a session is **irreversible** (a latch like
`name_locked`), so indexed memories are never silently orphaned by a later
disable. Enabling requires the embedder to be reachable.
Candidates under evaluation — the concrete engine / embedder / store choice is
**still open**, to be settled against the requirements above when we implement:
- **Embedder candidate: the team's `vetta-embedder`** (BGE-M3 dense 1024-d +
learned-sparse + ColBERT + a BGE-Reranker-v2-m3 cross-encoder sidecar), repo
`vetta-semantics`, already deployed on Linux hosts at `:8091` (C++/ggml, Vulkan
with CPU fallback, no Python/ONNX). Probed live: `/embed` and `/rerank` behave
correctly and multilingually; it would be reached over HTTP like the engine, so
no model is bundled. A strong candidate, **not yet chosen**. Alternative: a
small bundled multilingual embedder (ONNX/candle) if zero external services is
ever required.
- **Store candidate: sqlite-vec** inside the existing SQLite behind the `Store`
trait (dense KNN + metadata columns; recall → rerank → inject), keeping memory
co-located and transactional with sessions (single binary). Alternates behind
the same seam: the team's Qdrant (used by Iris) and the planned ArangoDB
(documents + vectors + search).
never override the core (core > pack). For now the tool guidance lives in the
tool declarations themselves; a dedicated prompt section will follow the
model's own feedback from real use.
- **One general engine + one general embedder** stays the rule: a single
multilingual, domain-agnostic embedding model and a single vector engine must
decently cover any need; specialization lives *above* the index, never in a
second engine or model.
### Sliding context window + per-session notepad
@@ -481,8 +499,8 @@ policy ships first), common/cross-session memories, a working-memory reference a
recap is out of scope**: summarizing what slides out needs an autonomous background
agent, whereas strata-ctl is reactive — the agent-curated notepad plus deterministic
truncation cover the resume anchor without a curator. The deep-retrieval complement
is the suspended semantic vector memory above; a simpler lexical recall over the
retained SQLite history can come first.
is the semantic vector memory above (implemented); a simpler lexical recall over
the retained SQLite history can still come as a lighter addition.
### Client surfaces (under consideration, not scheduled)
+2
View File
@@ -7,6 +7,8 @@
"error.name_locked": "The session name is immutable after the first interaction.",
"error.name_empty": "The name must not be empty.",
"error.session_not_found": "Session not found.",
"error.memory_unavailable": "Semantic memory is not available on this server.",
"error.memory_embedder_unreachable": "Cannot enable memory: the embedder is unreachable.",
"upload.bad_base64": "Invalid file data (base64).",
"upload.empty": "The file is empty.",
"upload.too_large": "The file exceeds the maximum allowed size.",
+2
View File
@@ -7,6 +7,8 @@
"error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.",
"error.name_empty": "Il nome non può essere vuoto.",
"error.session_not_found": "Sessione non trovata.",
"error.memory_unavailable": "La memoria semantica non è disponibile su questo server.",
"error.memory_embedder_unreachable": "Impossibile attivare la memoria: l'embedder non è raggiungibile.",
"upload.bad_base64": "Dati del file non validi (base64).",
"upload.empty": "Il file è vuoto.",
"upload.too_large": "Il file supera la dimensione massima consentita.",
+400
View File
@@ -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
View File
@@ -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,
},
+6
View File
@@ -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
View File
@@ -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);
+34
View File
@@ -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");
}
}
+1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "strata-memory"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "strata-ctl semantic memory: swappable Embedder trait + HTTP (BGE-M3) backend, Qdrant Edge index"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
# Blocking HTTP client (matches strata-ctl's existing choice). `json` enables send_json.
ureq = { version = "3.5.2", features = ["json"] }
# In-process Qdrant engine (single shard, disk-backed). The semantic index over
# memory records; rebuildable/disposable. Pinned: pre-1.0 beta.
qdrant-edge = "0.9"
[dev-dependencies]
# Temporary shard directories for hermetic in-process index tests.
tempfile = "3"
+501
View File
@@ -0,0 +1,501 @@
//! Semantic index over memory records, backed by an in-process Qdrant Edge shard.
//!
//! Architecture (ratified): the relational Store owns the authoritative records;
//! this index is a REBUILDABLE/DISPOSABLE semantic layer over them. Vectors live
//! only here; what reaches the model is text + score (see the symbolic-vector
//! principle). The payload carries a copy of the record so recall can render
//! without a Store round-trip; on embedder swap the whole shard is rebuilt.
//!
//! Dense-only baseline (no sparse/ColBERT). Soft-delete via a `dead` payload flag
//! filtered out of every query (pattern from our Iris Qdrant backend).
use std::path::{Path, PathBuf};
use std::sync::Arc;
use qdrant_edge::{
Condition, Distance, EdgeConfigBuilder, EdgeShard, EdgeVectorParams, FieldCondition, Filter,
Match, NamedQuery, Payload, PayloadOps, PointInsertOperations, PointOperations, PointStruct,
QueryEnum, QueryRequestBuilder, ScoringQuery, ScrollRequestBuilder, SetPayloadOp,
UpdateOperation, ValueVariants, VectorInternal, Vectors, WithPayloadInterface, WithVector,
};
use serde::{Deserialize, Serialize};
use crate::{EmbedError, Embedder};
/// Named dense vector in the shard.
pub const DENSE_VECTOR_NAME: &str = "dense";
/// Sidecar file recording which embedder built the shard (rebuild-on-swap guard).
const MODEL_FILE: &str = "strata_model.json";
/// The authoritative memory record shape. The relational Store owns these; the
/// index keeps a rebuildable copy in the point payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MemoryRecord {
pub id: String,
pub category: String,
pub title: String,
pub content: String,
pub keywords: Vec<String>,
pub scope: String,
pub timestamp: String,
pub source: String,
}
/// A recall hit: the record (text) + its relevance score. No vector ever leaves.
#[derive(Debug, Clone)]
pub struct Hit {
pub record: MemoryRecord,
pub score: f32,
}
#[derive(Debug, thiserror::Error)]
pub enum IndexError {
#[error("qdrant: {0}")]
Qdrant(String),
#[error("io: {0}")]
Io(String),
#[error("serde: {0}")]
Serde(String),
#[error(transparent)]
Embed(#[from] EmbedError),
#[error("model mismatch: index built with '{index}' (dim {index_dim}), current '{current}' (dim {current_dim}) — rebuild required")]
ModelMismatch {
index: String,
index_dim: usize,
current: String,
current_dim: usize,
},
}
impl From<qdrant_edge::OperationError> for IndexError {
fn from(e: qdrant_edge::OperationError) -> Self {
IndexError::Qdrant(e.to_string())
}
}
#[derive(Serialize, Deserialize)]
struct ModelTag {
model_id: String,
dim: usize,
}
/// In-process semantic index. Holds the embedder so `upsert`/`search` can embed
/// text directly; the caller never handles raw vectors.
pub struct MemoryIndex {
shard: EdgeShard,
dim: usize,
model_id: String,
embedder: Arc<dyn Embedder>,
}
impl MemoryIndex {
/// Open (or create) a shard at `path`. If it already exists, its embedder tag
/// must match `model_id`/`dim`, else [`IndexError::ModelMismatch`] is returned
/// so the caller can rebuild rather than mix incompatible vectors.
pub fn open(
path: impl AsRef<Path>,
dim: usize,
model_id: impl Into<String>,
embedder: Arc<dyn Embedder>,
) -> Result<Self, IndexError> {
let path = path.as_ref();
let model_id = model_id.into();
let model_file = path.join(MODEL_FILE);
if path.join("edge_config.json").exists() {
let shard = EdgeShard::load(path, None)?;
let tag = read_tag(&model_file)?;
if tag.model_id != model_id || tag.dim != dim {
return Err(IndexError::ModelMismatch {
index: tag.model_id,
index_dim: tag.dim,
current: model_id,
current_dim: dim,
});
}
Ok(Self {
shard,
dim,
model_id,
embedder,
})
} else {
std::fs::create_dir_all(path).map_err(|e| IndexError::Io(e.to_string()))?;
let config = EdgeConfigBuilder::new()
.vector(
DENSE_VECTOR_NAME,
EdgeVectorParams::builder(dim, Distance::Cosine).build(),
)
.build();
let shard = EdgeShard::new(path, config)?;
write_tag(
&model_file,
&ModelTag {
model_id: model_id.clone(),
dim,
},
)?;
Ok(Self {
shard,
dim,
model_id,
embedder,
})
}
}
pub fn dim(&self) -> usize {
self.dim
}
pub fn model_id(&self) -> &str {
&self.model_id
}
/// Probe whether the embedder responds (gate for enabling memory on a session).
/// One tiny embed; true iff it succeeds. Trait-generic, so it also works for the
/// future in-process embedder.
pub fn embedder_reachable(&self) -> bool {
self.embedder.embed(&["ping"]).is_ok()
}
/// Embed the record's content and upsert it (idempotent on the record id).
pub fn upsert(&self, record: &MemoryRecord) -> Result<(), IndexError> {
let vector = self
.embedder
.embed(&[record.content.as_str()])?
.pop()
.ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?;
if vector.len() != self.dim {
return Err(IndexError::Qdrant(format!(
"vector dim {} != index dim {}",
vector.len(),
self.dim
)));
}
let mut payload =
serde_json::to_value(record).map_err(|e| IndexError::Serde(e.to_string()))?;
payload["dead"] = serde_json::json!(false);
let point = PointStruct::new(
point_id(&record.id),
Vectors::new_named([(DENSE_VECTOR_NAME, vector)]),
payload,
);
self.shard.update(UpdateOperation::PointOperation(
PointOperations::UpsertPoints(PointInsertOperations::PointsList(vec![point.into()])),
))?;
Ok(())
}
/// Semantic recall: embed `query`, return up to `top_k` live records scoring
/// at least `threshold`, optionally filtered by category/scope. Tombstones
/// (`dead=true`) are always excluded.
pub fn search(
&self,
query: &str,
top_k: usize,
threshold: f32,
category: Option<&str>,
scope: Option<&str>,
) -> Result<Vec<Hit>, IndexError> {
let vector = self
.embedder
.embed(&[query])?
.pop()
.ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?;
self.search_vector(&vector, top_k, threshold, category, scope)
}
/// Vector-level search (also used by the symbolic workspace bridge: a
/// `$VEC[n]` resolved server-side is fed here without entering context).
pub fn search_vector(
&self,
vector: &[f32],
top_k: usize,
threshold: f32,
category: Option<&str>,
scope: Option<&str>,
) -> Result<Vec<Hit>, IndexError> {
let scoring = ScoringQuery::Vector(QueryEnum::Nearest(NamedQuery::new(
VectorInternal::from(vector.to_vec()),
DENSE_VECTOR_NAME.to_string(),
)));
let request = QueryRequestBuilder::new(top_k)
.query(scoring)
.filter(live_filter(category, scope))
.score_threshold(threshold)
.with_payload(WithPayloadInterface::Bool(true))
.with_vector(WithVector::Bool(false))
.build();
let points = self.shard.query(request)?;
let mut hits = Vec::with_capacity(points.len());
for p in points {
if let Some(record) = payload_to_record(p.payload.as_ref()) {
hits.push(Hit {
record,
score: p.score,
});
}
}
Ok(hits)
}
/// Soft-delete: mark the record `dead=true` so it is excluded from recall but
/// retained for rebuild/audit. The authoritative removal happens in the Store.
pub fn mark_dead(&self, id: &str) -> Result<(), IndexError> {
let payload = Payload::from(
serde_json::json!({ "dead": true })
.as_object()
.unwrap()
.clone(),
);
let op = SetPayloadOp {
payload,
points: None,
filter: Some(Filter::new_must(field_match_str("id", id))),
key: None,
};
self.shard
.update(UpdateOperation::PayloadOperation(PayloadOps::SetPayload(
op,
)))?;
Ok(())
}
/// Persist WAL + segments to disk.
pub fn flush(&self) -> Result<(), IndexError> {
self.shard.flush()?;
Ok(())
}
/// Every record id present in the shard, INCLUDING tombstones. Used by the
/// service to reconcile the authoritative Store against the index (find records
/// that were saved while the embedder was down) without re-embedding everything.
/// Tombstones are included on purpose so a soft-deleted record is not resurrected.
pub fn indexed_ids(&self) -> Result<Vec<String>, IndexError> {
let mut ids = Vec::new();
let mut offset = None;
loop {
let mut req = ScrollRequestBuilder::new()
.limit(256)
.with_payload(WithPayloadInterface::Bool(true))
.with_vector(WithVector::Bool(false));
if let Some(o) = offset {
req = req.offset(o);
}
let (records, next) = self.shard.scroll(req.build())?;
for r in records {
if let Some(id) = r
.payload
.as_ref()
.and_then(|p| p.0.get("id"))
.and_then(|v| v.as_str())
{
ids.push(id.to_string());
}
}
match next {
Some(o) => offset = Some(o),
None => break,
}
}
Ok(ids)
}
}
// ── helpers ──
/// Stable numeric point id from the record id (FNV-1a). The authoritative string
/// id is kept in the payload; the numeric id only needs to be deterministic so a
/// re-upsert of the same record overwrites its point.
fn point_id(id: &str) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in id.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h
}
fn field_match_str(key: &str, value: &str) -> Condition {
Condition::Field(FieldCondition::new_match(
key.parse().expect("valid payload key"),
Match::new_value(ValueVariants::String(value.to_string())),
))
}
fn dead_condition() -> Condition {
Condition::Field(FieldCondition::new_match(
"dead".parse().expect("valid payload key"),
Match::new_value(ValueVariants::Bool(true)),
))
}
/// Every query excludes tombstones; optional category/scope are `must` matches.
fn live_filter(category: Option<&str>, scope: Option<&str>) -> Filter {
let mut must = Vec::new();
if let Some(c) = category {
must.push(field_match_str("category", c));
}
if let Some(s) = scope {
must.push(field_match_str("scope", s));
}
Filter {
must: if must.is_empty() { None } else { Some(must) },
must_not: Some(vec![dead_condition()]),
..Default::default()
}
}
fn payload_to_record(payload: Option<&Payload>) -> Option<MemoryRecord> {
let map = &payload?.0;
let mut value = serde_json::Value::Object(map.clone());
if let Some(obj) = value.as_object_mut() {
obj.remove("dead");
}
serde_json::from_value(value).ok()
}
fn read_tag(path: &PathBuf) -> Result<ModelTag, IndexError> {
let data = std::fs::read_to_string(path).map_err(|e| IndexError::Io(e.to_string()))?;
serde_json::from_str(&data).map_err(|e| IndexError::Serde(e.to_string()))
}
fn write_tag(path: &Path, tag: &ModelTag) -> Result<(), IndexError> {
let data = serde_json::to_string(tag).map_err(|e| IndexError::Serde(e.to_string()))?;
std::fs::write(path, data).map_err(|e| IndexError::Io(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
/// Deterministic embedder: maps a few known texts 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"
}
}
fn record(id: &str, content: &str, category: &str) -> MemoryRecord {
MemoryRecord {
id: id.to_string(),
category: category.to_string(),
title: id.to_string(),
content: content.to_string(),
keywords: vec![],
scope: "global".to_string(),
timestamp: "0".to_string(),
source: "test".to_string(),
}
}
fn open(dir: &Path) -> MemoryIndex {
MemoryIndex::open(dir, 4, "stub", Arc::new(StubEmbedder)).unwrap()
}
#[test]
fn upsert_then_search_finds_record() {
let tmp = tempfile::tempdir().unwrap();
let idx = open(tmp.path());
idx.upsert(&record("r1", "alpha", "facts")).unwrap();
idx.flush().unwrap();
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].record.id, "r1");
assert!(
(hits[0].score - 1.0).abs() < 1e-5,
"cosine score={}",
hits[0].score
);
}
#[test]
fn search_ranks_nearest_first() {
let tmp = tempfile::tempdir().unwrap();
let idx = open(tmp.path());
idx.upsert(&record("a", "alpha", "facts")).unwrap();
idx.upsert(&record("b", "beta", "facts")).unwrap();
// threshold -1.0 includes the orthogonal (cosine 0.0) record too, so we
// can assert ordering; a 0.0 threshold would legitimately drop it.
let hits = idx.search("alpha", 5, -1.0, None, None).unwrap();
assert_eq!(hits.len(), 2);
assert_eq!(hits[0].record.id, "a");
assert!(hits[0].score > hits[1].score);
}
#[test]
fn mark_dead_excludes_from_recall() {
let tmp = tempfile::tempdir().unwrap();
let idx = open(tmp.path());
idx.upsert(&record("r1", "alpha", "facts")).unwrap();
idx.mark_dead("r1").unwrap();
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
assert!(hits.is_empty(), "dead record must be excluded");
}
#[test]
fn category_filter() {
let tmp = tempfile::tempdir().unwrap();
let idx = open(tmp.path());
idx.upsert(&record("a", "alpha", "facts")).unwrap();
idx.upsert(&record("b", "alpha", "experience")).unwrap();
let hits = idx.search("alpha", 5, 0.0, Some("facts"), None).unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].record.id, "a");
}
#[test]
fn reopen_with_different_model_is_mismatch() {
let tmp = tempfile::tempdir().unwrap();
{
let idx = open(tmp.path());
idx.upsert(&record("a", "alpha", "facts")).unwrap();
idx.flush().unwrap();
}
let err = MemoryIndex::open(tmp.path(), 4, "other-model", Arc::new(StubEmbedder));
assert!(matches!(err, Err(IndexError::ModelMismatch { .. })));
}
#[test]
fn indexed_ids_includes_tombstones() {
let tmp = tempfile::tempdir().unwrap();
let idx = open(tmp.path());
idx.upsert(&record("a", "alpha", "facts")).unwrap();
idx.upsert(&record("b", "beta", "facts")).unwrap();
idx.mark_dead("b").unwrap();
let mut ids = idx.indexed_ids().unwrap();
ids.sort();
// Both live and soft-deleted ids are reported (so reconciliation will not
// re-embed and resurrect the tombstone).
assert_eq!(ids, vec!["a".to_string(), "b".to_string()]);
}
#[test]
fn reopen_same_model_preserves_data() {
let tmp = tempfile::tempdir().unwrap();
{
let idx = open(tmp.path());
idx.upsert(&record("a", "alpha", "facts")).unwrap();
idx.flush().unwrap();
}
let idx = open(tmp.path());
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].record.id, "a");
}
}
+281
View File
@@ -0,0 +1,281 @@
//! strata-memory — semantic memory primitives for strata-ctl.
//!
//! Self-contained on purpose: it knows nothing of sessions or the GUI. It exposes
//! a swappable [`Embedder`] trait (dense vectors only — the ratified retrieval
//! baseline) plus an optional [`Reranker`] capability, and an [`HttpEmbedder`]
//! backend that speaks the `vetta-embedder` (BGE-M3) HTTP contract. The later
//! in-process Rust embedder drops in behind the same trait with no caller change.
//!
//! The vector index (Qdrant Edge) and the record schema land in later increments;
//! this module fixes the embedder seam first so the spike and the production path
//! share one interface.
use std::io::Read;
use std::time::Duration;
pub mod workspace;
pub use workspace::{
ExecReport, Outcome, VectorSlot, VectorSource, VectorWorkspace, WorkspaceError,
};
pub mod index;
pub use index::{Hit, IndexError, MemoryIndex, MemoryRecord};
/// Default dense dimension of BGE-M3 as served by `vetta-embedder`.
pub const BGE_M3_DIM: usize = 1024;
/// Errors surfaced by the embedder seam. Transport failures and contract
/// violations are distinguished so callers can fail-open (e.g. persist a memory
/// record and defer re-indexing when the embedder is unreachable).
#[derive(Debug, thiserror::Error)]
pub enum EmbedError {
#[error("transport: {0}")]
Transport(String),
#[error("decode: {0}")]
Decode(String),
#[error("server error {status}: {body}")]
Server { status: u16, body: String },
#[error("unexpected response shape: {0}")]
Shape(String),
}
/// Dense embedding provider. One embedder for all memory content; specialization
/// happens above the index (directive packs), not by swapping models per use.
pub trait Embedder: Send + Sync {
/// Return one L2-normalized dense vector per input text, in order.
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError>;
/// Vector dimension this embedder emits (used to size + validate the index).
fn dim(&self) -> usize;
/// Stable model identifier. Persisted alongside the index so that switching
/// embedders (or quantization) is detectable and forces a rebuild instead of
/// silently mixing incompatible vectors.
fn model_id(&self) -> &str;
}
/// A single reranked document: original input index + relevance score. Scores are
/// raw cross-encoder logits; only their ordering is meaningful.
#[derive(Debug, Clone, PartialEq)]
pub struct Reranked {
pub index: usize,
pub score: f64,
}
/// Optional second-stage capability. Kept as a separate trait (not a method on
/// [`Embedder`]) so an embedder without a reranker still satisfies the core
/// interface, and consumers probe for reranking at runtime.
pub trait Reranker: Send + Sync {
fn rerank(&self, query: &str, docs: &[&str], top_n: usize)
-> Result<Vec<Reranked>, EmbedError>;
}
/// [`Embedder`] + [`Reranker`] backend over the `vetta-embedder` HTTP contract:
/// `POST /embed {texts:[...]} -> {embeddings:[[...]]}` and
/// `POST /rerank {query,documents,top_n} -> {results:[{index,score,document}]}`.
///
/// Synchronous by design (a library must not dictate an async runtime); strata-ctl
/// calls it from `tokio::task::spawn_blocking`.
pub struct HttpEmbedder {
base_url: String,
model_id: String,
dim: usize,
timeout: Duration,
}
impl HttpEmbedder {
/// `base_url` is e.g. `http://192.168.50.18:8091` (supplied by the caller from
/// the DB config — deliberately not hardcoded here). `model_id` tags the index.
pub fn new(base_url: impl Into<String>, model_id: impl Into<String>, dim: usize) -> Self {
Self {
base_url: base_url.into(),
model_id: model_id.into(),
dim,
timeout: Duration::from_secs(8),
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
fn agent(&self) -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_global(Some(self.timeout))
.build()
.new_agent()
}
fn post_json(
&self,
path: &str,
body: &serde_json::Value,
) -> Result<serde_json::Value, EmbedError> {
let url = format!("{}{}", self.base_url.trim_end_matches('/'), path);
let mut resp = self
.agent()
.post(&url)
.send_json(body)
.map_err(|e| EmbedError::Transport(e.to_string()))?;
let status = resp.status().as_u16();
let mut buf = Vec::new();
resp.body_mut()
.as_reader()
.read_to_end(&mut buf)
.map_err(|e| EmbedError::Transport(e.to_string()))?;
if !(200..300).contains(&status) {
let body = String::from_utf8_lossy(&buf).chars().take(512).collect();
return Err(EmbedError::Server { status, body });
}
serde_json::from_slice(&buf).map_err(|e| EmbedError::Decode(e.to_string()))
}
}
/// Parse `{"embeddings": [[f32, ...], ...]}`. Public-shape tolerant: reads numbers
/// via `as_f64` and narrows to f32.
fn parse_embeddings(v: &serde_json::Value) -> Result<Vec<Vec<f32>>, EmbedError> {
let arr = v
.get("embeddings")
.and_then(|e| e.as_array())
.ok_or_else(|| EmbedError::Shape("missing 'embeddings' array".into()))?;
arr.iter()
.map(|row| {
row.as_array()
.map(|r| {
r.iter()
.filter_map(|x| x.as_f64().map(|f| f as f32))
.collect::<Vec<f32>>()
})
.ok_or_else(|| EmbedError::Shape("embedding row is not an array".into()))
})
.collect()
}
/// Parse `{"results": [{"index": n, "score": s}, ...]}` into [`Reranked`].
fn parse_rerank(v: &serde_json::Value) -> Result<Vec<Reranked>, EmbedError> {
let arr = v
.get("results")
.and_then(|e| e.as_array())
.ok_or_else(|| EmbedError::Shape("missing 'results' array".into()))?;
arr.iter()
.map(|r| {
let index = r
.get("index")
.and_then(|i| i.as_u64())
.ok_or_else(|| EmbedError::Shape("result missing 'index'".into()))?
as usize;
let score = r
.get("score")
.and_then(|s| s.as_f64())
.ok_or_else(|| EmbedError::Shape("result missing 'score'".into()))?;
Ok(Reranked { index, score })
})
.collect()
}
impl Embedder for HttpEmbedder {
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
let body = serde_json::json!({ "texts": texts });
let v = self.post_json("/embed", &body)?;
let out = parse_embeddings(&v)?;
if out.len() != texts.len() {
return Err(EmbedError::Shape(format!(
"expected {} vectors, got {}",
texts.len(),
out.len()
)));
}
for row in &out {
if row.len() != self.dim {
return Err(EmbedError::Shape(format!(
"expected dim {}, got {}",
self.dim,
row.len()
)));
}
}
Ok(out)
}
fn dim(&self) -> usize {
self.dim
}
fn model_id(&self) -> &str {
&self.model_id
}
}
impl Reranker for HttpEmbedder {
fn rerank(
&self,
query: &str,
docs: &[&str],
top_n: usize,
) -> Result<Vec<Reranked>, EmbedError> {
let body = serde_json::json!({ "query": query, "documents": docs, "top_n": top_n });
let v = self.post_json("/rerank", &body)?;
parse_rerank(&v)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_embeddings_reads_dense_rows() {
let json = serde_json::json!({"embeddings": [[0.1, 0.2, 0.3], [-0.4, 0.5, 0.6]]});
let out = parse_embeddings(&json).unwrap();
assert_eq!(out.len(), 2);
assert_eq!(out[0].len(), 3);
assert!((out[0][0] - 0.1).abs() < 1e-6);
}
#[test]
fn parse_embeddings_rejects_missing_key() {
let json = serde_json::json!({"error": "no texts provided"});
assert!(matches!(parse_embeddings(&json), Err(EmbedError::Shape(_))));
}
#[test]
fn parse_rerank_preserves_order_and_index() {
// Shape captured live from :8091/rerank.
let json = serde_json::json!({
"query": "come si configura il token MCP",
"results": [
{"index": 1, "score": -1.708251, "document": "mcp token"},
{"index": 0, "score": -10.783061, "document": "gatto"},
{"index": 2, "score": -11.032022, "document": "carbonara"}
]
});
let out = parse_rerank(&json).unwrap();
assert_eq!(out[0].index, 1); // most relevant first
assert_eq!(out[1].index, 0);
assert_eq!(out[2].index, 2);
assert!(out[0].score > out[1].score);
}
#[test]
fn dim_is_reported_and_used_for_validation() {
let e = HttpEmbedder::new("http://127.0.0.1:9", "bge-m3-q8", BGE_M3_DIM);
assert_eq!(e.dim(), 1024);
assert_eq!(e.model_id(), "bge-m3-q8");
}
/// Hits the real Altair instance; run explicitly with the LAN reachable.
/// `cargo test -- --ignored` — mirrors the repo's convention for live checks.
#[test]
#[ignore]
fn live_embed_altair_returns_unit_norm_dense() {
let e = HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", BGE_M3_DIM);
let v = e.embed(&["Il gatto nero salta sul tavolo"]).unwrap();
assert_eq!(v[0].len(), 1024);
let norm: f32 = v[0].iter().map(|x| x * x).sum::<f32>().sqrt();
assert!(
(norm - 1.0).abs() < 1e-3,
"expected L2-normalized, got norm {norm}"
);
}
}
+804
View File
@@ -0,0 +1,804 @@
//! Symbolic vector workspace — an RPN calculator over embeddings with 16
//! persistent per-session slots `$VEC[0..15]`.
//!
//! Design principle (Federico): vectors are handled SYMBOLICALLY. The full
//! 1024-float arrays live server-side (in the slots / the index); what reaches
//! the model is only references (`$VEC[n]`), scalar metrics (COS/DOT/NORM),
//! slot metadata, and at most an 8-value preview. [`ExecReport`] carries an
//! [`Outcome`] that structurally cannot contain a full vector, so the rendering
//! path can never dump the array into context.
//!
//! Adapted from our own Iris `vector_workspace` (RPN "Vera Core"), focused on the
//! vector algebra; the scientific-calculator extras (trig/log/HP.X bridge) are
//! intentionally trimmed. The vector primitives are reimplemented here (trivial
//! f32 ops) so the crate stays self-contained.
use serde::{Deserialize, Serialize};
use crate::{EmbedError, Embedder};
/// Number of persistent slots per session (`$VEC[0]..$VEC[15]`).
pub const VECTOR_SLOT_COUNT: usize = 16;
/// Max floats shown when previewing a vector result (never the full array).
const PREVIEW_LEN: usize = 8;
/// Provenance of a stored vector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VectorSource {
TextEmbedding,
Copied,
Derived,
}
impl VectorSource {
pub fn as_str(self) -> &'static str {
match self {
VectorSource::TextEmbedding => "TextEmbedding",
VectorSource::Copied => "Copied",
VectorSource::Derived => "Derived",
}
}
}
/// One persistent slot. The `vector` is the real data, kept server-side; it is
/// serialized only for DB persistence (strata-ctl owns the Store), never for the
/// model-facing report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorSlot {
pub dims: usize,
pub label: Option<String>,
pub source: VectorSource,
pub updated_at: String,
pub vector: Vec<f32>,
}
/// The per-session workspace. Serializable so strata-ctl can persist it in the DB.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorWorkspace {
pub slots: [Option<VectorSlot>; VECTOR_SLOT_COUNT],
}
impl Default for VectorWorkspace {
fn default() -> Self {
Self::new()
}
}
/// Errors from lexing/evaluating a program or resolving a slot reference.
#[derive(Debug, thiserror::Error)]
pub enum WorkspaceError {
#[error("parse: {0}")]
Parse(String),
#[error("stack: {0}")]
Stack(String),
#[error("type: {0}")]
Type(String),
#[error("slot: {0}")]
Slot(String),
#[error("dims: {0}")]
Dims(String),
#[error(transparent)]
Embed(#[from] EmbedError),
}
/// A model-facing result. Deliberately has NO full-vector variant: a vector is
/// summarized as `dims` + an ≤8-value `preview`, so the array cannot leak into
/// context through the report.
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
Scalar(f64),
Text(String),
Vector { dims: usize, preview: String },
}
/// Result of executing a program: the final stack value (summarized), the slots
/// touched, and human-readable notes (INFO/LIST).
#[derive(Debug, Clone, Default)]
pub struct ExecReport {
pub result: Option<Outcome>,
pub touched_slots: Vec<usize>,
pub notes: Vec<String>,
}
// Internal runtime value: during evaluation the stack DOES hold full vectors;
// they are summarized into an Outcome only when building the report.
#[derive(Debug, Clone)]
enum Value {
Text(String),
Scalar(f64),
Vector(Vec<f32>),
}
#[derive(Debug, Clone)]
enum Token {
Word(String),
Quoted(String),
}
impl VectorWorkspace {
pub fn new() -> Self {
Self {
slots: std::array::from_fn(|_| None),
}
}
/// Resolve a symbolic reference (`$VEC[n]`) to its vector, server-side. This
/// is the bridge used by search: the model passes `"$VEC[0]"`, the framework
/// resolves it here and feeds the index — the floats never enter context.
pub fn resolve(&self, reference: &str) -> Result<Vec<f32>, WorkspaceError> {
let idx = parse_slot_ref(reference)?;
self.slots[idx]
.as_ref()
.map(|s| s.vector.clone())
.ok_or_else(|| WorkspaceError::Slot(format!("$VEC[{idx}] is empty")))
}
/// Execute an RPN program. `embedder` backs the `EMB` op.
pub fn execute(
&mut self,
program: &str,
embedder: &dyn Embedder,
) -> Result<ExecReport, WorkspaceError> {
let tokens = lex(program)?;
let mut stack: Vec<Value> = Vec::new();
let mut touched: Vec<usize> = Vec::new();
let mut notes: Vec<String> = Vec::new();
let mut i = 0;
while i < tokens.len() {
match &tokens[i] {
Token::Quoted(text) => {
stack.push(Value::Text(text.clone()));
i += 1;
}
Token::Word(word) => {
if let Ok(v) = word.parse::<f64>() {
stack.push(Value::Scalar(v));
i += 1;
continue;
}
let op = word.to_ascii_uppercase();
match op.as_str() {
// ── stack ──
"DUP" => {
let top = stack.last().cloned().ok_or_else(|| under("DUP"))?;
stack.push(top);
i += 1;
}
"DROP" => {
stack.pop().ok_or_else(|| under("DROP"))?;
i += 1;
}
"SWAP" => {
need(&stack, 2, "SWAP")?;
let n = stack.len();
stack.swap(n - 1, n - 2);
i += 1;
}
"OVER" => {
need(&stack, 2, "OVER")?;
let v = stack[stack.len() - 2].clone();
stack.push(v);
i += 1;
}
"ROT" => {
need(&stack, 3, "ROT")?;
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
let c = stack.pop().unwrap();
stack.push(b);
stack.push(a);
stack.push(c);
i += 1;
}
"CLEAR" => {
stack.clear();
i += 1;
}
// ── scalar ──
"+" | "-" | "*" | "/" | "POW" | "^" | "GT" | ">" | "LT" | "<" | "EQ"
| "==" => {
let b = pop_scalar(&mut stack)?;
let a = pop_scalar(&mut stack)?;
let r = match op.as_str() {
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => {
if b == 0.0 {
return Err(WorkspaceError::Stack(
"division by zero".into(),
));
}
a / b
}
"POW" | "^" => a.powf(b),
"GT" | ">" => bool_num(a > b),
"LT" | "<" => bool_num(a < b),
_ => bool_num((a - b).abs() < 1e-9),
};
stack.push(Value::Scalar(r));
i += 1;
}
"SQRT" | "ABS" | "NEG" | "NOT" | "!" => {
let a = pop_scalar(&mut stack)?;
let r = match op.as_str() {
"SQRT" => a.sqrt(),
"ABS" => a.abs(),
"NEG" => -a,
_ => bool_num(a == 0.0),
};
stack.push(Value::Scalar(r));
i += 1;
}
// ── embeddings / slots ──
"EMB" => {
let text = pop_text(&mut stack)?;
let mut v = embedder.embed(&[text.as_str()])?;
let vec = v.pop().ok_or_else(|| {
WorkspaceError::Embed(EmbedError::Shape("empty".into()))
})?;
stack.push(Value::Vector(vec));
i += 1;
}
"RCL" => {
let idx = parse_slot_arg(tokens.get(i + 1))?;
let stored = self.slots[idx].as_ref().ok_or_else(|| {
WorkspaceError::Slot(format!("$VEC[{idx}] is empty"))
})?;
stack.push(Value::Vector(stored.vector.clone()));
i += 2;
}
"STO" => {
let idx = parse_slot_arg(tokens.get(i + 1))?;
let vec = pop_vector(&mut stack)?;
let label = self.slots[idx].as_ref().and_then(|s| s.label.clone());
self.slots[idx] = Some(VectorSlot {
dims: vec.len(),
label,
source: VectorSource::Copied,
updated_at: now_stamp(),
vector: vec,
});
touch(&mut touched, idx);
i += 2;
}
"CLR" => {
let idx = parse_slot_arg(tokens.get(i + 1))?;
self.slots[idx] = None;
touch(&mut touched, idx);
i += 2;
}
"LABEL" => {
let idx = parse_slot_arg(tokens.get(i + 1))?;
let label = parse_label_arg(tokens.get(i + 2))?;
let entry = self.slots[idx].as_mut().ok_or_else(|| {
WorkspaceError::Slot(format!("cannot label empty $VEC[{idx}]"))
})?;
entry.label = Some(label);
entry.updated_at = now_stamp();
touch(&mut touched, idx);
i += 3;
}
"INFO" => {
let idx = parse_slot_arg(tokens.get(i + 1))?;
notes.push(self.slot_line(idx));
i += 2;
}
"LIST" => {
notes.push(self.list());
i += 1;
}
// ── vector algebra ──
"V+" | "V-" | "AVG" | "WAVG" => {
let w = if op == "WAVG" {
Some(pop_scalar(&mut stack)? as f32)
} else {
None
};
let rhs = pop_vector(&mut stack)?;
let lhs = pop_vector(&mut stack)?;
let r = match op.as_str() {
"V+" => v_add(&lhs, &rhs)?,
"V-" => v_sub(&lhs, &rhs)?,
"AVG" => v_scale(&v_add(&lhs, &rhs)?, 0.5),
_ => v_wavg(&lhs, &rhs, w.unwrap()),
};
stack.push(Value::Vector(r));
i += 1;
}
"UNIT" => {
let v = pop_vector(&mut stack)?;
stack.push(Value::Vector(v_unit(&v)?));
i += 1;
}
"SCALE" => {
let top = stack.pop().ok_or_else(|| under("SCALE"))?;
let second = stack.pop().ok_or_else(|| under("SCALE"))?;
let (vec, s) = match (second, top) {
(Value::Vector(v), Value::Scalar(s)) => (v, s as f32),
(Value::Scalar(s), Value::Vector(v)) => (v, s as f32),
_ => {
return Err(WorkspaceError::Type(
"SCALE expects one vector and one scalar".into(),
))
}
};
stack.push(Value::Vector(v_scale(&vec, s)));
i += 1;
}
"COS" | "DOT" | "DIST" | "PROJ" => {
let rhs = pop_vector(&mut stack)?;
let lhs = pop_vector(&mut stack)?;
let r = match op.as_str() {
"COS" => v_cosine(&lhs, &rhs)? as f64,
"DOT" => v_dot(&lhs, &rhs)? as f64,
"DIST" => 1.0 - v_cosine(&lhs, &rhs)? as f64,
_ => v_proj(&lhs, &rhs)? as f64,
};
stack.push(Value::Scalar(r));
i += 1;
}
"NORM" => {
let v = pop_vector(&mut stack)?;
stack.push(Value::Scalar(v_norm(&v) as f64));
i += 1;
}
_ => {
return Err(WorkspaceError::Parse(format!("unknown token '{word}'")));
}
}
}
}
}
let result = stack.last().map(summarize);
Ok(ExecReport {
result,
touched_slots: touched,
notes,
})
}
/// Model-facing rendering: scalars, text, slot metadata, ≤8-value previews.
/// Never the full vector.
pub fn render(&self, report: &ExecReport) -> String {
let mut lines = vec!["VectorWorkspace executed successfully.".to_string()];
match &report.result {
Some(Outcome::Scalar(v)) => lines.push(format!("Final result: scalar {v:.6}")),
Some(Outcome::Text(t)) => lines.push(format!("Final result: text \"{t}\"")),
Some(Outcome::Vector { dims, preview }) => {
lines.push(format!("Final result: vector[{dims}] = [{preview}]"))
}
None => lines.push("Final result: no stack value.".to_string()),
}
if !report.touched_slots.is_empty() {
lines.push("Touched slots:".to_string());
for idx in &report.touched_slots {
lines.push(self.slot_line(*idx));
}
}
if !report.notes.is_empty() {
lines.push("Notes:".to_string());
lines.extend(report.notes.iter().cloned());
}
lines.join("\n")
}
/// Occupied-slot listing (metadata only).
pub fn list(&self) -> String {
let occupied: Vec<String> = self
.slots
.iter()
.enumerate()
.filter_map(|(idx, s)| s.as_ref().map(|_| self.slot_line(idx)))
.collect();
if occupied.is_empty() {
"Occupied slots: none".to_string()
} else {
format!("Occupied slots:\n{}", occupied.join("\n"))
}
}
fn slot_line(&self, idx: usize) -> String {
match &self.slots[idx] {
Some(s) => {
let label = s
.label
.as_ref()
.map(|l| format!(" label=\"{l}\""))
.unwrap_or_default();
format!(
"- $VEC[{idx}]: occupied=true dims={} source={}{} updated_at={}",
s.dims,
s.source.as_str(),
label,
s.updated_at
)
}
None => format!("- $VEC[{idx}]: occupied=false"),
}
}
}
// ── summarization / preview (the symbolic boundary) ──
fn summarize(v: &Value) -> Outcome {
match v {
Value::Scalar(s) => Outcome::Scalar(*s),
Value::Text(t) => Outcome::Text(t.clone()),
Value::Vector(vec) => Outcome::Vector {
dims: vec.len(),
preview: preview_vector(vec),
},
}
}
fn preview_vector(vec: &[f32]) -> String {
let head: Vec<String> = vec
.iter()
.take(PREVIEW_LEN)
.map(|v| format!("{v:.4}"))
.collect();
if vec.len() > PREVIEW_LEN {
format!("{}, ...", head.join(", "))
} else {
head.join(", ")
}
}
// ── vector primitives (reimplemented, self-contained) ──
fn check_dims(a: &[f32], b: &[f32]) -> Result<(), WorkspaceError> {
if a.len() != b.len() {
return Err(WorkspaceError::Dims(format!("{} vs {}", a.len(), b.len())));
}
Ok(())
}
fn v_add(a: &[f32], b: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
check_dims(a, b)?;
Ok(a.iter().zip(b).map(|(x, y)| x + y).collect())
}
fn v_sub(a: &[f32], b: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
check_dims(a, b)?;
Ok(a.iter().zip(b).map(|(x, y)| x - y).collect())
}
fn v_scale(a: &[f32], s: f32) -> Vec<f32> {
a.iter().map(|x| x * s).collect()
}
/// Linear interpolation: `lhs*(1-w) + rhs*w`.
fn v_wavg(a: &[f32], b: &[f32], w: f32) -> Vec<f32> {
a.iter()
.zip(b)
.map(|(x, y)| x * (1.0 - w) + y * w)
.collect()
}
fn v_dot(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
check_dims(a, b)?;
Ok(a.iter().zip(b).map(|(x, y)| x * y).sum())
}
fn v_norm(a: &[f32]) -> f32 {
a.iter().map(|x| x * x).sum::<f32>().sqrt()
}
fn v_unit(a: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
let n = v_norm(a);
if n <= 1e-12 {
return Err(WorkspaceError::Dims(
"cannot normalize a zero vector".into(),
));
}
Ok(v_scale(a, 1.0 / n))
}
fn v_cosine(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
check_dims(a, b)?;
let na = v_norm(a);
let nb = v_norm(b);
if na <= 1e-12 || nb <= 1e-12 {
return Err(WorkspaceError::Dims("cosine with a zero vector".into()));
}
Ok(v_dot(a, b)? / (na * nb))
}
/// Scalar projection of `a` onto `b`: `dot(a,b)/|b|`.
fn v_proj(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
check_dims(a, b)?;
let nb = v_norm(b);
if nb <= 1e-12 {
return Err(WorkspaceError::Dims("projection onto a zero vector".into()));
}
Ok(v_dot(a, b)? / nb)
}
// ── lexing / parsing helpers ──
fn lex(input: &str) -> Result<Vec<Token>, WorkspaceError> {
let chars: Vec<char> = input.chars().collect();
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
if chars[i].is_whitespace() {
i += 1;
continue;
}
if chars[i] == '"' {
i += 1;
let mut s = String::new();
while i < chars.len() && chars[i] != '"' {
s.push(chars[i]);
i += 1;
}
if i >= chars.len() {
return Err(WorkspaceError::Parse("unterminated quoted string".into()));
}
i += 1; // closing quote
out.push(Token::Quoted(s));
continue;
}
let start = i;
while i < chars.len() && !chars[i].is_whitespace() {
i += 1;
}
out.push(Token::Word(chars[start..i].iter().collect()));
}
Ok(out)
}
fn parse_slot_ref(raw: &str) -> Result<usize, WorkspaceError> {
let upper = raw.to_ascii_uppercase();
let inner = upper
.strip_prefix("$VEC[")
.and_then(|s| s.strip_suffix(']'))
.ok_or_else(|| {
WorkspaceError::Parse(format!("invalid slot reference '{raw}', expected $VEC[n]"))
})?;
let idx: usize = inner
.parse()
.map_err(|_| WorkspaceError::Parse(format!("invalid slot index in '{raw}'")))?;
if idx >= VECTOR_SLOT_COUNT {
return Err(WorkspaceError::Slot(format!(
"$VEC[{idx}] out of range (0..{})",
VECTOR_SLOT_COUNT - 1
)));
}
Ok(idx)
}
fn parse_slot_arg(token: Option<&Token>) -> Result<usize, WorkspaceError> {
match token {
Some(Token::Word(w)) => parse_slot_ref(w),
Some(Token::Quoted(_)) => Err(WorkspaceError::Parse(
"expected $VEC[n], got quoted text".into(),
)),
None => Err(WorkspaceError::Parse("missing slot reference".into())),
}
}
fn parse_label_arg(token: Option<&Token>) -> Result<String, WorkspaceError> {
match token {
Some(Token::Quoted(t)) | Some(Token::Word(t)) => Ok(t.clone()),
None => Err(WorkspaceError::Parse("missing label text".into())),
}
}
fn pop_text(stack: &mut Vec<Value>) -> Result<String, WorkspaceError> {
match stack.pop() {
Some(Value::Text(t)) => Ok(t),
Some(_) => Err(WorkspaceError::Type("expected text".into())),
None => Err(under("text")),
}
}
fn pop_vector(stack: &mut Vec<Value>) -> Result<Vec<f32>, WorkspaceError> {
match stack.pop() {
Some(Value::Vector(v)) => Ok(v),
Some(_) => Err(WorkspaceError::Type("expected vector".into())),
None => Err(under("vector")),
}
}
fn pop_scalar(stack: &mut Vec<Value>) -> Result<f64, WorkspaceError> {
match stack.pop() {
Some(Value::Scalar(v)) => Ok(v),
Some(_) => Err(WorkspaceError::Type("expected scalar".into())),
None => Err(under("scalar")),
}
}
fn under(op: &str) -> WorkspaceError {
WorkspaceError::Stack(format!("underflow on {op}"))
}
fn need(stack: &[Value], n: usize, op: &str) -> Result<(), WorkspaceError> {
if stack.len() < n {
return Err(under(op));
}
Ok(())
}
fn bool_num(b: bool) -> f64 {
if b {
1.0
} else {
0.0
}
}
fn touch(touched: &mut Vec<usize>, idx: usize) {
if !touched.contains(&idx) {
touched.push(idx);
}
}
fn now_stamp() -> String {
// No chrono dependency in this crate: a stable UTC timestamp from SystemTime.
match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
Ok(d) => format!("{}", d.as_secs()),
Err(_) => "0".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Deterministic embedder for hermetic tests: maps text to a small vector.
struct StubEmbedder;
impl Embedder for StubEmbedder {
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
Ok(texts
.iter()
.map(|t| {
let n = t.len() as f32;
vec![n, n * 2.0, n * 3.0, 0.0]
})
.collect())
}
fn dim(&self) -> usize {
4
}
fn model_id(&self) -> &str {
"stub"
}
}
#[test]
fn slot_ref_parse_and_range() {
assert_eq!(parse_slot_ref("$VEC[3]").unwrap(), 3);
assert_eq!(parse_slot_ref("$vec[15]").unwrap(), 15);
assert!(parse_slot_ref("$VEC[16]").is_err());
assert!(parse_slot_ref("VEC[0]").is_err());
}
#[test]
fn lex_preserves_quoted_strings() {
let t = lex("\"hello world\" EMB STO $VEC[0]").unwrap();
assert!(matches!(&t[0], Token::Quoted(s) if s == "hello world"));
assert!(matches!(&t[1], Token::Word(s) if s == "EMB"));
assert!(matches!(&t[3], Token::Word(s) if s == "$VEC[0]"));
}
#[test]
fn emb_sto_rcl_cos_roundtrip() {
let mut ws = VectorWorkspace::new();
let e = StubEmbedder;
// "ab" -> [2,4,6,0]; "abcd" -> [4,8,12,0] (parallel => cosine 1.0)
ws.execute("\"ab\" EMB STO $VEC[0]", &e).unwrap();
let rep = ws.execute("\"abcd\" EMB RCL $VEC[0] COS", &e).unwrap();
match rep.result {
Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5, "cos={s}"),
other => panic!("expected scalar cosine, got {other:?}"),
}
assert_eq!(ws.resolve("$VEC[0]").unwrap().len(), 4);
}
#[test]
fn unit_normalizes_to_one() {
let mut ws = VectorWorkspace::new();
let rep = ws.execute("\"abc\" EMB UNIT NORM", &StubEmbedder).unwrap();
match rep.result {
Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5),
other => panic!("expected norm 1, got {other:?}"),
}
}
#[test]
fn report_never_leaks_full_vector() {
let mut ws = VectorWorkspace::new();
// 4-dim stub vector: preview shows all 4 (<=8). Use a longer one via SCALE? dims stay 4.
let rep = ws.execute("\"abc\" EMB", &StubEmbedder).unwrap();
match &rep.result {
Some(Outcome::Vector { dims, preview }) => {
assert_eq!(*dims, 4);
// preview is a short string, not the serialized array
assert!(preview.split(',').count() <= PREVIEW_LEN);
}
other => panic!("expected vector outcome, got {other:?}"),
}
let rendered = ws.render(&rep);
assert!(rendered.contains("vector[4]"));
// The rendered report must not contain a JSON-style full array of the vector.
assert!(!rendered.contains("[3.0, 6.0, 9.0"));
}
#[test]
fn preview_caps_at_eight() {
let long: Vec<f32> = (0..1024).map(|i| i as f32).collect();
let p = preview_vector(&long);
assert!(p.ends_with("..."));
assert_eq!(p.trim_end_matches(", ...").split(',').count(), PREVIEW_LEN);
}
#[test]
fn dim_mismatch_is_error() {
assert!(v_add(&[1.0, 2.0], &[1.0]).is_err());
assert!(v_cosine(&[1.0, 2.0], &[1.0]).is_err());
assert!(v_unit(&[0.0, 0.0]).is_err());
}
#[test]
fn label_and_list_metadata_only() {
let mut ws = VectorWorkspace::new();
ws.execute(
"\"ab\" EMB STO $VEC[0] LABEL $VEC[0] \"gatto\"",
&StubEmbedder,
)
.unwrap();
let listing = ws.list();
assert!(listing.contains("label=\"gatto\""));
assert!(listing.contains("dims=4"));
// metadata listing carries no float values
assert!(!listing.contains("2.0000"));
}
#[test]
fn scale_accepts_vector_scalar_either_order() {
let mut ws = VectorWorkspace::new();
let rep = ws
.execute("\"ab\" EMB 0.5 SCALE NORM", &StubEmbedder)
.unwrap();
// [2,4,6,0]*0.5 = [1,2,3,0], norm = sqrt(14) ≈ 3.7417
match rep.result {
Some(Outcome::Scalar(s)) => assert!((s - 14.0f64.sqrt()).abs() < 1e-4),
other => panic!("expected scalar norm, got {other:?}"),
}
}
/// Live symbolic flow against Altair: EMB two phrases into slots, COS yields a
/// scalar (never the array); slots hold 1024-dim vectors server-side while the
/// listing shows only metadata. `cargo test -p strata-memory -- --ignored`.
#[test]
#[ignore]
fn live_symbolic_cos_altair() {
let e =
crate::HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", crate::BGE_M3_DIM);
let mut ws = VectorWorkspace::new();
ws.execute("\"Il gatto nero salta sul tavolo\" EMB STO $VEC[0]", &e)
.unwrap();
ws.execute(
"\"Un felino scuro balza sopra il tavolo\" EMB STO $VEC[1]",
&e,
)
.unwrap();
let rep = ws.execute("RCL $VEC[0] RCL $VEC[1] COS", &e).unwrap();
match rep.result {
Some(Outcome::Scalar(s)) => {
assert!(
(0.5..=1.0).contains(&s),
"paraphrase cosine should be high, got {s}"
)
}
other => panic!("expected scalar cosine, got {other:?}"),
}
let listing = ws.list();
assert!(listing.contains("dims=1024"));
assert!(ws.render(&rep).contains("scalar"));
}
}
+20 -1
View File
@@ -75,7 +75,7 @@ async fn build_app() -> (axum::Router, Arc<SqliteStore>) {
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!("strata-ctl-test-{nanos}"));
let app = router_with_store(svc, store.clone(), AuthConfig::default(), root);
let app = router_with_store(svc, store.clone(), AuthConfig::default(), root, None);
(app, store)
}
@@ -163,6 +163,25 @@ async fn mcp_connector_crud_and_validation() {
assert_eq!(st, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn memory_enable_rejected_without_service() {
let (app, _store) = build_app().await;
let id = create_session(&app).await;
// No memory service in this app -> enabling the one-way latch is refused.
let (st, text) = req(
&app,
Method::PATCH,
&format!("/api/sessions/{id}"),
Some(serde_json::json!({"settings": {"memory_enabled": true}})),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{text}");
// The rejected enable did not persist: the session stays off.
let (_, text) = req(&app, Method::GET, &format!("/api/sessions/{id}"), None).await;
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(v["settings"]["memory_enabled"], false);
}
#[tokio::test]
async fn session_holds_context_and_persists_usage() {
let (app, _store) = build_app().await;
+15
View File
@@ -800,6 +800,17 @@ function fillSettingsForm(data, scope) {
// MCP: catalog editor in Generali, per-session tool allowlist in Sessione.
$("#set-mcp-catalog").hidden = scope !== "general";
$("#set-mcp-tools").hidden = scope !== "session";
// Semantic memory: per-session ONE-WAY opt-in (hidden in Generali). Once on,
// the checkbox is disabled — it can never be turned off (irreversible latch).
$("#set-memory-field").hidden = !isSession;
if (isSession) {
const on = !!data.memory_enabled;
$("#set-memory").checked = on;
$("#set-memory").disabled = on;
$("#set-memory-hint").textContent = on
? t("settings.memory.hint.on")
: t("settings.memory.hint.off");
}
}
function readSettingsForm() {
@@ -855,6 +866,10 @@ async function saveSettings() {
applyFontSize(Number($("#set-fontsize").value));
// Preserve unexposed fields (seed, penalties) from the loaded instance.
const settings = { ...settingsBase, ...readSettingsForm() };
// One-way memory latch in the UI too: checking enables, never un-enables.
if (settingsScope === "session") {
settings.memory_enabled = $("#set-memory").checked || !!settingsBase.memory_enabled;
}
try {
if (settingsScope === "session") {
const sess = currentSession();
+4
View File
@@ -38,6 +38,10 @@
"settings.mcp.fields.required": "Name, URL and token are required.",
"settings.mcp.saved": "Connector saved.",
"settings.mcp.error": "MCP error: {msg}",
"settings.memory.title": "Semantic memory",
"settings.memory.label": "Enable long-term memory for this chat",
"settings.memory.hint.off": "Off by default. Once enabled it cannot be disabled (memories stay recallable). Requires a reachable embedder.",
"settings.memory.hint.on": "Enabled for this chat: remember/recall/forget. Cannot be disabled.",
"settings.save": "Save",
"settings.cancel": "Cancel",
"settings.hint.session": "Changes apply only to this session.",
+4
View File
@@ -38,6 +38,10 @@
"settings.mcp.fields.required": "Nome, URL e token sono obbligatori.",
"settings.mcp.saved": "Connettore salvato.",
"settings.mcp.error": "Errore MCP: {msg}",
"settings.memory.title": "Memoria semantica",
"settings.memory.label": "Abilita la memoria a lungo termine per questa chat",
"settings.memory.hint.off": "Off di default. Una volta attivata non si può disattivare (le memorie restano richiamabili). Richiede l'embedder raggiungibile.",
"settings.memory.hint.on": "Attiva per questa chat: remember/recall/forget. Non si può disattivare.",
"settings.save": "Salva",
"settings.cancel": "Annulla",
"settings.hint.session": "Modifiche valide solo per questa sessione.",
+9
View File
@@ -145,6 +145,15 @@
<p class="muted small" data-i18n="settings.mcp.tools.hint">Scegli quali tool di ogni connettore il modello può usare in questa chat. Salva per applicare.</p>
<div id="mcp-tools-list" class="mcp-list"></div>
</div>
<!-- Semantic memory: per-session ONE-WAY opt-in (Sessione scope) -->
<div id="set-memory-field" class="mcp-block" hidden>
<h3 data-i18n="settings.memory.title">Memoria semantica</h3>
<label class="mcp-tool">
<input id="set-memory" type="checkbox" />
<span class="mcp-tool-text" data-i18n="settings.memory.label">Abilita la memoria a lungo termine per questa chat</span>
</label>
<p id="set-memory-hint" class="muted small"></p>
</div>
<div class="dialog-actions">
<button id="set-cancel" class="btn" data-i18n="settings.cancel">Annulla</button>
<button id="set-save" class="btn primary" data-i18n="settings.save">Salva</button>