Skip to content

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

Merge upstream/main into fix/6040-auto-recall-lane-c\n\nResolves the overlap with #6046 (Lane B through DriverMemory), which landed\nfirst and touched the same turn path and test fixtures:\n\n- core_turn.rs keeps the recall_lanes call; the 5 s Lane B budget that #6046\n set in core_turn.rs now lives in turn/recall_lanes.rs with its rationale.\n- turn_tests_part_04_tests.rs stays as main has it (scripted_reply is shared\n as pub(super)); the Lane C turn tests move to turn_tests_part_05_tests.rs,\n because both blocks together would cross the 750-line layout gate.\n- RecordingProvider carries both the fast_retrieve result and the namespace\n hits/summaries; the coverage matrix and .claude/memory.md keep both entries.\n

Shanuee5b77403ff8
diff --cc .claude/memory.md
index d8995ffa44,3fc20a2c08..abe4031f60
--- a/.claude/memory.md
+++ b/.claude/memory.md
@@@ -11,7 -13,7 +13,8 @@@ Quick reference for anyone starting wit
- **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.
+ - **A `Memory` trait method left on its default is a silent no-op in production (issue #6041)** — the session's `Arc<dyn Memory>` is `agent/experience/ops.rs::DriverMemory` (since `7a4278378`), and `tinymemory-api`'s `Memory::recall_relevant_by_vector` defaults to `Ok(vec![])`, so situational preferences (Lane B) injected nothing on every module-backed install while every turn test stayed green — the harness tests bind the embedded `tinymemory_core::store::create_memory`, which overrides it. `DriverMemory` now answers through `preferences::recall_by_vector_over` (one body with the guard path). Rule: a turn-level test that pins production behaviour must bind `DriverMemory` over `guard::test_support::RecordingProvider` (`with_namespace_hits`, `with_list_result`), not the embedded store; and before leaving a trait default in place, grep who actually holds the handle. Costs measured on the desktop once the lane was live: the vector recall is one query-embed round trip, 0.8–3 s per turn, so `recall_situational_preferences_on` lists the namespace first (no embed) and skips the recall when nothing is stored; Lane B's budget is 5 s (3 s lost the block on both on-topic turns). Floor tuning data: `[pref_recall] namespace= kept= top_similarity= floor= elapsed_ms=` — with the managed embedder, unrelated message↔preference pairs score 0.28–0.33, a rule-phrased travel preference vs a trip-planning message 0.349, a coffee preference vs a café question 0.575; the 0.35 floor is thin but lowering it pulls cross-topic preferences in.
## Strict Rules
diff --cc docs/TEST-COVERAGE-MATRIX.md
index fc3dfc8857,ed70f46315..bf60ddda3c
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@@ -342,17 -343,14 +343,17 @@@ End-to-end coverage of the agent harnes
### 8.4 Explicit User Preferences (Two-Lane)
- | ID | Feature | Layer | Test path(s) | Status | Notes |
- | ----- | ------------------------------------------ | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
- | 8.4.1 | Save Preference (general / situational) | RU | `src/openhuman/agent/tools/save_preference_tests.rs` | ✅ | `save_preference` tool → `user_pref_{general,situational}`, topic-keyed |
- | 8.4.2 | Lane A — Standing Prefs in System Prompt | RU | `src/openhuman/agent/learning/prompt_sections.rs`, `src/openhuman/agent/harness/session/turn_tests.rs` | ✅ | General prefs rendered into the system prompt at thread start |
- | 8.4.3 | Lane B — Situational Recall (vector-gated) | RU | `src/openhuman/memory/store/namespace_store/query_tests.rs::recall_relevant_by_vector_gates_on_similarity` | ✅ | Per-turn; relevant query injects, unrelated suppresses |
- | 8.4.4 | Same-Topic Contradiction (replace) | RU | `src/openhuman/agent/tools/save_preference_tests.rs::recategorising_moves_pref_between_namespaces` | ✅ | `ON CONFLICT REPLACE`; a topic lives in exactly one scope |
- | 8.4.5 | Cross-Topic Contradiction Surfacing | RU | `src/openhuman/agent/tools/save_preference_tests.rs::save_surfaces_related_preference_for_contradiction_check` | ✅ | Related prefs surfaced in the tool result for the chat agent to resolve |
- | 8.4.6 | vector_chunks Model-Signature Recall Guard | RU | `src/openhuman/memory/store/namespace_store/query_tests.rs::vector_recall_excludes_other_model_signature` | ✅ | Excludes cross-model vectors; dim-guards legacy rows |
- | 8.4.7 | Lane C — Auto-recall of User Facts (gated) | RU | `src/openhuman/memory/auto_recall/{gate_tests,auto_recall_tests}.rs`, `src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs::auto_recall_*` | ✅ | #6040: lexical gate, bounded `fast_retrieve` via the guard, block rides the user message; `hooks.auto_recall` switch |
+ | ID | Feature | Layer | Test path(s) | Status | Notes |
+ | ----- | ------------------------------------------ | ----- | -------------------------------------------------------------------------------------------------------------- | ------ | ----------------------------------------------------------------------- |
+ | 8.4.1 | Save Preference (general / situational) | RU | `src/openhuman/agent/tools/save_preference_tests.rs` | ✅ | `save_preference` tool → `user_pref_{general,situational}`, topic-keyed |
+ | 8.4.2 | Lane A — Standing Prefs in System Prompt | RU | `src/openhuman/agent/learning/prompt_sections.rs`, `src/openhuman/agent/harness/session/turn_tests.rs` | ✅ | General prefs rendered into the system prompt at thread start |
+ | 8.4.3 | Lane B — Situational Recall (vector-gated) | RU | `src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs::situational_preference_reaches_the_model_through_driver_memory`, `src/openhuman/agent/experience/ops_tests.rs::recall_relevant_by_vector_*`, `src/openhuman/memory/preferences/preferences_tests.rs` | ✅ | Per-turn through the production `DriverMemory` handle (#6041); relevant query injects, below-floor suppresses |
+ | 8.4.4 | Same-Topic Contradiction (replace) | RU | `src/openhuman/agent/tools/save_preference_tests.rs::recategorising_moves_pref_between_namespaces` | ✅ | `ON CONFLICT REPLACE`; a topic lives in exactly one scope |
+ | 8.4.5 | Cross-Topic Contradiction Surfacing | RU | `src/openhuman/agent/tools/save_preference_tests.rs::save_surfaces_related_preference_for_contradiction_check` | ✅ | Related prefs surfaced in the tool result for the chat agent to resolve |
+ | 8.4.6 | vector_chunks Model-Signature Recall Guard | RU | `src/openhuman/memory/store/namespace_store/query_tests.rs::vector_recall_excludes_other_model_signature` | ✅ | Excludes cross-model vectors; dim-guards legacy rows |
++| 8.4.7 | Lane C — Auto-recall of User Facts (gated) | RU | `src/openhuman/memory/auto_recall/{gate_tests,auto_recall_tests}.rs`, `src/openhuman/agent/harness/session/turn_tests_part_05_tests.rs::auto_recall_*` | ✅ | #6040: lexical gate, bounded `fast_retrieve` via the guard, block rides the user message; `hooks.auto_recall` switch |
+| 8.4.8 | Lane C Boot Warm-up | RU | `src/openhuman/memory/auto_recall/warm_tests.rs` | ✅ | One bounded retrieval after the memory module loads; failure/timeout are log-only |
+| 8.4.9 | Memory-Access Instruction (ungated) | RU | `src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs::memory_access_instruction_is_present_with_learning_disabled`, `src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs` | ✅ | Added whenever a retrieval tool is visible, independent of `learning.enabled`; forbids claiming absence unsearched |
### 8.5 Long-term Goals
diff --cc src/openhuman/agent/harness/session/turn/recall_lanes.rs
index 686c0068c1,0000000000..afa84c9a13
mode 100644,000000..100644
--- a/src/openhuman/agent/harness/session/turn/recall_lanes.rs
+++ b/src/openhuman/agent/harness/session/turn/recall_lanes.rs
@@@ -1,94 -1,0 +1,98 @@@
+//! 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);
++ // 5 s, not 3: the module's lookup (a query embed round trip, queued behind
++ // the citation and autosave calls spawned off the turn) measured over 3 s
++ // on a live desktop and lost the block on both on-topic turns of the
++ // #6041 field test.
++ const SITUATIONAL_RECALL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
+ 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 --cc src/openhuman/agent/harness/session/turn_tests.rs
index 531f308f70,531f308f70..3983078a9e
--- a/src/openhuman/agent/harness/session/turn_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests.rs
@@@ -540,3 -540,3 +540,5 @@@ mod part_02_tests
mod part_03_tests;
#[path = "turn_tests_part_04_tests.rs"]
mod part_04_tests;
++#[path = "turn_tests_part_05_tests.rs"]
++mod part_05_tests;
diff --cc src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
index 1741bb253d,1a05b9ab62..e81384cc27
--- a/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
@@@ -463,84 -463,24 +463,24 @@@ fn skill_retraction_note_names_removed_
);
}
- // ── Lane C: auto-recall of facts about the user (#6040) ──────────────────────
+ // ── Lane B through the production memory handle (#6041) ─────────────────────
//
- // 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,
+ // Every other turn test binds the embedded store, whose `Memory` impl answers
+ // `recall_relevant_by_vector` itself. Production binds `DriverMemory`, which
+ // sat on the trait's empty default — so Lane B never injected anything on a
+ // module-backed install and no test noticed. These run the real `turn()` over
+ // `DriverMemory` on a scripted driver.
+
+ use crate::openhuman::agent::experience::ops::DriverMemory;
+ use crate::openhuman::memory::api::provider::MemoryProvider;
+ use crate::openhuman::memory::guard::test_support::{
+ namespace_hit, namespace_summary, RecordingProvider,
};
- 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,
- }
+ use crate::openhuman::memory::preferences::USER_PREF_SITUATIONAL_NAMESPACE;
- 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),
- })
- }
+ const PREFERENCES_BANNER: &str = "## Relevant preferences for this message";
- 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> {
++pub(super) fn scripted_reply(text: &str) -> Arc<SequenceProvider> {
Arc::new(SequenceProvider {
responses: AsyncMutex::new(vec![Ok(ChatResponse {
text: Some(text.into()),
diff --cc src/openhuman/agent/harness/session/turn_tests_part_05_tests.rs
index 0000000000,0000000000..a90dc10eb6
new file mode 100644
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn_tests_part_05_tests.rs
@@@ -1,0 -1,0 +1,215 @@@
++use super::part_04_tests::scripted_reply;
++use super::*;
++
++// ── 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,
++ })
++ }
++}
++
++/// 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 --cc src/openhuman/memory/guard/test_support_part_01.rs
index eddcfe5cd5,1f01038b67..870e065395
--- a/src/openhuman/memory/guard/test_support_part_01.rs
+++ b/src/openhuman/memory/guard/test_support_part_01.rs
@@@ -77,9 -77,12 +77,15 @@@ 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>,
+ /// What `recall_namespace_scored` returns, so the vector-floored recall
+ /// paths (Lane B, the contradiction check) can be driven with known scores.
+ namespace_hits: Mutex<Vec<NamespaceMemoryHit>>,
+ /// What `namespaces` returns, so a namespace can look populated (Lane B
+ /// asks for the count before it pays for an embed) without a real store.
+ namespace_summaries: Mutex<Vec<NamespaceSummary>>,
}
impl Default for RecordingProvider {
@@@ -93,7 -96,8 +99,9 @@@ impl RecordingProvider
Self {
calls: Mutex::new(Vec::new()),
recall_result: Mutex::new(Vec::new()),
+ fast_retrieve_result: Mutex::new(RetrievalResponse::default()),
+ namespace_hits: Mutex::new(Vec::new()),
+ namespace_summaries: Mutex::new(Vec::new()),
}
}
@@@ -102,11 -106,16 +110,21 @@@
self
}
+ pub fn with_fast_retrieve_result(self, response: RetrievalResponse) -> Self {
+ *self.fast_retrieve_result.lock().unwrap() = response;
+ self
+ }
+
+ pub fn with_namespace_hits(self, hits: Vec<NamespaceMemoryHit>) -> Self {
+ *self.namespace_hits.lock().unwrap() = hits;
+ self
+ }
+
+ pub fn with_namespace_summaries(self, summaries: Vec<NamespaceSummary>) -> Self {
+ *self.namespace_summaries.lock().unwrap() = summaries;
+ self
+ }
+
fn record(&self, call: Call) {
self.calls.lock().unwrap().push(call);
}