Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(embeddings): hybrid retrieval on by default, best-effort

AkitaOnRails540afb212e05
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bbbd10c..b39335f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
pinned sha256; baselines are published under `docs/benchmarks/`. The
existing LLM A/B harness moved to the `ab` subcommand.
### Changed
+- Hybrid retrieval is on by default: an install with no
+ `embedding_provider` configured now gets in-process local embeddings
+ best-effort — the model downloads in the background on first start
+ (hybrid search enables on the next restart), existing pages are
+ backfilled by a one-shot startup pass, and hosts that cannot fetch
+ the model keep the previous FTS-only behaviour with a warning. Opt
+ out with `embedding_provider = "none"`; configured providers are
+ never overridden. Measured on LongMemEval-S: overall hit@5 rises
+ from 0.617 (FTS-only) to 0.779 with local embeddings.
- The wiki's on-disk format is now natively the Open Knowledge Format
(OKF) v0.2: every page write fills the spec's `type`, `generated`,
`sources` and `stale_after` keys (ai-memory's own fields ride along as
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index cbd41aa1..d24fa8dd 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1384,6 +1384,36 @@ async fn start_maintenance_scheduler(
}));
}
+ // One-shot startup backfill (2.0): with an embedder present, pages
+ // written before it existed - a fresh upgrade onto the default local
+ // embedder, or a provider switch - get their vectors without any
+ // maintenance config. Skips already-embedded pages, so a settled
+ // store logs one cheap no-op pass. Runs in the background; startup
+ // is never blocked on it.
+ if let Some(embedder) = embedder.clone() {
+ let reader = reader.clone();
+ let writer = writer.clone();
+ let wiki = wiki.clone();
+ tasks.push(tokio::spawn(async move {
+ let started = std::time::Instant::now();
+ match run_scheduled_embedding_backfill_tick(&reader, &writer, &wiki, &embedder).await {
+ Ok(outcome) if outcome.embedded > 0 || outcome.failed > 0 || outcome.errors > 0 => {
+ info!(
+ scopes = outcome.scopes,
+ embedded = outcome.embedded,
+ skipped = outcome.skipped,
+ failed = outcome.failed,
+ errors = outcome.errors,
+ elapsed_ms = started.elapsed().as_millis(),
+ "startup embedding backfill completed"
+ );
+ }
+ Ok(_) => {}
+ Err(e) => tracing::warn!(error = %e, "startup embedding backfill failed"),
+ }
+ }));
+ }
+
if maintenance_enabled && embedding_backfill_interval_secs > 0 {
if let Some(embedder) = embedder {
let reader = reader.clone();
@@ -1704,6 +1734,7 @@ async fn configure_embedder(
let provider_name = cfg.provider.name().to_string();
let model = cfg.model.clone();
let dim = cfg.dim;
+ let defaulted = cfg.defaulted;
// Local embeddings: fetch the model once, checksum-pinned, before
// the loader runs (docs/local-embeddings.md). Offline installs drop
// the files into models/ by hand and never hit the network.
@@ -1711,15 +1742,53 @@ async fn configure_embedder(
&& let Some(models_dir) = cfg.models_dir.as_deref()
&& !ai_memory_llm::model_present(models_dir)
{
+ if defaulted {
+ // Best-effort default (docs/local-embeddings.md): never
+ // block startup on an ~87 MB download. Fetch in the
+ // background; THIS boot runs without an embedder (the
+ // pre-2.0 behaviour), the next start finds the files and
+ // enables hybrid search. Offline hosts just log the warn.
+ let models_dir = models_dir.to_path_buf();
+ tokio::spawn(async move {
+ tracing::info!(
+ dir = %models_dir.display(),
+ "fetching the default local embedding model in the \
+ background (~87 MB, one time); hybrid search enables \
+ on the next start"
+ );
+ if let Err(e) = ai_memory_llm::fetch_model(&models_dir).await {
+ tracing::warn!(
+ error = %e,
+ "default local embedding model fetch failed; running \
+ without an embedder. Set embedding_provider = \"none\" \
+ to opt out, or install offline per \
+ docs/local-embeddings.md"
+ );
+ }
+ });
+ return Ok((wiki, None));
+ }
tracing::info!(
dir = %models_dir.display(),
"local embedding model not present; fetching (~87 MB, one time)"
);
- ai_memory_llm::fetch_model(models_dir)
- .await
- .context("fetching the local embedding model (set up offline per docs/local-embeddings.md if this host has no network)")?;
- }
- let embedder = build_embedder(cfg).context("building embedder from config")?;
+ ai_memory_llm::fetch_model(models_dir).await.context(
+ "fetching the local embedding model (set up offline per \
+ docs/local-embeddings.md if this host has no network)",
+ )?;
+ }
+ let embedder = match build_embedder(cfg) {
+ Ok(e) => e,
+ Err(e) if defaulted => {
+ tracing::warn!(
+ error = %e,
+ "default local embeddings unavailable (model load failed); \
+ continuing without an embedder"
+ );
+ return Ok((wiki, None));
+ }
+ Err(e) => return Err(e).context("building embedder from config"),
+ };
let mismatch = store
.reader
.embedding_meta_for_mismatch(
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index e61d8370..267fcc16 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -1140,8 +1140,15 @@ impl Config {
/// Returns [`LlmError::NotConfigured`] for unknown providers, missing API
/// keys, or invalid dimensions.
pub fn embedder_config(&self) -> LlmResult<Option<EmbedderConfig>> {
- let Some(provider_raw) = non_empty(self.embedding_provider.as_deref()) else {
- return Ok(None);
+ // 2.0 default: hybrid retrieval out of the box. An unset provider
+ // selects in-process `local` embeddings BEST-EFFORT (the serve
+ // layer degrades to no-embedder if the model cannot be fetched or
+ // loaded); `embedding_provider = "none"` opts out entirely, and an
+ // explicitly configured provider keeps hard-failure semantics.
+ let (provider_raw, defaulted) = match non_empty(self.embedding_provider.as_deref()) {
+ Some("none" | "off" | "disabled") => return Ok(None),
+ Some(raw) => (raw, false),
+ None => ("local", true),
};
let provider = match provider_raw {
"openai" => EmbedderChoice::OpenAi,
@@ -1152,7 +1159,7 @@ impl Config {
other => {
return Err(LlmError::NotConfigured(format!(
"AI_MEMORY_EMBEDDING_PROVIDER={other} not one of \
- openai|voyage|google|gemini|openai-compat|local"
+ openai|voyage|google|gemini|openai-compat|local|none"
)));
}
};
@@ -1224,6 +1231,7 @@ impl Config {
api_key,
base_url,
models_dir: Some(self.data_dir.join("models")),
+ defaulted,
}))
}
diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.toml
index 96629f63..4330ff95 100644
--- a/crates/ai-memory-cli/templates/config.default.toml
+++ b/crates/ai-memory-cli/templates/config.default.toml
@@ -96,6 +96,17 @@ log_level = "info"
# will not shrink after the first prune; the `ai-memory backup` tarball will.
# - A quarter of raw capture: observation_retention_days = 90
# - Smaller transactions on a slow disk: observation_prune_batch = 2000
+# --- Embeddings (hybrid retrieval) ---------------------------------------
+# Unset = the 2.0 default: in-process local embeddings (all-MiniLM-L6-v2,
+# 384-dim), no API key, no data egress. The ~87 MB model is fetched once
+# into <data_dir>/models/ in the background (checksum-pinned; hybrid search
+# enables on the next start), and existing pages are backfilled
+# automatically at startup. See docs/local-embeddings.md.
+# embedding_provider = "none" # opt out (FTS + entity + graph only)
+# embedding_provider = "openai" # or voyage | google | openai-compat
+# embedding_model = "..." # provider-specific override
+# embedding_dim = 384 # must match the model
+
[decay]
lambda = 0.02
sigma = 0.6
diff --git a/crates/ai-memory-cli/tests/autoscope_env.rs b/crates/ai-memory-cli/tests/autoscope_env.rs
index d6a932d1..70d7cc4c 100644
--- a/crates/ai-memory-cli/tests/autoscope_env.rs
+++ b/crates/ai-memory-cli/tests/autoscope_env.rs
@@ -45,6 +45,9 @@ fn spawn_and_wait_for_log(
])
.arg(tmp.path())
.env("AI_MEMORY_DATA_DIR", tmp.path())
+ // Hermetic: the 2.0 default would otherwise start a background
+ // model download on every spawned server.
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")
// Force tracing to spit at least info-level so the
// "active-project isolation mode" line is rendered to stderr.
.env("RUST_LOG", "info")
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index 5b181b5e..d1402e7d 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -158,6 +158,12 @@ pub struct EmbedderConfig {
pub base_url: Option<String>,
/// `<data_dir>/models/` root, required by the `local` provider.
pub models_dir: Option<std::path::PathBuf>,
+ /// True when no provider was configured and `local` was chosen as
+ /// the 2.0 default. Best-effort semantics: a defaulted embedder
+ /// that cannot fetch or load its model degrades to no-embedder with
+ /// a warning instead of refusing to start; an explicitly configured
+ /// one still fails hard.
+ pub defaulted: bool,
}
/// Construct an `Arc<dyn Embedder>` from the config.
diff --git a/crates/ai-memory-llm/tests/openai_compat_embedder.rs b/crates/ai-memory-llm/tests/openai_compat_embedder.rs
index 5925bf03..e0d8c3ad 100644
--- a/crates/ai-memory-llm/tests/openai_compat_embedder.rs
+++ b/crates/ai-memory-llm/tests/openai_compat_embedder.rs
@@ -85,6 +85,7 @@ async fn factory_builds_compat_embedder_and_requires_base_url() {
api_key: SecretString::from(String::new()),
base_url: Some("http://localhost:11434/v1".into()),
models_dir: None,
+ defaulted: false,
})
.expect("factory builds compat embedder");
assert_eq!(ok.provider(), "openai-compat");
@@ -97,6 +98,7 @@ async fn factory_builds_compat_embedder_and_requires_base_url() {
api_key: SecretString::from(String::new()),
base_url: None,
models_dir: None,
+ defaulted: false,
}) {
Ok(_) => panic!("compat embedder must not build without a base URL"),
Err(err) => err,
@@ -113,6 +115,7 @@ async fn factory_builds_compat_embedder_and_requires_base_url() {
api_key: SecretString::from(String::new()),
base_url: Some("http://localhost:11434/v1".into()),
models_dir: None,
+ defaulted: false,
});
assert!(
matches!(zero_dim, Err(LlmError::NotConfigured(ref msg)) if msg.contains("greater than zero")),
diff --git a/docs/MIGRATION-2.0.md b/docs/MIGRATION-2.0.md
index 1c43807d..174e008c 100644
--- a/docs/MIGRATION-2.0.md
+++ b/docs/MIGRATION-2.0.md
@@ -38,6 +38,18 @@ The migration is idempotent: restarting the server re-runs nothing and
never takes a second backup. Fresh installs skip all of it, including
the backup.
+## Embeddings on by default
+
+2.0 also turns on [local embeddings](local-embeddings.md) for installs
+that never configured an embedding provider: the first start downloads
+the ~87 MB model in the background (checksum-pinned, to
+`<data_dir>/models/`), the next start enables hybrid search, and
+existing pages are embedded automatically by a startup backfill. No
+data leaves the machine — inference is in-process. Hosts that cannot
+fetch the model keep the old FTS-only behaviour with a warning. Opt
+out with `embedding_provider = "none"`; installs with a configured
+provider are untouched.
+
## Running in a server or container (docker deploys)
Inside a container the home directory is **ephemeral** — it lives in
diff --git a/docs/local-embeddings.md b/docs/local-embeddings.md
index ae9e073a..d11641fe 100644
--- a/docs/local-embeddings.md
+++ b/docs/local-embeddings.md
@@ -6,9 +6,19 @@ required. Pure-Rust BERT inference (candle) with
`all-MiniLM-L6-v2` (384-dim), the sentence-transformers workhorse the
comparable memory servers ship by default.
+**As of 2.0 this is the default**: an install with no
+`embedding_provider` configured gets local embeddings automatically —
+best-effort. The model downloads in the background on the first start
+(hybrid search enables on the next restart), existing pages are
+backfilled automatically, and a host that cannot fetch the model (or a
+slim build without the feature) simply keeps the FTS-only behaviour
+with a warning. Opt out with `embedding_provider = "none"`; an
+explicitly configured provider is never overridden.
+
```toml
-# config.toml
-embedding_provider = "local" # model/dim default correctly
+# config.toml — all optional as of 2.0
+embedding_provider = "local" # explicit: hard-fails if unavailable
+# embedding_provider = "none" # opt out of vectors entirely
```
## Why: semantic recall without data egress
diff --git a/evals/src/retrieval/mod.rs b/evals/src/retrieval/mod.rs
index 11fe8ac1..88f6774c 100644
--- a/evals/src/retrieval/mod.rs
+++ b/evals/src/retrieval/mod.rs
@@ -69,6 +69,9 @@ pub struct RetrievalArgs {
}
pub async fn run(args: RetrievalArgs) -> Result<()> {
+ // Captured at launch: a long run must not stamp its report with a
+ // commit that landed while it was in flight.
+ let commit = report::commit_sha();
if args.fetch && !args.dataset.exists() {
dataset::fetch(&args.dataset).await?;
}
@@ -201,7 +204,7 @@ pub async fn run(args: RetrievalArgs) -> Result<()> {
let rep = report::Report {
generated_at: Timestamp::now().to_string(),
- commit: report::commit_sha(),
+ commit,
hardware: report::hardware(),
dataset: "longmemeval_s",
dataset_sha256: dataset::LONGMEMEVAL_S_SHA256,