Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(memory): recall facts about the user before the turn, never claim absence unsearched

Shanud11045e2254d
diff --git a/.claude/memory.md b/.claude/memory.md
index aeb5dca058..d8995ffa44 100644
--- a/.claude/memory.md
+++ b/.claude/memory.md
@@ -11,6 +11,7 @@ Quick reference for anyone starting with Claude on this project. Updated by the
- **Cargo incremental builds can serve stale UI** — If the app shows old frontend after a Rust rebuild, run `cargo clean --manifest-path app/src-tauri/Cargo.toml` before rebuilding.
- **`build.rs` missing `rerun-if-changed` causes stale ACL / "Command not found" at runtime** — `app/src-tauri/build.rs` had no `cargo:rerun-if-changed` directives for `permissions/` or `capabilities/`. Adding/changing TOML or JSON files there did not re-trigger `tauri-build`, so ACL tables were stale and registered commands silently failed. Fixed by adding `println!("cargo:rerun-if-changed=permissions")` and `println!("cargo:rerun-if-changed=capabilities")` in `build.rs` (issue #270). Also: any new Tauri command must have a matching entry in a `permissions/` TOML file or it will hit the same error even if it is in `generate_handler!`.
- **macOS deep links require .app bundle** — `pnpm tauri dev` does NOT support deep links. Must use `pnpm tauri build --debug --bundles app`.
+- **"I don't have that stored" on a personal question while the fact is in memory (issue #6040)** — the turn injects no memory of the user by itself, and the `MemoryAccessSection` instruction was gated on `learning.enabled` (default `false`), so the model was never told to look before claiming absence. Now: Lane C (`src/openhuman/memory/auto_recall/`) runs a lexically gated, bounded `fast_retrieve` through the session binding's guard and prepends a `## Relevant memory for this message` block to the **user message** (never the system prompt — KV-cache prefix); the instruction is added whenever a retrieval tool is registered, regardless of learning; `memory_recall` no longer requires `namespace`. Switch: `[subsystems.memory.hooks] auto_recall` / `OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL` — the flag existed before and was read by nothing. `core_turn.rs` sits near the 750-line gate: per-turn memory lanes live in `turn/recall_lanes.rs`, add there. `RecordingProvider::with_fast_retrieve_result` scripts the guarded retrieval family in tests. The sub-agent fast path (#4677) still skips entity-less queries; Lane C calls the engine directly, whose empty-entity path is dense retrieval. **Latency:** every `fast_retrieve` asks the host for spaCy over the bus (`memory_host.rs::extract_spacy` → the Python server) plus a query embed, so a warm lookup is ~1.5–3 s and the first after boot was >5 s (Python server + model load) — `memory::auto_recall::warm::spawn_at_boot`, hooked in `modules/boot.rs` right after the TinyMemory module loads, runs one throwaway retrieval so the user's first question is warm (measured: warm-up 2.4 s at boot, first real lookup 1.6 s). Lane budget is 5 s; `[memory_host] embed/extract_spacy elapsed_ms` debug lines give the split.
## Strict Rules
diff --git a/.env.example b/.env.example
index f58b734df9..aabafd2fc5 100644
--- a/.env.example
+++ b/.env.example
@@ -458,8 +458,12 @@ OPENHUMAN_ANALYTICS_ENABLED=true
# Subsystem driver binding ([subsystems.memory] — kernel.md §3.6)
# ---------------------------------------------------------------------------
# Which driver answers for the memory subsystem, and the memory-hook budgets.
-# NOTHING READS THESE YET — the config surface exists so bindings can be
-# authored ahead of the registry landing. Defaults reproduce today's behaviour.
+# `auto_recall` switches the pre-turn recall of facts about the user — the
+# "Relevant memory for this message" block a question like "who is my idol?"
+# gets; set it to false to turn that lane off. `recall_max_chars` bounds what
+# any recall may hand the model. The remaining knobs exist so bindings can be
+# authored ahead of the registry landing; nothing reads them yet. Defaults
+# reproduce today's behaviour.
# Per-driver option tables ([subsystems.memory.drivers.<id>], incl. the
# fail-closed `trust_state`) are config-file only; there is no env form.
# OPENHUMAN_MEMORY_DRIVER=tinycortex
diff --git a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
index 84732e0712..e0e2b10891 100644
--- a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
+++ b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
@@ -541,6 +541,35 @@ async fn build_session_agent_uses_profile_memory_instead_of_root_memory() {
assert!(!prompt.contains("shared root memory marker"));
}
+/// #6040 — the memory-access instruction is about the memory tools, not the
+/// learning subsystem, so it must be in the prompt with `learning.enabled`
+/// off (the default) whenever a retrieval tool is registered and visible.
+#[tokio::test]
+async fn memory_access_instruction_is_present_with_learning_disabled() {
+ crate::openhuman::memory::host_impls::install_for_tests();
+ use crate::openhuman::agent::context::prompt::LearnedContextData;
+ use crate::openhuman::agent::harness::session::types::Agent;
+ use crate::openhuman::agent::learning::MEMORY_ACCESS_INSTRUCTION;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.learning.enabled = false;
+
+ let agent = Agent::build_session_agent_inner(&config, "orchestrator", None, None, false, None)
+ .expect("build session agent");
+ let prompt = agent
+ .build_system_prompt(LearnedContextData::default())
+ .expect("build_system_prompt");
+ assert!(
+ prompt.contains(MEMORY_ACCESS_INSTRUCTION.trim()),
+ "the memory-access section must not be gated on learning.enabled"
+ );
+ assert!(
+ prompt.contains("Never say something is not stored"),
+ "the instruction must forbid claiming absence without a retrieval"
+ );
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// B38 (Gap 2) — a custom (non-shipped) `AgentRegistryEntry` must synthesize a
// real `AgentDefinition` and run with its own `ToolScope::Named` filter,
diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs
index bd3d76c029..729fccb2dd 100644
--- a/src/openhuman/agent/harness/session/builder/factory.rs
+++ b/src/openhuman/agent/harness/session/builder/factory.rs
@@ -256,14 +256,9 @@ impl Agent {
// raw SQLite handle the factory used to strip off the engine result.
// That handle was the #5378 `:290` blocker: a concrete connection no
// module or remote driver can supply. The engine's connection is now
- // exclusively the engine's.
- let archivist_provider = crate::openhuman::memory::binding::for_subtree(
- &config.workspace_dir,
- &memory_subdir,
- &config.subsystems.memory,
- )
- .map(|binding| binding.provider().clone())
- .map_err(|e| anyhow::anyhow!("archivist memory binding: {e}"))?;
+ // exclusively the engine's. Lane C (#6040) rides the same binding.
+ let (archivist_provider, auto_recall) =
+ super::helpers::bind_session_memory(config, &memory_subdir)?;
// Dedicated profiles still recall unstamped experiences written by
// pre-profile versions from the shared memory DB. Resolve that shared
// store once, here, and hand it to the session rather than making the
@@ -986,7 +981,9 @@ impl Agent {
// listing is build-time configurable)
// An empty `visible` set means "no filter" (wildcard / orchestrator
// path); in that case any registered retrieval tool is reachable.
- if config.learning.enabled {
+ // Not gated on `learning.enabled` (#6040): the instruction is about
+ // the memory tools, which exist whether or not learning runs.
+ {
let recall_tools = ["memory_recall", "memory_search"];
let has_retrieval = recall_tools.iter().any(|name| {
let registered = tools.iter().any(|t| t.name() == *name)
@@ -998,10 +995,10 @@ impl Agent {
prompt_builder = prompt_builder.add_section(Box::new(
crate::openhuman::agent::learning::MemoryAccessSection,
));
- log::debug!("[learning] memory_access prompt section registered");
+ log::debug!("[memory_access] prompt section registered");
} else {
log::debug!(
- "[learning] skipping MemoryAccessSection — neither memory_recall nor \
+ "[memory_access] skipping MemoryAccessSection — neither memory_recall nor \
memory_search is registered+visible for agent={agent_id}"
);
}
@@ -1215,6 +1212,7 @@ impl Agent {
.visible_tool_names(visible)
.memory(memory)
.shared_experience_memory(shared_experience_memory)
+ .auto_recall(Some(auto_recall))
.tool_dispatcher(tool_dispatcher)
.prompt_builder(prompt_builder)
.config(effective_agent_config)
diff --git a/src/openhuman/agent/harness/session/builder/helpers.rs b/src/openhuman/agent/harness/session/builder/helpers.rs
index c205c4fada..f0be2116c7 100644
--- a/src/openhuman/agent/harness/session/builder/helpers.rs
+++ b/src/openhuman/agent/harness/session/builder/helpers.rs
@@ -17,10 +17,31 @@
//! reached through this session's own `binding::for_subtree(..)`, which needs
//! the subtree passed in rather than the memory object.
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use crate::openhuman::memory::auto_recall::AutoRecall;
use crate::openhuman::memory::tool_memory::{tool_memory_store, ToolMemoryRule};
use crate::openhuman::memory::Memory;
use std::sync::Arc;
+/// Binds this session's memory subtree once and hands back the two handles
+/// the factory takes from it: the raw provider the archivist writes through,
+/// and Lane C (#6040) over the same binding's guard, so the auto-recall reads
+/// exactly the subtree the session chats against — a dedicated profile recalls
+/// its own facts, never the shared tree's.
+pub(super) fn bind_session_memory(
+ config: &crate::openhuman::config::Config,
+ memory_subdir: &str,
+) -> anyhow::Result<(Arc<dyn MemoryProvider>, Arc<AutoRecall>)> {
+ let binding = crate::openhuman::memory::binding::for_subtree(
+ &config.workspace_dir,
+ memory_subdir,
+ &config.subsystems.memory,
+ )
+ .map_err(|e| anyhow::anyhow!("archivist memory binding: {e}"))?;
+ let auto_recall = Arc::new(AutoRecall::from_guard(binding.guard()));
+ Ok((binding.provider().clone(), auto_recall))
+}
+
/// (#1400) Best-effort synchronous prefetch of eager tool-scoped rules.
///
/// `from_config_*` is sync but typically runs inside a multi-threaded
diff --git a/src/openhuman/agent/harness/session/builder/setters.rs b/src/openhuman/agent/harness/session/builder/setters.rs
index 4db73250fd..f418ee193c 100644
--- a/src/openhuman/agent/harness/session/builder/setters.rs
+++ b/src/openhuman/agent/harness/session/builder/setters.rs
@@ -24,6 +24,7 @@ impl AgentBuilder {
subagent_tool_ceiling_names: None,
memory: None,
shared_experience_memory: None,
+ auto_recall: None,
prompt_builder: None,
tool_dispatcher: None,
config: None,
@@ -122,6 +123,16 @@ impl AgentBuilder {
self
}
+ /// Binds Lane C, the gated pre-turn auto-recall of facts about the user
+ /// (#6040). `None` leaves the lane out of the turn entirely.
+ pub fn auto_recall(
+ mut self,
+ auto_recall: Option<Arc<crate::openhuman::memory::auto_recall::AutoRecall>>,
+ ) -> Self {
+ self.auto_recall = auto_recall;
+ self
+ }
+
/// Sets the system prompt builder for the agent.
pub fn prompt_builder(
mut self,
@@ -603,6 +614,7 @@ impl AgentBuilder {
.memory
.ok_or_else(|| anyhow::anyhow!("memory is required"))?,
shared_experience_memory: self.shared_experience_memory,
+ auto_recall: self.auto_recall,
tool_dispatcher: std::sync::Arc::from(
self.tool_dispatcher
.ok_or_else(|| anyhow::anyhow!("tool_dispatcher is required"))?,
diff --git a/src/openhuman/agent/harness/session/turn/core_turn.rs b/src/openhuman/agent/harness/session/turn/core_turn.rs
index 4a862472eb..8271578930 100644
--- a/src/openhuman/agent/harness/session/turn/core_turn.rs
+++ b/src/openhuman/agent/harness/session/turn/core_turn.rs
@@ -334,57 +334,13 @@ impl Agent {
// when it needs it, rather than every turn paying for a broad guess.
let mut context = String::new();
- // ── Lane B: situational preferences (every turn) ─────────────────────
- // Recall topic-scoped preferences semantically relevant to THIS message
- // (model-aware embeddings, gated by vector similarity) and inject them
- // under a banner. Runs every turn — unlike the first-turn-gated tree/STM
- // blocks above — because the query changes per message; it rides the
- // per-turn context that's prepended to the user message (no KV-cache
- // cost). An unrelated message clears the similarity gate to nothing, so
- // no block is injected.
- {
- // Bounded: this is the one memory await left on the turn's
- // critical path, and on a cold launch the memory module may still
- // be downloading behind it. A turn without a preference block is
- // an ordinary turn; a turn that waits minutes for one is the
- // outage this bound exists to prevent. The citation and autosave
- // work above is already spawned off the path.
- const SITUATIONAL_RECALL_BUDGET: std::time::Duration =
- std::time::Duration::from_secs(3);
- let situational = match tokio::time::timeout(
- SITUATIONAL_RECALL_BUDGET,
- crate::openhuman::memory::preferences::recall_situational_preferences_on(
- &self.memory,
- user_message,
- ),
- )
- .await
- {
- Ok(situational) => situational,
- Err(_elapsed) => {
- log::warn!(
- "[pref_recall] situational recall exceeded {SITUATIONAL_RECALL_BUDGET:?}; \
- continuing without a preference block"
- );
- Vec::new()
- }
- };
- if !situational.is_empty() {
- log::info!(
- "[pref_recall] situational block injected: {} item(s)",
- situational.len()
- );
- context.push_str("## Relevant preferences for this message\n\n");
- for pref in &situational {
- context.push_str("- ");
- context.push_str(pref.trim());
- context.push('\n');
- }
- context.push('\n');
- } else {
- log::debug!("[pref_recall] no situational preference relevant to this message");
- }
- }
+ // ── Lanes B and C: per-message memory (every turn) ───────────────────
+ // Situational preferences, and the gated auto-recall of facts about the
+ // user (#6040). Both are bounded — the only memory awaits left on the
+ // turn's critical path; citations and autosave above are spawned off
+ // it — and both ride this per-turn context rather than the cached
+ // system-prompt prefix. See `turn/recall_lanes.rs`.
+ super::recall_lanes::append_recall_lanes(self, user_message, &mut context).await;
// ── Thread goal (Codex-style per-thread completion contract) ─────────
// Load this thread's durable goal once per turn and prepend a compact
diff --git a/src/openhuman/agent/harness/session/turn/mod.rs b/src/openhuman/agent/harness/session/turn/mod.rs
index 6e80bbbc31..652877786f 100644
--- a/src/openhuman/agent/harness/session/turn/mod.rs
+++ b/src/openhuman/agent/harness/session/turn/mod.rs
@@ -4,6 +4,7 @@
mod context;
mod core;
mod graph;
+mod recall_lanes;
mod session_io;
mod tools;
diff --git a/src/openhuman/agent/harness/session/turn/recall_lanes.rs b/src/openhuman/agent/harness/session/turn/recall_lanes.rs
new file mode 100644
index 0000000000..686c0068c1
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn/recall_lanes.rs
@@ -0,0 +1,94 @@
+//! The per-message memory lanes of the turn's context.
+//!
+//! Both lanes fetch what memory holds for *this* message and prepend it to the
+//! user message — never to the system prompt, whose rendered bytes are the
+//! KV-cache prefix the inference backend has already tokenised. Both are
+//! bounded, because on a cold launch the memory module may still be
+//! downloading behind them: a turn without a block is an ordinary turn, a turn
+//! that waits minutes for one is the outage the bounds exist to prevent.
+//!
+//! - **Lane B** — situational preferences: topic-scoped preferences whose
+//! vector similarity to the message clears a floor. Runs every turn; an
+//! unrelated message clears the gate to nothing.
+//! - **Lane C** — auto-recall of facts about the user (#6040): opens only for
+//! a message that asks about the user, then one bounded tree lookup. See
+//! [`crate::openhuman::memory::auto_recall`] for the gate, the floor and the
+//! switch.
+//!
+//! The two run **side by side**. Each embeds the message on its own — there is
+//! no retrieval that takes a precomputed vector — so run in sequence the turn
+//! would pay the sum of two round trips; joined, it pays the slower one. The
+//! blocks are appended in a fixed order afterwards, so the prompt is stable
+//! whichever lane answers first.
+//!
+//! `core_turn.rs` documents the broad per-turn recall that used to live here
+//! and why it was removed; neither lane is that.
+
+use super::super::types::Agent;
+use std::time::Instant;
+
+/// Append the Lane B and Lane C blocks for `user_message` to `context`.
+pub(super) async fn append_recall_lanes(agent: &Agent, user_message: &str, context: &mut String) {
+ let (situational, auto_recall) = tokio::join!(
+ situational_preferences(agent, user_message),
+ auto_recall_block(agent, user_message),
+ );
+ if !situational.is_empty() {
+ context.push_str("## Relevant preferences for this message\n\n");
+ for pref in &situational {
+ context.push_str("- ");
+ context.push_str(pref.trim());
+ context.push('\n');
+ }
+ context.push('\n');
+ }
+ if let Some(block) = auto_recall {
+ context.push_str(&block);
+ }
+}
+
+/// Lane B: preferences semantically relevant to this message.
+async fn situational_preferences(agent: &Agent, user_message: &str) -> Vec<String> {
+ const SITUATIONAL_RECALL_BUDGET: std::time::Duration = std::time::Duration::from_secs(3);
+ let started = Instant::now();
+ let situational = match tokio::time::timeout(
+ SITUATIONAL_RECALL_BUDGET,
+ crate::openhuman::memory::preferences::recall_situational_preferences_on(
+ &agent.memory,
+ user_message,
+ ),
+ )
+ .await
+ {
+ Ok(situational) => situational,
+ Err(_elapsed) => {
+ log::warn!(
+ "[pref_recall] situational recall exceeded {SITUATIONAL_RECALL_BUDGET:?}; \
+ continuing without a preference block"
+ );
+ return Vec::new();
+ }
+ };
+ if situational.is_empty() {
+ log::debug!(
+ "[pref_recall] no situational preference relevant to this message elapsed_ms={}",
+ started.elapsed().as_millis()
+ );
+ } else {
+ log::info!(
+ "[pref_recall] situational block injected: {} item(s) elapsed_ms={}",
+ situational.len(),
+ started.elapsed().as_millis()
+ );
+ }
+ situational
+}
+
+/// Lane C: the gated auto-recall block, when the session has the lane bound.
+async fn auto_recall_block(agent: &Agent, user_message: &str) -> Option<String> {
+ let Some(auto_recall) = agent.auto_recall.as_ref() else {
+ log::debug!("[auto_recall] no lane bound to this session; skipping");
+ return None;
+ };
+ auto_recall.block_for(user_message).await
+}
diff --git a/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs b/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
index 410176bcb7..1741bb253d 100644
--- a/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
@@ -462,3 +462,229 @@ fn skill_retraction_note_names_removed_skills_and_warns_against_run_skill() {
"retraction note must not look like an install announcement: {note}"
);
}
+
+// ── Lane C: auto-recall of facts about the user (#6040) ──────────────────────
+//
+// The lane is exercised through a real `turn()`: a scripted source stands in
+// for the memory driver, the scripted chat model records every request, and
+// the assertions read the user message the model was actually sent.
+
+use crate::openhuman::memory::api::error::MemoryError;
+use crate::openhuman::memory::api::provider::retrieval::{
+ FastRetrieveQuery, RetrievalHit, RetrievalNodeKind, RetrievalResponse,
+};
+use crate::openhuman::memory::auto_recall::{AutoRecall, AutoRecallSource, AUTO_RECALL_BANNER};
+
+const IDOL_QUESTION: &str = "who is my idol and why?";
+const IDOL_FACT: &str = "Idol: Virat Kohli, because of his dedication and consistency";
+
+struct ScriptedAutoRecallSource {
+ hits: Vec<RetrievalHit>,
+ delay: Duration,
+ calls: AtomicUsize,
+}
+
+impl ScriptedAutoRecallSource {
+ fn with_fact(content: &str) -> Arc<Self> {
+ Arc::new(Self {
+ hits: vec![RetrievalHit {
+ node_id: "leaf-1".into(),
+ node_kind: RetrievalNodeKind::Leaf,
+ tree_id: String::new(),
+ tree_kind: None,
+ tree_scope: "folder:profile".into(),
+ level: 0,
+ content: content.to_string(),
+ entities: Vec::new(),
+ topics: Vec::new(),
+ time_range_start: chrono::DateTime::<chrono::Utc>::default(),
+ time_range_end: chrono::DateTime::<chrono::Utc>::default(),
+ score: 0.9,
+ child_ids: Vec::new(),
+ source_ref: None,
+ }],
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn slow(content: &str, delay: Duration) -> Arc<Self> {
+ let mut source = Arc::try_unwrap(Self::with_fact(content))
+ .ok()
+ .expect("fresh arc");
+ source.delay = delay;
+ Arc::new(source)
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+}
+
+#[async_trait]
+impl AutoRecallSource for ScriptedAutoRecallSource {
+ async fn fast_retrieve(
+ &self,
+ _query: &str,
+ _options: FastRetrieveQuery,
+ ) -> Result<RetrievalResponse, MemoryError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if !self.delay.is_zero() {
+ tokio::time::sleep(self.delay).await;
+ }
+ Ok(RetrievalResponse {
+ total: self.hits.len(),
+ hits: self.hits.clone(),
+ truncated: false,
+ })
+ }
+}
+
+fn scripted_reply(text: &str) -> Arc<SequenceProvider> {
+ Arc::new(SequenceProvider {
+ responses: AsyncMutex::new(vec![Ok(ChatResponse {
+ text: Some(text.into()),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ })]),
+ requests: AsyncMutex::new(Vec::new()),
+ tool_counts: AsyncMutex::new(Vec::new()),
+ })
+}
+
+/// A turn-capable agent with Lane C bound (or deliberately absent), over the
+/// same real embedded store the other turn tests use.
+fn make_agent_with_auto_recall(
+ provider: Arc<dyn ChatModel<()>>,
+ auto_recall: Option<Arc<AutoRecall>>,
+) -> Agent {
+ let workspace = tempfile::TempDir::new().expect("temp workspace");
+ let workspace_path = workspace.path().to_path_buf();
+ std::mem::forget(workspace);
+ let memory_cfg = crate::openhuman::config::MemoryConfig {
+ backend: "none".into(),
+ ..crate::openhuman::config::MemoryConfig::default()
+ };
+ crate::openhuman::memory::host_impls::install_for_tests();
+ let mem: Arc<dyn Memory> =
+ Arc::from(tinymemory_core::store::create_memory(&memory_cfg, &workspace_path).unwrap());
+
+ Agent::builder()
+ .chat_model(provider)
+ .tools(vec![])
+ .memory(mem)
+ .auto_recall(auto_recall)
+ .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .config(crate::openhuman::config::AgentConfig::default())
+ .context_config(crate::openhuman::config::ContextConfig::default())
+ .workspace_dir(workspace_path)
+ .event_context("turn-test-session", "turn-test-channel")
+ .build()
+ .unwrap()
+}
+
+/// The messages the model was sent on the first (only) request, split by role.
+async fn first_request(provider: &SequenceProvider) -> (Vec<String>, Vec<String>) {
+ let requests = provider.requests.lock().await;
+ let request = requests.first().expect("the model was called once");
+ let system = request
+ .iter()
+ .filter(|m| m.role == "system")
+ .map(|m| m.content.clone())
+ .collect();
+ let user = request
+ .iter()
+ .filter(|m| m.role == "user")
+ .map(|m| m.content.clone())
+ .collect();
+ (system, user)
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn auto_recall_block_rides_the_user_message_for_a_personal_question() {
+ let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
+ let lane = Arc::new(AutoRecall::new(source.clone(), true, None));
+ let provider_impl = scripted_reply("Virat Kohli, for his dedication and consistency.");
+ let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
+ let mut agent = make_agent_with_auto_recall(provider, Some(lane));
+
+ let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
+ assert!(reply.contains("Virat"));
+ assert_eq!(source.calls(), 1, "one bounded lookup for one gated turn");
+
+ let (system, user) = first_request(&provider_impl).await;
+ let last_user = user.last().expect("a user message");
+ assert!(
+ last_user.contains(AUTO_RECALL_BANNER) && last_user.contains("Virat Kohli"),
+ "the block must ride the user message: {last_user}"
+ );
+ assert!(
+ last_user.contains(IDOL_QUESTION),
+ "the user's own words must follow the block: {last_user}"
+ );
+ assert!(
+ system.iter().all(|s| !s.contains(AUTO_RECALL_BANNER)),
+ "the block must never land in the system prompt"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn auto_recall_stays_silent_and_costs_nothing_on_small_talk() {
+ let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
+ let lane = Arc::new(AutoRecall::new(source.clone(), true, None));
+ let provider_impl = scripted_reply("Sunny, probably.");
+ let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
+ let mut agent = make_agent_with_auto_recall(provider, Some(lane));
+
+ agent
+ .turn("what's the weather today")
+ .await
+ .expect("turn succeeds");
+ assert_eq!(source.calls(), 0, "a closed gate never reaches the store");
+ let (_, user) = first_request(&provider_impl).await;
+ assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn auto_recall_disabled_by_the_hooks_switch_injects_nothing() {
+ let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
+ let lane = Arc::new(AutoRecall::new(source.clone(), false, None));
+ let provider_impl = scripted_reply("I don't have that stored.");
+ let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
+ let mut agent = make_agent_with_auto_recall(provider, Some(lane));
+
+ agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
+ assert_eq!(source.calls(), 0);
+ let (_, user) = first_request(&provider_impl).await;
+ assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn auto_recall_timeout_yields_an_ordinary_turn() {
+ let source = ScriptedAutoRecallSource::slow(IDOL_FACT, Duration::from_millis(300));
+ let lane = Arc::new(
+ AutoRecall::new(source.clone(), true, None).with_budget(Duration::from_millis(20)),
+ );
+ let provider_impl = scripted_reply("Still here.");
+ let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
+ let mut agent = make_agent_with_auto_recall(provider, Some(lane));
+
+ let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
+ assert_eq!(reply, "Still here.");
+ assert_eq!(source.calls(), 1);
+ let (_, user) = first_request(&provider_impl).await;
+ assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_session_without_the_lane_turns_as_before() {
+ let provider_impl = scripted_reply("Hello.");
+ let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
+ let mut agent = make_agent_with_auto_recall(provider, None);
+
+ let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
+ assert_eq!(reply, "Hello.");
+ let (_, user) = first_request(&provider_impl).await;
+ assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
+}
diff --git a/src/openhuman/agent/harness/session/types.rs b/src/openhuman/agent/harness/session/types.rs
index ad0a343a82..1433c2a0b3 100644
--- a/src/openhuman/agent/harness/session/types.rs
+++ b/src/openhuman/agent/harness/session/types.rs
@@ -102,6 +102,10 @@ pub struct Agent {
/// experience recall can merge unstamped legacy guidance. `None` for the
/// shared/default memory path.
pub(super) shared_experience_memory: Option<Arc<dyn Memory>>,
+ /// Lane C — the gated pre-turn recall of facts about the user (#6040).
+ /// `None` when the session was built without a memory binding (tests,
+ /// embedders that bring their own `Memory`); the lane then stays silent.
+ pub(super) auto_recall: Option<Arc<crate::openhuman::memory::auto_recall::AutoRecall>>,
// `Arc` (not `Box`) so the tinyagents turn path can hold a cheap clone of
// the dispatcher without borrowing the `Agent` while session state mutates.
pub(super) tool_dispatcher: Arc<dyn ToolDispatcher>,
@@ -483,6 +487,8 @@ pub struct AgentBuilder {
pub(super) subagent_tool_ceiling_names: Option<std::collections::HashSet<String>>,
pub(super) memory: Option<Arc<dyn Memory>>,
pub(super) shared_experience_memory: Option<Arc<dyn Memory>>,
+ /// Forwarded to [`Agent::auto_recall`] at build time. Defaults to `None`.
+ pub(super) auto_recall: Option<Arc<crate::openhuman::memory::auto_recall::AutoRecall>>,
pub(super) prompt_builder: Option<SystemPromptBuilder>,
pub(super) tool_dispatcher: Option<Box<dyn ToolDispatcher>>,
pub(super) config: Option<crate::openhuman::config::AgentConfig>,
diff --git a/src/openhuman/agent/learning/prompt_sections.rs b/src/openhuman/agent/learning/prompt_sections.rs
index 1260fe5bde..f0c7caf70c 100644
--- a/src/openhuman/agent/learning/prompt_sections.rs
+++ b/src/openhuman/agent/learning/prompt_sections.rs
@@ -101,23 +101,31 @@ impl PromptSection for UserProfileSection {
/// Static bias instruction that tells the agent to call `memory_recall` before
/// answering questions involving named people, projects, prior decisions, or
-/// anything the user mentioned in past sessions.
+/// anything the user mentioned in past sessions — and never to claim something
+/// is not stored without having looked (#6040).
///
/// The text is frozen at compile time — no I/O at build time.
/// Register this section after [`LearnedContextSection`] in the prompt-section
-/// composition order (see `SystemPromptBuilder::with_defaults`).
+/// composition order (see `SystemPromptBuilder::with_defaults`). It is added
+/// whenever a retrieval tool is registered and visible, independently of
+/// `learning.enabled`: the instruction is about the memory tools, which exist
+/// whether or not the learning subsystem runs.
pub struct MemoryAccessSection;
-/// The static prose injected into every system prompt. Kept at ≤ 80 tokens.
+/// The static prose injected into every system prompt. Kept at ≤ 100 words
+/// (the composition test pins that ceiling).
pub const MEMORY_ACCESS_INSTRUCTION: &str = "\
## Memory access\n\
\n\
Before answering questions involving named people, projects, threads, prior \
decisions, recurring topics, or anything the user has mentioned in past sessions, \
call `memory_recall` (or `memory_search` for keyword lookups) to retrieve \
-relevant context. Surface what matters in your reply; don't stitch together \
-continuity from prompt history alone. Skip retrieval for purely procedural \
-requests where prior context isn't relevant.";
+relevant context. Questions about the user themselves — favourites, idols, \
+people, plans, habits — always warrant a retrieval first. Never say something is \
+not stored or not remembered unless a retrieval you just ran returned nothing. \
+Surface what matters in your reply; don't stitch together continuity from prompt \
+history alone. Skip retrieval for purely procedural requests where prior context \
+isn't relevant.";
impl PromptSection for MemoryAccessSection {
fn name(&self) -> &str {
diff --git a/src/openhuman/memory/auto_recall/auto_recall_tests.rs b/src/openhuman/memory/auto_recall/auto_recall_tests.rs
new file mode 100644
index 0000000000..6ab331b139
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/auto_recall_tests.rs
@@ -0,0 +1,285 @@
+use super::*;
+use crate::openhuman::memory::api::error::MemoryError;
+use crate::openhuman::memory::api::provider::retrieval::{RetrievalNodeKind, RetrievalResponse};
+use crate::openhuman::memory::guard::test_support::{
+ embedded_policy, guarded_with, RecordingProvider,
+};
+use async_trait::async_trait;
+use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
+use std::sync::Mutex;
+
+const QUESTION: &str = "who is my idol and why?";
+
+fn hit(content: &str, score: f32) -> RetrievalHit {
+ RetrievalHit {
+ node_id: format!("n-{}", content.len()),
+ node_kind: RetrievalNodeKind::Leaf,
+ tree_id: String::new(),
+ tree_kind: None,
+ tree_scope: String::new(),
+ level: 0,
+ content: content.to_string(),
+ entities: Vec::new(),
+ topics: Vec::new(),
+ time_range_start: chrono::DateTime::<chrono::Utc>::default(),
+ time_range_end: chrono::DateTime::<chrono::Utc>::default(),
+ score,
+ child_ids: Vec::new(),
+ source_ref: None,
+ }
+}
+
+fn response(hits: Vec<RetrievalHit>) -> RetrievalResponse {
+ let total = hits.len();
+ RetrievalResponse {
+ hits,
+ total,
+ truncated: false,
+ }
+}
+
+/// A source that answers with a scripted response, optionally slowly or with
+/// an error, and counts how often it was asked.
+struct Scripted {
+ outcome: Mutex<Result<RetrievalResponse, String>>,
+ delay: Duration,
+ calls: AtomicUsize,
+}
+
+impl Scripted {
+ fn hits(hits: Vec<RetrievalHit>) -> Arc<Self> {
+ Arc::new(Self {
+ outcome: Mutex::new(Ok(response(hits))),
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn failing(message: &str) -> Arc<Self> {
+ Arc::new(Self {
+ outcome: Mutex::new(Err(message.to_string())),
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn slow(hits: Vec<RetrievalHit>, delay: Duration) -> Arc<Self> {
+ Arc::new(Self {
+ outcome: Mutex::new(Ok(response(hits))),
+ delay,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(AtomicOrdering::SeqCst)
+ }
+}
+
+#[async_trait]
+impl AutoRecallSource for Scripted {
+ async fn fast_retrieve(
+ &self,
+ _query: &str,
+ _options: FastRetrieveQuery,
+ ) -> Result<RetrievalResponse, MemoryError> {
+ self.calls.fetch_add(1, AtomicOrdering::SeqCst);
+ if !self.delay.is_zero() {
+ tokio::time::sleep(self.delay).await;
+ }
+ match &*self.outcome.lock().unwrap() {
+ Ok(response) => Ok(response.clone()),
+ Err(message) => Err(MemoryError::Backend(message.clone())),
+ }
+ }
+}
+
+// ── select_hits ──────────────────────────────────────────────────────────────
+
+#[test]
+fn select_hits_ranks_best_first_and_caps_at_the_limit() {
+ let hits = select_hits(vec![
+ hit("third", 0.7),
+ hit("first", 0.9),
+ hit("fourth", 0.6),
+ hit("second", 0.8),
+ ]);
+ let contents: Vec<&str> = hits.iter().map(|h| h.content.as_str()).collect();
+ assert_eq!(contents, vec!["first", "second", "third"]);
+}
+
+#[test]
+fn select_hits_drops_the_weak_tail_below_the_relative_floor() {
+ let hits = select_hits(vec![hit("strong", 1.0), hit("weak", 0.2), hit("ok", 0.6)]);
+ let contents: Vec<&str> = hits.iter().map(|h| h.content.as_str()).collect();
+ assert_eq!(contents, vec!["strong", "ok"]);
+}
+
+#[test]
+fn select_hits_keeps_order_when_scores_carry_no_signal() {
+ // A driver that reports 0.0 for everything still ranked them; keep that.
+ let hits = select_hits(vec![
+ hit("a", 0.0),
+ hit("b", 0.0),
+ hit("c", 0.0),
+ hit("d", 0.0),
+ ]);
+ assert_eq!(hits.len(), AUTO_RECALL_LIMIT);
+ assert_eq!(hits[0].content, "a");
+}
+
+#[test]
+fn select_hits_drops_empty_content_before_ranking() {
+ let hits = select_hits(vec![hit(" ", 1.0), hit("real", 0.4)]);
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].content, "real");
+}
+
+// ── render_block ─────────────────────────────────────────────────────────────
+
+#[test]
+fn render_block_is_a_banner_plus_one_line_per_hit() {
+ let mut scoped = hit("Idol: Virat Kohli, for his dedication and consistency", 0.9);
+ scoped.tree_scope = "folder:profile".into();
+ let block = render_block(&[scoped, hit("Favourite colour: black", 0.5)], None);
+ assert!(block.starts_with(AUTO_RECALL_BANNER));
+ assert!(block.contains(
+ "- Idol: Virat Kohli, for his dedication and consistency (from folder:profile)\n"
+ ));
+ assert!(block.contains("- Favourite colour: black\n"));
+ assert!(block.ends_with("\n\n"));
+}
+
+#[test]
+fn render_block_collapses_whitespace_and_clips_each_hit() {
+ let long = format!(
+ "line one\n\n line two {}",
+ "x".repeat(AUTO_RECALL_PER_HIT_CHARS)
+ );
+ let block = render_block(&[hit(&long, 1.0)], None);
+ assert!(block.contains("- line one line two x"));
+ assert!(!block.contains('\n'.to_string().repeat(3).as_str()));
+ assert!(block.contains('…'), "a clipped hit must say so");
+}
+
+#[test]
+fn render_block_honours_the_recall_budget() {
+ let block = render_block(&[hit(&"y".repeat(300), 1.0)], Some(80));
+ assert!(block.chars().count() <= 80 + "…\n\n".chars().count());
+ assert!(block.ends_with("…\n\n"));
+}
+
+// ── block_for ────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn block_for_injects_the_fact_for_an_about_me_question() {
+ let source = Scripted::hits(vec![hit(
+ "Idol: Virat Kohli, because of his dedication and consistency",
+ 0.9,
+ )]);
+ let lane = AutoRecall::new(source.clone(), true, None);
+ let block = lane.block_for(QUESTION).await.expect("a block");
+ assert!(block.starts_with(AUTO_RECALL_BANNER));
+ assert!(block.contains("Virat Kohli"));
+ assert_eq!(source.calls(), 1);
+}
+
+#[tokio::test]
+async fn block_for_never_touches_the_source_when_the_gate_is_closed() {
+ let source = Scripted::hits(vec![hit("anything", 1.0)]);
+ let lane = AutoRecall::new(source.clone(), true, None);
+ assert!(lane.block_for("what's the weather today").await.is_none());
+ assert!(lane.block_for("fix my code").await.is_none());
+ assert_eq!(source.calls(), 0);
+}
+
+#[tokio::test]
+async fn block_for_is_silent_when_disabled() {
+ let source = Scripted::hits(vec![hit("anything", 1.0)]);
+ let lane = AutoRecall::new(source.clone(), false, None);
+ assert!(!lane.enabled());
+ assert!(lane.block_for(QUESTION).await.is_none());
+ assert_eq!(source.calls(), 0);
+}
+
+#[tokio::test]
+async fn block_for_yields_nothing_when_no_hit_survives() {
+ let source = Scripted::hits(vec![hit(" ", 1.0)]);
+ let lane = AutoRecall::new(source.clone(), true, None);
+ assert!(lane.block_for(QUESTION).await.is_none());
+ assert_eq!(source.calls(), 1);
+}
+
+#[tokio::test]
+async fn block_for_degrades_on_a_retrieval_error() {
+ let source = Scripted::failing("store locked");
+ let lane = AutoRecall::new(source.clone(), true, None);
+ assert!(lane.block_for(QUESTION).await.is_none());
+ assert_eq!(source.calls(), 1);
+}
+
+#[tokio::test]
+async fn block_for_degrades_when_the_budget_expires() {
+ let source = Scripted::slow(vec![hit("late", 1.0)], Duration::from_millis(200));
+ let lane = AutoRecall::new(source.clone(), true, None).with_budget(Duration::from_millis(20));
+ assert!(lane.block_for(QUESTION).await.is_none());
+ assert_eq!(source.calls(), 1);
+}
+
+#[tokio::test]
+async fn block_for_applies_the_guard_recall_budget() {
+ let source = Scripted::hits(vec![hit(&"z".repeat(300), 1.0)]);
+ let lane = AutoRecall::new(source, true, Some(60));
+ let block = lane.block_for(QUESTION).await.expect("a block");
+ assert!(block.chars().count() <= 60 + "…\n\n".chars().count());
+}
+
+// ── from_guard ───────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn from_guard_reads_through_the_guarded_retrieval_family() {
+ let provider = RecordingProvider::new().with_fast_retrieve_result(response(vec![hit(
+ "Idol: Virat Kohli, because of his dedication and consistency",
+ 0.8,
+ )]));
+ let (provider, guard) = guarded_with(provider, embedded_policy());
+ let lane = AutoRecall::from_guard(Arc::new(guard));
+ assert!(lane.enabled(), "the shipped policy has auto_recall on");
+
+ let block = lane.block_for(QUESTION).await.expect("a block");
+ assert!(block.contains("Virat Kohli"));
+ let call = provider.only_call();
+ assert_eq!(call.method, "retrieval.fast_retrieve");
+}
+
+#[tokio::test]
+async fn from_guard_honours_the_hooks_switch() {
+ let hooks = crate::openhuman::config::schema::MemoryHooksConfig {
+ auto_recall: false,
+ ..Default::default()
+ };
+ let policy = crate::openhuman::memory::guard::GuardPolicy::new(
+ "recording",
+ crate::core::subsystem::DriverClass::Embedded,
+ hooks,
+ "trusted",
+ );
+ let (provider, guard) = guarded_with(RecordingProvider::new(), policy);
+ let lane = AutoRecall::from_guard(Arc::new(guard));
+ assert!(!lane.enabled());
+ assert!(lane.block_for(QUESTION).await.is_none());
+ assert_eq!(provider.call_count(), 0);
+}
+
+#[tokio::test]
+async fn from_guard_over_a_driver_without_retrieval_stays_silent() {
+ // The null driver advertises no capability, so the guard builds no
+ // retrieval family: the lane must degrade to "nothing", not to an error.
+ let inner: Arc<dyn crate::openhuman::memory::api::provider::MemoryProvider> =
+ Arc::new(tinymemory_api::null::NullMemoryProvider);
+ let guard =
+ crate::openhuman::memory::guard::MemoryGuard::new(inner, Arc::new(embedded_policy()));
+ let lane = AutoRecall::from_guard(Arc::new(guard));
+ assert!(lane.enabled());
+ assert!(lane.block_for(QUESTION).await.is_none());
+}
diff --git a/src/openhuman/memory/auto_recall/gate.rs b/src/openhuman/memory/auto_recall/gate.rs
new file mode 100644
index 0000000000..6c2236c344
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/gate.rs
@@ -0,0 +1,107 @@
+//! The gate in front of Lane C: is this message asking about the user?
+//!
+//! Deciding that with words costs nothing — no embedding, no store — which is
+//! what lets the lane run on every turn without paying on every turn. The rule
+//! is deliberately narrow: a message must **own** something (`my`, `me`, `I`,
+//! …) **and** ask or request (`who … ?`, `what's …`, `tell me …`, `remind me
+//! …`). "Fix my code" owns but does not ask; "what's the weather" asks but owns
+//! nothing; neither reaches the store. A false positive costs one bounded tree
+//! lookup that injects nothing; a false negative is covered by the standing
+//! memory-access instruction, which tells the model to retrieve before it
+//! claims something is not stored.
+//!
+//! The word lists are English. A message in another language passes only if
+//! it happens to contain one of these tokens, so non-English users fall back
+//! to the instruction-driven path. A fingerprint-similarity gate over a few
+//! stock "about me" prototypes would lift that limit at the cost of one embed
+//! per candidate turn; it is deferred until real gate logs say the lexical
+//! rule misses enough to be worth it.
+
+/// Messages longer than this are pastes, transcripts or briefs, not questions
+/// about the user. They never reach the store.
+const MAX_MESSAGE_CHARS: usize = 600;
+
+/// First-person ownership or self-reference. Apostrophes are stripped before
+/// matching, so `i've` and `ive` both land on the same entry.
+const FIRST_PERSON: &[&str] = &["my", "me", "mine", "myself", "i", "im", "ive", "id", "ill"];
+
+/// A leading word that makes the message a question or a request. Terminal
+/// `?` is the other way in.
+const LEADS: &[&str] = &[
+ "who", "whos", "what", "whats", "which", "why", "when", "where", "how", "hows", "do", "does",
+ "did", "am", "is", "are", "was", "were", "can", "could", "would", "should", "have", "has",
+ "tell", "remind", "recall", "remember", "describe", "list", "name",
+];
+
+/// What the gate decided, and why. The reason is a stable slug for the
+/// `[auto_recall]` log line and for tests.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum GateDecision {
+ /// Run the lookup.
+ Open(&'static str),
+ /// Skip it.
+ Closed(&'static str),
+}
+
+impl GateDecision {
+ /// Whether the lookup runs.
+ pub fn is_open(self) -> bool {
+ matches!(self, Self::Open(_))
+ }
+
+ /// The slug behind the decision.
+ pub fn reason(self) -> &'static str {
+ match self {
+ Self::Open(reason) | Self::Closed(reason) => reason,
+ }
+ }
+}
+
+/// Decide whether `message` asks about the user.
+pub fn gate_decision(message: &str) -> GateDecision {
+ let trimmed = message.trim();
+ if trimmed.is_empty() {
+ return GateDecision::Closed("empty");
+ }
+ if trimmed.contains("```") {
+ return GateDecision::Closed("code_block");
+ }
+ if trimmed.chars().count() > MAX_MESSAGE_CHARS {
+ return GateDecision::Closed("too_long");
+ }
+
+ let words = words_of(trimmed);
+ if !words
+ .iter()
+ .any(|word| FIRST_PERSON.contains(&word.as_str()))
+ {
+ return GateDecision::Closed("no_first_person");
+ }
+ let asks = trimmed.ends_with('?')
+ || words
+ .first()
+ .is_some_and(|word| LEADS.contains(&word.as_str()));
+ if !asks {
+ return GateDecision::Closed("not_a_question");
+ }
+ GateDecision::Open("lexical")
+}
+
+/// Lower-cased words with apostrophes (straight or curly) removed, so
+/// `What’s` becomes `whats` and `I've` becomes `ive`.
+fn words_of(text: &str) -> Vec<String> {
+ text.split(|c: char| !(c.is_alphanumeric() || c == '\'' || c == '\u{2019}'))
+ .filter(|word| !word.is_empty())
+ .map(|word| {
+ word.chars()
+ .filter(|c| *c != '\'' && *c != '\u{2019}')
+ .collect::<String>()
+ .to_lowercase()
+ })
+ .filter(|word| !word.is_empty())
+ .collect()
+}
+
+#[cfg(test)]
+#[path = "gate_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/auto_recall/gate_tests.rs b/src/openhuman/memory/auto_recall/gate_tests.rs
new file mode 100644
index 0000000000..f515012edc
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/gate_tests.rs
@@ -0,0 +1,153 @@
+use super::*;
+
+/// Messages that ask about the user: the gate must open on every one.
+const OPENS: &[&str] = &[
+ "who is my idol and why?",
+ "what's my favourite colour",
+ "What is my favorite cricketer?",
+ "why do I admire virat?",
+ "tell me my reason for choosing virat as idol",
+ "remind me what my sister's name is",
+ "do you remember what I told you about my trip?",
+ "which web series do I like the most?",
+ "what did I say my goals were?",
+ "how do I usually take my coffee?",
+ "where do I work?",
+ "when is my birthday?",
+ "what do I like to eat",
+ "Do I have any allergies?",
+ "can you tell me what my timezone is?",
+ "what are my hobbies?",
+ "recall what I said about my manager",
+ "what's my dog's name?",
+ "am I a morning person?",
+ "who are my closest friends?",
+ "what did i tell you about my startup",
+ "Which city do I live in?",
+ "how many kids do I have?",
+ "what languages do I speak?",
+ "what is my role at work?",
+ "did I mention my favourite book?",
+ "what\u{2019}s my idol\u{2019}s best quality?",
+ "who did I say I look up to?",
+ "is my favourite colour black?",
+ "describe my ideal weekend based on what I've shared",
+ "have I told you about my parents?",
+ "list my favourite movies",
+];
+
+/// Messages that are not about the user: the gate must stay closed.
+const CLOSES: &[(&str, &str)] = &[
+ ("what's the weather today", "no_first_person"),
+ ("fix my code, it throws on line 12", "not_a_question"),
+ ("summarise this article", "no_first_person"),
+ ("thanks!", "no_first_person"),
+ ("ok", "no_first_person"),
+ ("write a haiku about autumn", "no_first_person"),
+ ("what is the capital of france?", "no_first_person"),
+ ("translate this to spanish: hello", "no_first_person"),
+ ("how does tokio spawn work?", "no_first_person"),
+ ("explain rust lifetimes", "no_first_person"),
+ (
+ "```rust\nfn main() {}\n```\nwhat does my code do?",
+ "code_block",
+ ),
+ ("run the tests", "no_first_person"),
+ ("who won the 2024 world cup?", "no_first_person"),
+ ("generate an image of a cat", "no_first_person"),
+ ("convert 10 miles to km", "no_first_person"),
+ ("what time is it in tokyo?", "no_first_person"),
+ ("give me a summary of the meeting notes", "not_a_question"),
+ ("send my email to the team", "not_a_question"),
+ ("open my calendar", "not_a_question"),
+ ("search the web for rust async patterns", "no_first_person"),
+ ("hello", "no_first_person"),
+ ("why is the sky blue?", "no_first_person"),
+ ("let's plan the sprint", "no_first_person"),
+ ("i think we should refactor this module", "not_a_question"),
+ ("I'll be back in 10 minutes", "not_a_question"),
+ ("how are you?", "no_first_person"),
+ ("what's 2+2?", "no_first_person"),
+ ("does this function handle null?", "no_first_person"),
+ ("deploy my branch to staging", "not_a_question"),
+ ("", "empty"),
+ (" \n ", "empty"),
+];
+
+#[test]
+fn opens_on_every_about_me_question() {
+ let missed: Vec<&str> = OPENS
+ .iter()
+ .copied()
+ .filter(|message| !gate_decision(message).is_open())
+ .collect();
+ assert!(
+ missed.is_empty(),
+ "gate stayed closed on about-me messages: {missed:?}"
+ );
+ assert!(OPENS.len() >= 30, "fixture must stay representative");
+}
+
+#[test]
+fn closes_on_every_other_message_with_the_expected_reason() {
+ let wrong: Vec<(&str, &str, GateDecision)> = CLOSES
+ .iter()
+ .copied()
+ .filter_map(|(message, reason)| {
+ let decision = gate_decision(message);
+ (decision != GateDecision::Closed(reason)).then_some((message, reason, decision))
+ })
+ .collect();
+ assert!(wrong.is_empty(), "unexpected gate decisions: {wrong:?}");
+ assert!(CLOSES.len() >= 30, "fixture must stay representative");
+}
+
+#[test]
+fn precision_and_recall_clear_the_bar() {
+ // The acceptance bar is ≥ 90 % both ways; the fixtures above pin 100 %,
+ // and this guards the bar itself if someone loosens an individual case.
+ let recall = OPENS
+ .iter()
+ .filter(|message| gate_decision(message).is_open())
+ .count() as f64
+ / OPENS.len() as f64;
+ let precision = CLOSES
+ .iter()
+ .filter(|(message, _)| !gate_decision(message).is_open())
+ .count() as f64
+ / CLOSES.len() as f64;
+ assert!(recall >= 0.9, "recall {recall}");
+ assert!(precision >= 0.9, "precision {precision}");
+}
+
+#[test]
+fn long_messages_are_pastes_not_questions() {
+ let long = format!("what is my {}?", "very ".repeat(200));
+ assert_eq!(gate_decision(&long), GateDecision::Closed("too_long"));
+}
+
+#[test]
+fn curly_apostrophes_do_not_hide_the_lead_word() {
+ assert_eq!(
+ gate_decision("what\u{2019}s my idol\u{2019}s name"),
+ GateDecision::Open("lexical")
+ );
+}
+
+#[test]
+fn reason_and_is_open_agree() {
+ let open = GateDecision::Open("lexical");
+ let closed = GateDecision::Closed("empty");
+ assert!(open.is_open());
+ assert!(!closed.is_open());
+ assert_eq!(open.reason(), "lexical");
+ assert_eq!(closed.reason(), "empty");
+}
+
+#[test]
+fn words_are_lowercased_and_stripped_of_apostrophes() {
+ assert_eq!(
+ words_of("I've Got My idol\u{2019}s NAME"),
+ vec!["ive", "got", "my", "idols", "name"]
+ );
+}
diff --git a/src/openhuman/memory/auto_recall/mod.rs b/src/openhuman/memory/auto_recall/mod.rs
new file mode 100644
index 0000000000..7edfa869e4
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/mod.rs
@@ -0,0 +1,265 @@
+//! Lane C — a gated, bounded pre-turn recall of facts about the user (#6040).
+//!
+//! The chat turn assembles a small per-turn context that rides on the user
+//! message, never on the cached system-prompt prefix. Lane B, situational
+//! preferences, has always been there. This lane sits beside it and answers the
+//! one question the model could not answer on its own: *does memory hold
+//! something about the user that this message is asking for?* Without it,
+//! "who is my idol and why?" was answered from prompt history alone, and the
+//! model — never told to look — replied "not stored" while the fact sat in the
+//! memory tree.
+//!
+//! # Why this is not the lane that was removed
+//!
+//! `core_turn.rs` documents the old `memory_loader.load_context()` block: two
+//! full scans of the `global` namespace on every turn, for at most nine lines,
+//! most of them empty once ordinary chat crowded the ranking. This lane is a
+//! different cost class on every axis that mattered there:
+//!
+//! - **It runs on a minority of turns.** [`gate_decision`] opens only for a
+//! message that asks about the user — first-person ownership plus a question
+//! or request shape. Small talk, code, weather and pastes never reach the
+//! store.
+//! - **It walks the tree, not the pile.** [`GuardSource`] calls the bound
+//! driver's `fast_retrieve` through the guard: summary-first, and on an
+//! entity-less query the engine's dense path, with a limit of
+//! [`AUTO_RECALL_LIMIT`]. The work is bounded by the answer, not by
+//! everything the user ever said.
+//! - **It is floored, capped and budgeted.** Hits below
+//! [`AUTO_RECALL_RELATIVE_FLOOR`] of the best score are dropped (retrieval
+//! scores are declared non-comparable across drivers, so the floor is
+//! relative, not absolute); at most [`AUTO_RECALL_LIMIT`] survive, each
+//! clipped to [`AUTO_RECALL_PER_HIT_CHARS`]; the whole block is clipped to
+//! the guard's `recall_max_chars`; and the lookup is abandoned after
+//! [`AUTO_RECALL_BUDGET`], so a memory module still downloading on a cold
+//! launch cannot stall the turn.
+//!
+//! # Switch
+//!
+//! `[subsystems.memory.hooks] auto_recall` (env
+//! `OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL`) is the kill-switch. The flag existed
+//! before this lane — declared, parsed, and read by nothing — so turning the
+//! lane off is a config edit on any install, with no new key to learn.
+//!
+//! # Failure mode
+//!
+//! Every failure is an ordinary turn without a block: a driver without the
+//! retrieval family, a retrieval error, a budget timeout. None of them is an
+//! error to the user, and each leaves an `[auto_recall]` line behind so the
+//! thresholds can be tuned from real logs.
+
+mod gate;
+mod source;
+pub mod warm;
+
+pub use gate::{gate_decision, GateDecision};
+pub use source::{AutoRecallSource, GuardSource};
+
+use crate::openhuman::memory::api::provider::retrieval::{FastRetrieveQuery, RetrievalHit};
+use crate::openhuman::memory::guard::MemoryGuard;
+use std::cmp::Ordering;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// Most hits a block may carry. Three is enough to answer a question about the
+/// user and small enough that a wrong guess costs a few lines, not a screen.
+pub const AUTO_RECALL_LIMIT: usize = 3;
+
+/// Characters kept per hit. A tree leaf is a chunk, not a sentence; the model
+/// needs the fact, not the whole page it came from.
+pub const AUTO_RECALL_PER_HIT_CHARS: usize = 400;
+
+/// How long the turn waits for the lookup before proceeding without it.
+///
+/// Wider than Lane B's 3 s on purpose. A warm `fast_retrieve` through the
+/// module measured 2–3 s on a loaded 16 GB desktop (field test, 2026-09-05),
+/// and at 3 s one of three real questions lost its block to the timeout — the
+/// turn then answers "not stored" for a fact that is stored, which is the bug
+/// this lane exists to fix. The lane only runs on gated turns, and the two
+/// lanes run side by side, so the worst case a turn pays is this bound alone.
+pub const AUTO_RECALL_BUDGET: Duration = Duration::from_secs(5);
+
+/// A hit is kept only while its score is at least this fraction of the best
+/// hit's. Scores are "higher is better" and nothing more across drivers, so an
+/// absolute threshold would be a guess; a relative one drops the long tail of
+/// weak matches without pretending to know the scale.
+pub const AUTO_RECALL_RELATIVE_FLOOR: f32 = 0.5;
+
+/// The banner that heads the injected block. Tests and the prompt snapshot
+/// look for it; the model reads it as the section title.
+pub const AUTO_RECALL_BANNER: &str = "## Relevant memory for this message";
+
+/// The lane itself: a retrieval source, the switch, and the budgets.
+pub struct AutoRecall {
+ source: Arc<dyn AutoRecallSource>,
+ enabled: bool,
+ recall_max_chars: Option<usize>,
+ budget: Duration,
+}
+
+impl AutoRecall {
+ /// A lane over `source`. `enabled = false` makes [`Self::block_for`]
+ /// answer `None` without touching the source; `recall_max_chars` clips the
+ /// rendered block (the guard's `recall_max_chars` budget).
+ pub fn new(
+ source: Arc<dyn AutoRecallSource>,
+ enabled: bool,
+ recall_max_chars: Option<usize>,
+ ) -> Self {
+ Self {
+ source,
+ enabled,
+ recall_max_chars,
+ budget: AUTO_RECALL_BUDGET,
+ }
+ }
+
+ /// The production lane: reads through `guard`, switched by the guard
+ /// policy's `hooks.auto_recall`, clipped by its `recall_max_chars`.
+ pub fn from_guard(guard: Arc<MemoryGuard>) -> Self {
+ let (enabled, recall_max_chars) = {
+ let policy = guard.policy();
+ (policy.hooks().auto_recall, policy.recall_budget())
+ };
+ log::debug!(
+ "[auto_recall] lane bound driver={} enabled={enabled} recall_max_chars={recall_max_chars:?}",
+ guard.policy().driver_id()
+ );
+ Self::new(Arc::new(GuardSource::new(guard)), enabled, recall_max_chars)
+ }
+
+ /// Overrides the lookup budget. Tests use it to make the timeout path
+ /// reachable without sleeping for seconds.
+ #[must_use]
+ pub fn with_budget(mut self, budget: Duration) -> Self {
+ self.budget = budget;
+ self
+ }
+
+ /// Whether the lane will run at all.
+ pub fn enabled(&self) -> bool {
+ self.enabled
+ }
+
+ /// The block to prepend to `user_message`, or `None` when the lane is off,
+ /// the gate is closed, nothing relevant came back, or the lookup failed or
+ /// timed out. Never an error: a turn without a block is an ordinary turn.
+ pub async fn block_for(&self, user_message: &str) -> Option<String> {
+ if !self.enabled {
+ log::debug!("[auto_recall] disabled by hooks.auto_recall; skipping");
+ return None;
+ }
+ let decision = gate_decision(user_message);
+ let GateDecision::Open(reason) = decision else {
+ log::debug!(
+ "[auto_recall] gate=closed reason={} chars={}",
+ decision.reason(),
+ user_message.chars().count()
+ );
+ return None;
+ };
+
+ let started = Instant::now();
+ let query = FastRetrieveQuery {
+ limit: AUTO_RECALL_LIMIT,
+ ..FastRetrieveQuery::default()
+ };
+ let response =
+ match tokio::time::timeout(self.budget, self.source.fast_retrieve(user_message, query))
+ .await
+ {
+ Ok(Ok(response)) => response,
+ Ok(Err(err)) => {
+ log::warn!(
+ "[auto_recall] gate=open reason={reason} retrieval failed after {}ms; \
+ continuing without a memory block: {err}",
+ started.elapsed().as_millis()
+ );
+ return None;
+ }
+ Err(_elapsed) => {
+ log::warn!(
+ "[auto_recall] gate=open reason={reason} retrieval exceeded {:?}; \
+ continuing without a memory block",
+ self.budget
+ );
+ return None;
+ }
+ };
+
+ let total = response.total;
+ let hits = select_hits(response.hits);
+ if hits.is_empty() {
+ log::info!(
+ "[auto_recall] gate=open reason={reason} hits=0 total={total} elapsed_ms={}",
+ started.elapsed().as_millis()
+ );
+ return None;
+ }
+ let block = render_block(&hits, self.recall_max_chars);
+ log::info!(
+ "[auto_recall] gate=open reason={reason} hits={} total={total} elapsed_ms={} chars={}",
+ hits.len(),
+ started.elapsed().as_millis(),
+ block.chars().count()
+ );
+ Some(block)
+ }
+}
+
+/// Ranks `hits` best-first, drops empty content and the weak tail below the
+/// relative floor, and keeps at most [`AUTO_RECALL_LIMIT`].
+pub(crate) fn select_hits(mut hits: Vec<RetrievalHit>) -> Vec<RetrievalHit> {
+ hits.retain(|hit| !hit.content.trim().is_empty());
+ // Best first; a NaN score sorts last rather than poisoning the order.
+ hits.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(Ordering::Equal));
+ if let Some(top) = hits.first().map(|hit| hit.score) {
+ if top > 0.0 {
+ let floor = top * AUTO_RECALL_RELATIVE_FLOOR;
+ hits.retain(|hit| hit.score >= floor);
+ }
+ }
+ hits.truncate(AUTO_RECALL_LIMIT);
+ hits
+}
+
+/// The block the turn prepends: the banner, one line per hit, clipped to
+/// `recall_max_chars` when the guard sets one.
+pub(crate) fn render_block(hits: &[RetrievalHit], recall_max_chars: Option<usize>) -> String {
+ let mut block = String::from(AUTO_RECALL_BANNER);
+ block.push_str("\n\n");
+ for hit in hits {
+ block.push_str("- ");
+ block.push_str(&one_line(&hit.content, AUTO_RECALL_PER_HIT_CHARS));
+ let scope = hit.tree_scope.trim();
+ if !scope.is_empty() {
+ block.push_str(" (from ");
+ block.push_str(scope);
+ block.push(')');
+ }
+ block.push('\n');
+ }
+ block.push('\n');
+ if let Some(max_chars) = recall_max_chars {
+ if block.chars().count() > max_chars {
+ block = block.chars().take(max_chars).collect();
+ block.push_str("…\n\n");
+ }
+ }
+ block
+}
+
+/// `text` with its whitespace collapsed onto one line and clipped to
+/// `max_chars`, so a multi-paragraph chunk stays one bullet.
+fn one_line(text: &str, max_chars: usize) -> String {
+ let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ let mut out: String = collapsed.chars().take(max_chars).collect();
+ if collapsed.chars().count() > max_chars {
+ out.push('…');
+ }
+ out
+}
+
+#[cfg(test)]
+#[path = "auto_recall_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/auto_recall/source.rs b/src/openhuman/memory/auto_recall/source.rs
new file mode 100644
index 0000000000..451eb33783
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/source.rs
@@ -0,0 +1,65 @@
+//! Where Lane C reads from.
+//!
+//! The lane is written against a one-method trait rather than the guard
+//! directly so the turn tests can script hits without a memory driver, and so
+//! the lane's own tests can exercise the timeout and error paths on demand.
+//! Production binds [`GuardSource`], which goes through the bound driver's
+//! guard: scope narrowing, taint stamping and the recall budget all apply
+//! exactly as they do for the memory tools.
+
+use crate::openhuman::memory::api::error::MemoryError;
+use crate::openhuman::memory::api::provider::retrieval::{FastRetrieveQuery, RetrievalResponse};
+use crate::openhuman::memory::api::provider::MemoryProvider as _;
+use crate::openhuman::memory::guard::MemoryGuard;
+use crate::openhuman::memory::source_scope::as_bus_scope;
+use async_trait::async_trait;
+use std::sync::Arc;
+
+/// A retrieval the lane can run.
+#[async_trait]
+pub trait AutoRecallSource: Send + Sync {
+ /// The driver's `fast_retrieve` for `query`, bounded by `options`.
+ async fn fast_retrieve(
+ &self,
+ query: &str,
+ options: FastRetrieveQuery,
+ ) -> Result<RetrievalResponse, MemoryError>;
+}
+
+/// The production source: the session's bound driver, behind its guard.
+pub struct GuardSource {
+ guard: Arc<MemoryGuard>,
+}
+
+impl GuardSource {
+ /// A source over `guard`.
+ pub fn new(guard: Arc<MemoryGuard>) -> Self {
+ Self { guard }
+ }
+}
+
+#[async_trait]
+impl AutoRecallSource for GuardSource {
+ async fn fast_retrieve(
+ &self,
+ query: &str,
+ options: FastRetrieveQuery,
+ ) -> Result<RetrievalResponse, MemoryError> {
+ // A driver without the retrieval family has no tree to rank. That is a
+ // degradation, not an error: the lane yields nothing, the same footing
+ // Lane B's `recall_by_vector` takes for a driver without vectors.
+ let Some(retrieval) = self.guard.as_retrieval() else {
+ log::debug!(
+ "[auto_recall] bound driver exposes no retrieval family; nothing to recall"
+ );
+ return Ok(RetrievalResponse::default());
+ };
+ // The per-turn source allowlist is host policy and a task-local; it
+ // does not cross the bus, so it is passed explicitly. The guard
+ // narrows it further and never widens it.
+ let scope = as_bus_scope();
+ retrieval
+ .fast_retrieve(query, options, scope.as_ref())
+ .await
+ }
+}
diff --git a/src/openhuman/memory/auto_recall/warm.rs b/src/openhuman/memory/auto_recall/warm.rs
new file mode 100644
index 0000000000..de016a968f
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/warm.rs
@@ -0,0 +1,103 @@
+//! Paying the first lookup's cold start before anyone is waiting on it.
+//!
+//! The first `fast_retrieve` after boot is not like the ones that follow. The
+//! module asks the host for spaCy entities, and the host's Python server may
+//! still have to start and load its model; the query embedding opens the
+//! embedder's first connection; the tree store is read cold. Measured on the
+//! desktop (2026-09-05): the first question after launch took more than 5 s
+//! and lost its block to the budget, the second took ~3 s. The user's first
+//! question after launch is exactly the one that should not be answered "not
+//! stored".
+//!
+//! So the host runs one throwaway retrieval as soon as the memory module is
+//! loaded, off every request path, with a generous bound of its own. Whatever
+//! it warms — the Python server, the embedder connection, the store's page
+//! cache — is warm for the first real turn. Nothing depends on its result:
+//! a signed-out embedder, a driver without retrieval, or a timeout each end
+//! in one log line.
+
+use super::source::{AutoRecallSource, GuardSource};
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::retrieval::FastRetrieveQuery;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// How long the warm-up may take before it is abandoned. Wide, because this
+/// is the call that absorbs the Python server start and the model load.
+pub const WARM_UP_BUDGET: Duration = Duration::from_secs(60);
+
+/// A query that opens every path a real lookup uses — entity extraction, a
+/// query embedding, a tree walk — without matching anything in particular.
+const WARM_UP_QUERY: &str = "warm up the memory retrieval path";
+
+/// What a warm-up run found out, for the log and for tests.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WarmUpOutcome {
+ /// The retrieval answered (with however many hits) inside the budget.
+ Warmed { elapsed_ms: u128 },
+ /// The retrieval failed; the failure is logged and nothing is retried.
+ Failed { elapsed_ms: u128 },
+ /// The budget expired first.
+ TimedOut,
+}
+
+/// Run one warm-up retrieval against `source`, bounded by `budget`.
+pub async fn warm_up(source: &dyn AutoRecallSource, budget: Duration) -> WarmUpOutcome {
+ let started = Instant::now();
+ let query = FastRetrieveQuery {
+ limit: 1,
+ ..FastRetrieveQuery::default()
+ };
+ match tokio::time::timeout(budget, source.fast_retrieve(WARM_UP_QUERY, query)).await {
+ Ok(Ok(response)) => {
+ let elapsed_ms = started.elapsed().as_millis();
+ log::info!(
+ "[auto_recall] warm-up done elapsed_ms={elapsed_ms} hits={} total={}",
+ response.hits.len(),
+ response.total
+ );
+ WarmUpOutcome::Warmed { elapsed_ms }
+ }
+ Ok(Err(err)) => {
+ let elapsed_ms = started.elapsed().as_millis();
+ // Expected while signed out (the embedder has no session) and on a
+ // driver without retrieval; the first real turn reports the same
+ // condition on its own line, so this stays at debug.
+ log::debug!("[auto_recall] warm-up failed after {elapsed_ms}ms: {err}");
+ WarmUpOutcome::Failed { elapsed_ms }
+ }
+ Err(_elapsed) => {
+ log::warn!(
+ "[auto_recall] warm-up exceeded {budget:?}; the first lookup will pay the cold start"
+ );
+ WarmUpOutcome::TimedOut
+ }
+ }
+}
+
+/// Spawn the boot warm-up for the memory driver `config` binds.
+///
+/// Returns without doing anything when the lane is switched off — a host that
+/// disabled `auto_recall` asked for no pre-turn retrieval work at all — or when
+/// the driver cannot be bound. Never blocks the caller.
+pub fn spawn_at_boot(config: Arc<Config>) {
+ if !config.subsystems.memory.hooks.auto_recall {
+ log::debug!("[auto_recall] warm-up skipped: hooks.auto_recall is off");
+ return;
+ }
+ tokio::spawn(async move {
+ let binding = match crate::openhuman::memory::binding::for_config(&config) {
+ Ok(binding) => binding,
+ Err(reason) => {
+ log::debug!("[auto_recall] warm-up skipped: memory binding unavailable: {reason}");
+ return;
+ }
+ };
+ let source = GuardSource::new(binding.guard());
+ warm_up(&source, WARM_UP_BUDGET).await;
+ });
+}
+
+#[cfg(test)]
+#[path = "warm_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/auto_recall/warm_tests.rs b/src/openhuman/memory/auto_recall/warm_tests.rs
new file mode 100644
index 0000000000..bd0bae280b
--- /dev/null
+++ b/src/openhuman/memory/auto_recall/warm_tests.rs
@@ -0,0 +1,95 @@
+use super::*;
+use crate::openhuman::memory::api::error::MemoryError;
+use crate::openhuman::memory::api::provider::retrieval::RetrievalResponse;
+use async_trait::async_trait;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct Scripted {
+ outcome: Result<(), String>,
+ delay: Duration,
+ calls: AtomicUsize,
+}
+
+impl Scripted {
+ fn ok() -> Self {
+ Self {
+ outcome: Ok(()),
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ }
+ }
+
+ fn failing() -> Self {
+ Self {
+ outcome: Err("signed out".into()),
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ }
+ }
+
+ fn slow(delay: Duration) -> Self {
+ Self {
+ outcome: Ok(()),
+ delay,
+ calls: AtomicUsize::new(0),
+ }
+ }
+}
+
+#[async_trait]
+impl AutoRecallSource for Scripted {
+ async fn fast_retrieve(
+ &self,
+ query: &str,
+ options: FastRetrieveQuery,
+ ) -> Result<RetrievalResponse, MemoryError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ assert_eq!(query, WARM_UP_QUERY);
+ assert_eq!(options.limit, 1, "the warm-up asks for the smallest page");
+ if !self.delay.is_zero() {
+ tokio::time::sleep(self.delay).await;
+ }
+ match &self.outcome {
+ Ok(()) => Ok(RetrievalResponse::default()),
+ Err(message) => Err(MemoryError::Backend(message.clone())),
+ }
+ }
+}
+
+#[tokio::test]
+async fn warm_up_runs_one_bounded_retrieval() {
+ let source = Scripted::ok();
+ let outcome = warm_up(&source, Duration::from_secs(1)).await;
+ assert!(
+ matches!(outcome, WarmUpOutcome::Warmed { .. }),
+ "{outcome:?}"
+ );
+ assert_eq!(source.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn warm_up_reports_a_failure_without_retrying() {
+ let source = Scripted::failing();
+ let outcome = warm_up(&source, Duration::from_secs(1)).await;
+ assert!(
+ matches!(outcome, WarmUpOutcome::Failed { .. }),
+ "{outcome:?}"
+ );
+ assert_eq!(source.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn warm_up_gives_up_when_the_budget_expires() {
+ let source = Scripted::slow(Duration::from_millis(200));
+ let outcome = warm_up(&source, Duration::from_millis(20)).await;
+ assert_eq!(outcome, WarmUpOutcome::TimedOut);
+}
+
+#[tokio::test]
+async fn spawn_at_boot_is_a_no_op_when_the_lane_is_off() {
+ let mut config = Config::default();
+ config.subsystems.memory.hooks.auto_recall = false;
+ // Nothing to observe but "does not panic and does not block": the spawn
+ // never happens, so there is no task to wait for.
+ spawn_at_boot(Arc::new(config));
+}
diff --git a/src/openhuman/memory/guard/test_support_part_01.rs b/src/openhuman/memory/guard/test_support_part_01.rs
index ac165e9afc..eddcfe5cd5 100644
--- a/src/openhuman/memory/guard/test_support_part_01.rs
+++ b/src/openhuman/memory/guard/test_support_part_01.rs
@@ -77,6 +77,9 @@ pub struct RecordingProvider {
calls: Mutex<Vec<Call>>,
/// What `recall` returns, so budget tests can drive a known result set.
recall_result: Mutex<Vec<MemoryEntry>>,
+ /// What `fast_retrieve` returns, so the auto-recall lane can be driven
+ /// through a real guard with known hits.
+ fast_retrieve_result: Mutex<RetrievalResponse>,
}
impl Default for RecordingProvider {
@@ -90,6 +93,7 @@ impl RecordingProvider {
Self {
calls: Mutex::new(Vec::new()),
recall_result: Mutex::new(Vec::new()),
+ fast_retrieve_result: Mutex::new(RetrievalResponse::default()),
}
}
@@ -98,6 +102,11 @@ impl RecordingProvider {
self
}
+ pub fn with_fast_retrieve_result(self, response: RetrievalResponse) -> Self {
+ *self.fast_retrieve_result.lock().unwrap() = response;
+ self
+ }
+
fn record(&self, call: Call) {
self.calls.lock().unwrap().push(call);
}
diff --git a/src/openhuman/memory/guard/test_support_part_02.rs b/src/openhuman/memory/guard/test_support_part_02.rs
index 6fd9432244..88be08536d 100644
--- a/src/openhuman/memory/guard/test_support_part_02.rs
+++ b/src/openhuman/memory/guard/test_support_part_02.rs
@@ -468,7 +468,7 @@ impl MemoryRetrieval for RecordingProvider {
taint: None,
scoped: Some(scope.is_some()),
});
- Ok(RetrievalResponse::default())
+ Ok(self.fast_retrieve_result.lock().unwrap().clone())
}
async fn cover_window(
diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rs
index 94175f91ef..0fe61b0cb3 100644
--- a/src/openhuman/memory/mod.rs
+++ b/src/openhuman/memory/mod.rs
@@ -34,6 +34,10 @@
pub mod agent;
pub mod api;
+/// Lane C — the gated, bounded pre-turn recall of facts about the user
+/// (#6040). Host policy end to end: what counts as a question about the user,
+/// how much a block may carry, and the switch are product decisions.
+pub mod auto_recall;
pub mod binding;
pub mod driver;
pub mod exit;
diff --git a/src/openhuman/memory/tools/recall.rs b/src/openhuman/memory/tools/recall.rs
index 58f0e31e3b..9945ac8cbd 100644
--- a/src/openhuman/memory/tools/recall.rs
+++ b/src/openhuman/memory/tools/recall.rs
@@ -1,3 +1,4 @@
+use crate::openhuman::agent::tinyagents::host::agent_memory::DEFAULT_AGENT_MEMORY_NAMESPACE;
use crate::openhuman::memory::api::provider::MemoryRecall;
use crate::openhuman::memory::ops::guard::active_memory_guard;
use crate::openhuman::tools::traits::{Tool, ToolResult};
@@ -32,7 +33,8 @@ impl Tool for MemoryRecallTool {
}
fn description(&self) -> &str {
- "Search memory for relevant facts in a namespace. Returns scored results ranked by relevance."
+ "Search memory for relevant facts: stored notes and ingested sources alike. Returns scored \
+ results ranked by relevance. Searches the default scope unless a namespace is given."
}
fn parameters_schema(&self) -> serde_json::Value {
@@ -45,26 +47,19 @@ impl Tool for MemoryRecallTool {
},
"namespace": {
"type": "string",
- "description": "Namespace to search (e.g. 'global', 'background', 'autocomplete', or 'skill-{id}')"
+ "description": "Namespace to search. Omit for the default scope ('global'); others include 'background', 'autocomplete', 'skill-{id}', or a connector source namespace"
},
"limit": {
"type": "integer",
"description": "Max results to return (default: 5)"
}
},
- "required": ["namespace", "query"]
+ "required": ["query"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let namespace = args
- .get("namespace")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing 'namespace' parameter"))?
- .trim();
- if namespace.is_empty() {
- return Err(anyhow::anyhow!("namespace cannot be empty"));
- }
+ let namespace = resolve_namespace(&args)?;
let query = args
.get("query")
.and_then(|v| v.as_str())
@@ -116,6 +111,21 @@ impl Tool for MemoryRecallTool {
}
}
+/// The namespace a call searches: the one it names, or the default scope when
+/// it names none. An explicit empty string is a caller mistake, not a request
+/// for the default — the model had a namespace in mind and lost it.
+pub(crate) fn resolve_namespace(args: &serde_json::Value) -> anyhow::Result<&str> {
+ match args
+ .get("namespace")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ {
+ None => Ok(DEFAULT_AGENT_MEMORY_NAMESPACE),
+ Some("") => Err(anyhow::anyhow!("namespace cannot be empty")),
+ Some(namespace) => Ok(namespace),
+ }
+}
+
#[cfg(test)]
#[path = "recall_tests.rs"]
mod tests;
diff --git a/src/openhuman/memory/tools/recall_tests.rs b/src/openhuman/memory/tools/recall_tests.rs
index e0ef02abf0..0e59e51aab 100644
--- a/src/openhuman/memory/tools/recall_tests.rs
+++ b/src/openhuman/memory/tools/recall_tests.rs
@@ -104,3 +104,31 @@ fn name_and_schema() {
assert_eq!(tool.name(), "memory_recall");
assert!(tool.parameters_schema()["properties"]["query"].is_object());
}
+
+/// Only the query is required: a caller that names no namespace searches the
+/// default scope instead of being sent back to guess one (#6040).
+#[test]
+fn schema_requires_only_the_query() {
+ let schema = MemoryRecallTool::new().parameters_schema();
+ assert_eq!(schema["required"], json!(["query"]));
+ assert!(schema["properties"]["namespace"].is_object());
+}
+
+#[test]
+fn resolve_namespace_defaults_when_absent() {
+ let args = json!({"query": "idol"});
+ let namespace = resolve_namespace(&args).unwrap();
+ assert_eq!(namespace, DEFAULT_AGENT_MEMORY_NAMESPACE);
+}
+
+#[test]
+fn resolve_namespace_keeps_an_explicit_one_trimmed() {
+ let args = json!({"namespace": " skill-gmail ", "query": "x"});
+ let namespace = resolve_namespace(&args).unwrap();
+ assert_eq!(namespace, "skill-gmail");
+}
+
+#[test]
+fn resolve_namespace_rejects_an_explicit_empty_one() {
+ assert!(resolve_namespace(&json!({"namespace": " ", "query": "x"})).is_err());
+}
diff --git a/src/openhuman/modules/boot.rs b/src/openhuman/modules/boot.rs
index b8016a7ce3..f2bcb5bf8c 100644
--- a/src/openhuman/modules/boot.rs
+++ b/src/openhuman/modules/boot.rs
@@ -87,6 +87,16 @@ pub async fn load_declared_modules(config: &Config) {
"[modules] eager module '{}' did not load: {reason}",
record.id
);
+ continue;
+ }
+ // The first retrieval after boot pays the Python server start, the
+ // model load and the embedder's first connection — several seconds the
+ // user's first question would otherwise wait on, or lose its memory
+ // block to. Pay it now, off the request path (#6040).
+ if record.id == super::memory::MODULE_ID {
+ crate::openhuman::memory::auto_recall::warm::spawn_at_boot(std::sync::Arc::new(
+ config.clone(),
+ ));
}
}
}
diff --git a/src/openhuman/modules/memory_host.rs b/src/openhuman/modules/memory_host.rs
index 7470fa3b0c..2ad8831974 100644
--- a/src/openhuman/modules/memory_host.rs
+++ b/src/openhuman/modules/memory_host.rs
@@ -75,7 +75,18 @@ impl EmbeddingCallbacks {
)
.map_err(method_error)?;
let borrowed: Vec<&str> = texts.iter().map(String::as_str).collect();
- embedder.embed(&borrowed).await.map_err(method_error)
+ // Timed because this is one of the two host round trips behind every
+ // per-turn memory lookup (the other is `extract_spacy` below); the
+ // `[auto_recall]` line reports the total, these report the split.
+ let started = std::time::Instant::now();
+ let result = embedder.embed(&borrowed).await.map_err(method_error);
+ log::debug!(
+ "[memory_host] embed provider={provider} texts={} elapsed_ms={} ok={}",
+ borrowed.len(),
+ started.elapsed().as_millis(),
+ result.is_ok()
+ );
+ result
}
}
@@ -427,9 +438,22 @@ impl RuntimeCallbacks {
}
async fn extract_spacy(&self, text: String) -> tinybus::Result<SpacyResponse> {
+ // The module asks for this on every query it retrieves for, so its
+ // latency lands directly on the chat turn. Timed for the same reason
+ // `embed` above is; the first call after boot also carries the Python
+ // server start and the model load, which is what the boot warm-up in
+ // `memory::auto_recall::warm` exists to pay early.
+ let started = std::time::Instant::now();
let response = crate::openhuman::runtime::python_server::extract_spacy(&self.0, &text)
.await
- .map_err(method_error)?;
+ .map_err(method_error);
+ log::debug!(
+ "[memory_host] extract_spacy chars={} elapsed_ms={} ok={}",
+ text.chars().count(),
+ started.elapsed().as_millis(),
+ response.is_ok()
+ );
+ let response = response?;
serde_json::from_value(serde_json::to_value(response).map_err(method_error)?)
.map_err(method_error)
}