Skip to content

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

refactor(memory): extract in-memory providers to tinymemory-conformance crate

Steven Enamakeld83b56d97f25
diff --git a/Cargo.lock b/Cargo.lock
index b8c22e7c7b..09f47549e8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4070,6 +4070,7 @@ dependencies = [
"tinymemory-bus",
"tinymemory-conformance",
"tinymemory-conversations",
+ "tinymemory-guard",
"tinymemory-sources",
"tinyruntime-bus",
"tinyruntime-pyserver",
@@ -7026,6 +7027,18 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "tinymemory-guard"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "chrono",
+ "log",
+ "serde_json",
+ "tinymemory-api",
+ "tracing",
+]
+
[[package]]
name = "tinymemory-remote"
version = "0.1.0"
diff --git a/crates/openhuman-core/src/channels/context_tests.rs b/crates/openhuman-core/src/channels/context_tests.rs
index 0406abc360..c3835938df 100644
--- a/crates/openhuman-core/src/channels/context_tests.rs
+++ b/crates/openhuman-core/src/channels/context_tests.rs
@@ -48,7 +48,7 @@ fn runtime_context() -> ChannelRuntimeContext {
channels_by_name: Arc::new(HashMap::new()),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("default".into()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![Box::new(DummyTool) as Box<dyn Tool>]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("prompt"),
model: Arc::new("model".into()),
@@ -152,7 +152,7 @@ fn skip_and_overflow_detection_cover_edge_cases() {
#[tokio::test]
async fn build_memory_context_filters_entries_and_truncates_content() {
- let mem = crate::memory::guard::in_memory::FixedRecallProvider::guarded(vec![
+ let mem = crate::memory::guard::in_memory::guarded_fixed_recall(vec![
memory_entry("keep", "v", Some(0.9)),
memory_entry("drop_history", "ignored", Some(0.9)),
memory_entry("low", "too low", Some(0.1)),
@@ -177,7 +177,7 @@ async fn build_memory_context_honors_total_budget_and_entry_limit() {
let entries = (0..10)
.map(|idx| memory_entry(&format!("k{idx}"), &"x".repeat(700), Some(0.9)))
.collect();
- let mem = crate::memory::guard::in_memory::FixedRecallProvider::guarded(entries);
+ let mem = crate::memory::guard::in_memory::guarded_fixed_recall(entries);
let rendered = build_memory_context(&mem, "hello", 0.4).await;
assert!(rendered.chars().count() <= MEMORY_CONTEXT_MAX_CHARS + 32);
diff --git a/crates/openhuman-core/src/channels/routes_tests.rs b/crates/openhuman-core/src/channels/routes_tests.rs
index 82b4825f8d..64741851f4 100644
--- a/crates/openhuman-core/src/channels/routes_tests.rs
+++ b/crates/openhuman-core/src/channels/routes_tests.rs
@@ -121,7 +121,7 @@ fn runtime_context(workspace_dir: PathBuf) -> ChannelRuntimeContext {
channels_by_name: Arc::new(HashMap::new()),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("openai".into()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![Box::new(DummyTool) as Box<dyn Tool>]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("prompt"),
model: Arc::new("reasoning-v1".into()),
diff --git a/crates/openhuman-core/src/channels/tests/discord_integration.rs b/crates/openhuman-core/src/channels/tests/discord_integration.rs
index f0910e6156..357b0db180 100644
--- a/crates/openhuman-core/src/channels/tests/discord_integration.rs
+++ b/crates/openhuman-core/src/channels/tests/discord_integration.rs
@@ -109,7 +109,7 @@ fn make_discord_ctx(
channels_by_name: Arc::new(channels),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/memory.rs b/crates/openhuman-core/src/channels/tests/memory.rs
index 41a1a042c7..e310220790 100644
--- a/crates/openhuman-core/src/channels/tests/memory.rs
+++ b/crates/openhuman-core/src/channels/tests/memory.rs
@@ -87,7 +87,7 @@ async fn process_channel_message_restores_per_sender_history_on_follow_ups() {
provider_impl.clone(),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
index 87819fe2af..1b7c3eaa8a 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
@@ -122,7 +122,7 @@ async fn message_dispatch_processes_messages_in_parallel() {
}),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -197,7 +197,7 @@ async fn process_channel_message_cancels_scoped_typing_task() {
}),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -287,7 +287,7 @@ async fn dispatch_routes_through_agent_run_turn_bus_handler() {
Arc::new(super::common::DummyModel),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -373,7 +373,7 @@ async fn channel_processed_event_records_resolved_agent_route() {
Arc::new(super::common::DummyModel),
)),
default_provider: Arc::new("requested-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("requested-model".to_string()),
@@ -487,7 +487,7 @@ async fn process_channel_message_hardens_multimodal_files_against_smuggled_marke
Arc::new(super::common::DummyModel),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -572,7 +572,7 @@ async fn process_channel_message_hardens_against_relative_path_markers() {
Arc::new(super::common::DummyModel),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
index ded49250d2..17041c6738 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
@@ -29,7 +29,7 @@ async fn process_channel_message_executes_native_tool_calls() {
Arc::new(ToolCallingModel),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -102,7 +102,7 @@ async fn process_channel_message_handles_models_command_without_llm_call() {
Arc::clone(&default_provider),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("default-model".to_string()),
@@ -203,7 +203,7 @@ async fn process_channel_message_uses_route_override_provider_and_model() {
Arc::clone(&default_provider),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("default-model".to_string()),
@@ -256,7 +256,7 @@ async fn process_channel_message_respects_configured_max_tool_iterations_above_d
}),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
@@ -316,7 +316,7 @@ async fn process_channel_message_reports_configured_max_tool_iterations_limit()
}),
)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/telegram_integration.rs b/crates/openhuman-core/src/channels/tests/telegram_integration.rs
index a2f560a13d..59b74fcdbe 100644
--- a/crates/openhuman-core/src/channels/tests/telegram_integration.rs
+++ b/crates/openhuman-core/src/channels/tests/telegram_integration.rs
@@ -85,7 +85,7 @@ fn make_test_context(
channels_by_name: Arc::new(channels),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("test-provider".to_string()),
- memory: crate::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),
+ memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),
tools_registry: Arc::new(vec![]),
system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
model: Arc::new("test-model".to_string()),
diff --git a/crates/openhuman-core/src/memory/binding.rs b/crates/openhuman-core/src/memory/binding.rs
index 8174237991..12c8a10ac1 100644
--- a/crates/openhuman-core/src/memory/binding.rs
+++ b/crates/openhuman-core/src/memory/binding.rs
@@ -44,7 +44,7 @@ use crate::memory::api::capabilities::Capabilities;
use crate::memory::api::health::MemoryHealth;
use crate::memory::api::provider::MemoryProvider;
use crate::memory::api::CONTRACT_VERSION;
-use crate::memory::guard::{GuardPolicy, MemoryGuard};
+use crate::memory::guard::{HostGuardPolicy, MemoryGuard};
#[cfg(not(feature = "modules"))]
use tinymemory_api::null::NullMemoryProvider;
use tinymemory_api::null::NULL_DRIVER_ID;
@@ -417,7 +417,7 @@ pub(super) fn bind_provider(
let capabilities = provider.capabilities();
let guard = Arc::new(MemoryGuard::new(
Arc::clone(&provider),
- Arc::new(GuardPolicy::new(
+ Arc::new(HostGuardPolicy::new(
driver_id.clone(),
class,
crate::config::schema::MemoryHooksConfig::default(),
diff --git a/crates/openhuman-core/src/memory/guard/in_memory.rs b/crates/openhuman-core/src/memory/guard/in_memory.rs
index 9eedc2b49d..d373cf9814 100644
--- a/crates/openhuman-core/src/memory/guard/in_memory.rs
+++ b/crates/openhuman-core/src/memory/guard/in_memory.rs
@@ -1,230 +1,24 @@
-//! An in-memory [`MemoryProvider`] that actually stores things.
+//! Guard-wrapping helpers over the conformance crate's in-memory drivers.
//!
-//! # Why this exists
+//! # Why the drivers are not here
//!
-//! The module port keeps meeting the same test problem. A consumer used to be
-//! handed an `Arc<dyn Memory>` and tests handed it a real `UnifiedMemory` over
-//! a temp dir, then asserted a genuine round trip: write, read back, prune.
-//! Converting the consumer to the guard breaks those tests, and the cheap
-//! answer — `#[ignore]` behind `OPENHUMAN_MODULE_PATH` — pays for each
-//! conversion with real coverage.
+//! [`InMemoryProvider`] (a substring-recall store that actually retains, for
+//! round-trip assertions) and [`FixedRecallProvider`] (a constant `recall`, for
+//! tests about what a caller does with a scripted result set) are engine-neutral
+//! reference drivers, and live in `tinymemory-conformance`. What is host-specific
+//! is wrapping one in a real [`MemoryGuard`](super::MemoryGuard) at the trusted
+//! tier, so a consumer converted to hold a guard can be tested through the same
+//! policy decorator production uses; that is all this module keeps.
//!
-//! [`super::test_support::RecordingProvider`] cannot stand in: it records calls
-//! and answers empty, which proves a call was *made* but never that the data
-//! came back. Round-trip assertions need storage.
-//!
-//! So this is storage: a `HashMap` keyed by `(namespace, key)` behind a mutex,
-//! implementing the mandatory three so it can be wrapped in a real
-//! [`MemoryGuard`](super::MemoryGuard) and dropped in wherever a consumer now
-//! wants a guard.
-//!
-//! # It is deliberately not `#[cfg(test)]`
-//!
-//! Integration tests under `tests/` link the library compiled without
-//! `cfg(test)`, so a test-gated helper is invisible to them — the trap
-//! `ProfileStore::for_tests` documents and this port has already fallen into
-//! once. `#[doc(hidden)]` keeps it off the public docs instead.
-//!
-//! # What it does not pretend to be
-//!
-//! `recall` is a substring match over content, not a ranked hybrid search. That
-//! is enough for "did the write land and come back", which is what these tests
-//! assert; it is **not** enough to test ranking, and a test about ordering
-//! should use the real engine rather than this.
+//! `RecordingProvider` (`test_support`) cannot stand in for either: it records
+//! calls, which proves a call was *made* but never that data came back.
-use std::collections::HashMap;
use std::sync::Arc;
-use async_trait::async_trait;
-use parking_lot::Mutex;
-
-use crate::memory::api::capabilities::Capabilities;
-use crate::memory::api::error::MemoryError;
-use crate::memory::api::health::MemoryHealth;
-use crate::memory::api::provider::types::SourceScope;
-use crate::memory::api::provider::types::{ExportPage, ExportRecord, ImportOutcome};
-use crate::memory::api::provider::{MemoryCore, MemoryPortability, MemoryProvider, MemoryRecall};
-use crate::memory::api::recall::OwnedRecallOpts;
-use crate::memory::api::types::{MemoryCategory, MemoryEntry, MemoryTaint, NamespaceSummary};
-
-/// Entries held in memory, keyed by `(namespace, key)`.
-#[derive(Default)]
-pub struct InMemoryProvider {
- entries: Mutex<HashMap<(String, String), MemoryEntry>>,
-}
-
-impl InMemoryProvider {
- #[must_use]
- pub fn new() -> Self {
- Self::default()
- }
-
- /// How many entries are stored, for assertions about pruning.
- #[must_use]
- pub fn len(&self) -> usize {
- self.entries.lock().len()
- }
-
- /// Whether the store holds nothing.
- #[must_use]
- pub fn is_empty(&self) -> bool {
- self.entries.lock().is_empty()
- }
-}
-
-#[async_trait]
-impl MemoryCore for InMemoryProvider {
- async fn store(
- &self,
- namespace: &str,
- key: &str,
- content: &str,
- category: MemoryCategory,
- session_id: Option<&str>,
- taint: MemoryTaint,
- ) -> Result<(), MemoryError> {
- let entry = MemoryEntry {
- id: format!("{namespace}/{key}"),
- key: key.to_string(),
- content: content.to_string(),
- namespace: Some(namespace.to_string()),
- category,
- // Monotonic enough for "oldest first" pruning assertions, and
- // stable to render.
- timestamp: chrono::Utc::now().to_rfc3339(),
- session_id: session_id.map(str::to_string),
- score: None,
- taint,
- };
- self.entries
- .lock()
- .insert((namespace.to_string(), key.to_string()), entry);
- Ok(())
- }
-
- async fn get(&self, namespace: &str, key: &str) -> Result<Option<MemoryEntry>, MemoryError> {
- Ok(self
- .entries
- .lock()
- .get(&(namespace.to_string(), key.to_string()))
- .cloned())
- }
-
- async fn forget(&self, namespace: &str, key: &str) -> Result<bool, MemoryError> {
- Ok(self
- .entries
- .lock()
- .remove(&(namespace.to_string(), key.to_string()))
- .is_some())
- }
-
- async fn list(
- &self,
- namespace: Option<&str>,
- category: Option<&MemoryCategory>,
- session_id: Option<&str>,
- ) -> Result<Vec<MemoryEntry>, MemoryError> {
- let entries = self.entries.lock();
- let mut out: Vec<MemoryEntry> = entries
- .values()
- .filter(|e| namespace.is_none_or(|ns| e.namespace.as_deref() == Some(ns)))
- .filter(|e| category.is_none_or(|c| &e.category == c))
- .filter(|e| session_id.is_none_or(|s| e.session_id.as_deref() == Some(s)))
- .cloned()
- .collect();
- // Deterministic order — a `HashMap`'s iteration order varies per
- // process and would make an otherwise-identical assertion flaky.
- out.sort_by(|a, b| a.key.cmp(&b.key));
- Ok(out)
- }
-
- async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {
- let entries = self.entries.lock();
- let mut counts: HashMap<String, usize> = HashMap::new();
- for entry in entries.values() {
- if let Some(ns) = &entry.namespace {
- *counts.entry(ns.clone()).or_default() += 1;
- }
- }
- let mut out: Vec<NamespaceSummary> = counts
- .into_iter()
- .map(|(namespace, count)| NamespaceSummary {
- namespace,
- count,
- last_updated: None,
- })
- .collect();
- out.sort_by(|a, b| a.namespace.cmp(&b.namespace));
- Ok(out)
- }
-}
-
-#[async_trait]
-impl MemoryRecall for InMemoryProvider {
- /// Substring match, not ranking — see the module docs.
- async fn recall(
- &self,
- query: &str,
- limit: usize,
- opts: &OwnedRecallOpts,
- _scope: Option<&SourceScope>,
- ) -> Result<Vec<MemoryEntry>, MemoryError> {
- let needle = query.to_lowercase();
- let entries = self.entries.lock();
- let mut out: Vec<MemoryEntry> = entries
- .values()
- .filter(|e| {
- opts.namespace
- .as_deref()
- .is_none_or(|ns| e.namespace.as_deref() == Some(ns))
- })
- .filter(|e| e.content.to_lowercase().contains(&needle))
- .cloned()
- .collect();
- out.sort_by(|a, b| a.key.cmp(&b.key));
- out.truncate(limit);
- Ok(out)
- }
-}
-
-#[async_trait]
-impl MemoryPortability for InMemoryProvider {
- async fn export_page(
- &self,
- _cursor: Option<&str>,
- _limit: usize,
- ) -> Result<ExportPage, MemoryError> {
- Err(MemoryError::Other(anyhow::anyhow!(
- "InMemoryProvider does not implement export"
- )))
- }
-
- async fn import_records(
- &self,
- _records: Vec<ExportRecord>,
- ) -> Result<ImportOutcome, MemoryError> {
- Err(MemoryError::Other(anyhow::anyhow!(
- "InMemoryProvider does not implement import"
- )))
- }
-}
-
-#[async_trait]
-impl MemoryProvider for InMemoryProvider {
- fn driver_id(&self) -> &str {
- "in-memory"
- }
+use crate::memory::api::provider::MemoryProvider;
+use crate::memory::api::types::MemoryEntry;
- /// Only the mandatory three. Advertising more would fail
- /// `audit_provider`, since no optional accessor is overridden.
- fn capabilities(&self) -> Capabilities {
- Capabilities::mandatory()
- }
-
- async fn health(&self) -> MemoryHealth {
- MemoryHealth::Ready
- }
-}
+pub use tinymemory_conformance::{FixedRecallProvider, InMemoryProvider};
/// A real [`MemoryGuard`](super::MemoryGuard) over a fresh in-memory store,
/// plus the store itself for direct assertions.
@@ -244,7 +38,7 @@ pub fn guarded_in_memory() -> (Arc<InMemoryProvider>, Arc<super::MemoryGuard>) {
/// provider directly and skipping the guard entirely.
#[must_use]
pub fn guard_over(provider: Arc<dyn MemoryProvider>) -> Arc<super::MemoryGuard> {
- let policy = Arc::new(super::GuardPolicy::new(
+ let policy = Arc::new(super::HostGuardPolicy::new(
"in-memory",
crate::core::subsystem::DriverClass::Embedded,
crate::config::schema::MemoryHooksConfig::default(),
@@ -253,118 +47,9 @@ pub fn guard_over(provider: Arc<dyn MemoryProvider>) -> Arc<super::MemoryGuard>
Arc::new(super::MemoryGuard::new(provider, policy))
}
-/// A provider whose `recall` answers with a fixed entry list, whatever the
-/// query.
-///
-/// # Why this is not [`InMemoryProvider`]
-///
-/// That one substring-matches, which is right for a round-trip test and wrong
-/// for the several channel/context tests that script a specific result set —
-/// scored entries, an over-long entry, ten entries to overflow a budget — and
-/// assert on what the *caller* does with it. Those tests are about rendering
-/// and filtering downstream of recall, so recall itself has to be a constant.
-///
-/// Everything else is inert: writes are accepted and dropped, reads answer
-/// empty. A test needing real storage wants [`InMemoryProvider`].
-pub struct FixedRecallProvider {
- entries: Vec<MemoryEntry>,
-}
-
-impl FixedRecallProvider {
- #[must_use]
- pub fn new(entries: Vec<MemoryEntry>) -> Self {
- Self { entries }
- }
-
- /// The provider wrapped in a real guard, ready to drop into a context.
- #[must_use]
- pub fn guarded(entries: Vec<MemoryEntry>) -> Arc<super::MemoryGuard> {
- guard_over(Arc::new(Self::new(entries)) as Arc<dyn MemoryProvider>)
- }
-}
-
-#[async_trait]
-impl MemoryCore for FixedRecallProvider {
- async fn store(
- &self,
- _namespace: &str,
- _key: &str,
- _content: &str,
- _category: MemoryCategory,
- _session_id: Option<&str>,
- _taint: MemoryTaint,
- ) -> Result<(), MemoryError> {
- Ok(())
- }
-
- async fn get(&self, _namespace: &str, _key: &str) -> Result<Option<MemoryEntry>, MemoryError> {
- Ok(None)
- }
-
- async fn forget(&self, _namespace: &str, _key: &str) -> Result<bool, MemoryError> {
- Ok(false)
- }
-
- async fn list(
- &self,
- _namespace: Option<&str>,
- _category: Option<&MemoryCategory>,
- _session_id: Option<&str>,
- ) -> Result<Vec<MemoryEntry>, MemoryError> {
- Ok(Vec::new())
- }
-
- async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {
- Ok(Vec::new())
- }
-}
-
-#[async_trait]
-impl MemoryRecall for FixedRecallProvider {
- async fn recall(
- &self,
- _query: &str,
- _limit: usize,
- _opts: &OwnedRecallOpts,
- _scope: Option<&SourceScope>,
- ) -> Result<Vec<MemoryEntry>, MemoryError> {
- Ok(self.entries.clone())
- }
-}
-
-#[async_trait]
-impl MemoryPortability for FixedRecallProvider {
- async fn export_page(
- &self,
- _cursor: Option<&str>,
- _limit: usize,
- ) -> Result<ExportPage, MemoryError> {
- Err(MemoryError::Other(anyhow::anyhow!(
- "FixedRecallProvider does not implement export"
- )))
- }
-
- async fn import_records(
- &self,
- _records: Vec<ExportRecord>,
- ) -> Result<ImportOutcome, MemoryError> {
- Err(MemoryError::Other(anyhow::anyhow!(
- "FixedRecallProvider does not implement import"
- )))
- }
-}
-
-#[async_trait]
-impl MemoryProvider for FixedRecallProvider {
- fn driver_id(&self) -> &str {
- "fixed-recall"
- }
-
- fn capabilities(&self) -> Capabilities {
- Capabilities::mandatory()
- }
-
- async fn health(&self) -> MemoryHealth {
- MemoryHealth::Ready
- }
+/// A real [`MemoryGuard`](super::MemoryGuard) over a [`FixedRecallProvider`]
+/// that answers `entries` to every recall, ready to drop into a context.
+#[must_use]
+pub fn guarded_fixed_recall(entries: Vec<MemoryEntry>) -> Arc<super::MemoryGuard> {
+ guard_over(Arc::new(FixedRecallProvider::new(entries)) as Arc<dyn MemoryProvider>)
}
diff --git a/crates/openhuman-core/src/memory/guard/mod.rs b/crates/openhuman-core/src/memory/guard/mod.rs
index 13a6fbed89..d696cb8924 100644
--- a/crates/openhuman-core/src/memory/guard/mod.rs
+++ b/crates/openhuman-core/src/memory/guard/mod.rs
@@ -41,7 +41,7 @@
//! | 4 | redaction | `GuardPolicy::redact_outbound` — a no-op for embedded drivers |
//! | 5 | egress + trust | `GuardPolicy::check_egress` |
//! | 6 | char budgets | `tinymemory_guard::budget`, driven by `MemoryHooksConfig` |
-//! | 7 | audit + tracing | [`audit`], `tinymemory_guard::audit` |
+//! | 7 | audit + tracing | `audit`, `tinymemory_guard::audit` |
//!
//! Three of those departed from the milestone brief because the brief's version
//! would have been wrong against this tree; each departure is argued at its own
@@ -88,7 +88,7 @@
//! This note used to say the fix "needs a fourteenth family in
//! `tinycortex_api`". **That family now exists.** The contract has
//! `MemoryProfile` (`tinymemory_api::provider::profile`, eleven methods) and
-//! [`families::GuardedProfile`] implements it, so the guarded door is built.
+//! `tinymemory_guard::families::GuardedProfile` implements it, so the guarded door is built.
//! What remains is migrating any remaining direct `ProfileStore` caller onto
//! it, plus the release lag on
//! the module that serves it — `MemoryProfile` is one of the five families that
@@ -122,3 +122,10 @@ pub use policy::HostGuardPolicy;
/// The policy decorator every product caller receives instead of the raw driver:
/// `tinymemory_guard::GuardedProvider` over the host's policy.
pub type MemoryGuard = tinymemory_guard::GuardedProvider<HostGuardPolicy>;
+
+#[cfg(test)]
+#[path = "families_tests.rs"]
+mod families_tests;
+#[cfg(test)]
+#[path = "provider_tests.rs"]
+mod provider_tests;
diff --git a/crates/openhuman-core/src/memory/guard/policy_tests.rs b/crates/openhuman-core/src/memory/guard/policy_tests.rs
index e980b53d42..2286e4828e 100644
--- a/crates/openhuman-core/src/memory/guard/policy_tests.rs
+++ b/crates/openhuman-core/src/memory/guard/policy_tests.rs
@@ -241,7 +241,7 @@ fn guard_does_not_redact_for_an_embedded_driver() {
#[test]
fn guard_does_not_redact_for_a_null_driver() {
- let policy = GuardPolicy::new(
+ let policy = HostGuardPolicy::new(
"null",
DriverClass::Null,
MemoryHooksConfig::default(),
@@ -258,7 +258,7 @@ fn guard_does_not_redact_for_a_null_driver() {
/// to catch it. This test is what would catch that move.
#[test]
fn guard_does_not_redact_for_a_module_driver() {
- let policy = GuardPolicy::new(
+ let policy = HostGuardPolicy::new(
"tinymemory",
DriverClass::Module,
MemoryHooksConfig::default(),
@@ -274,7 +274,7 @@ fn guard_does_not_redact_for_a_module_driver() {
#[test]
fn guard_does_not_redact_json_for_a_module_driver() {
- let policy = GuardPolicy::new(
+ let policy = HostGuardPolicy::new(
"tinymemory",
DriverClass::Module,
MemoryHooksConfig::default(),
@@ -336,7 +336,7 @@ fn guard_admits_an_external_driver_whose_trust_was_raised() {
#[test]
fn budgets_come_from_the_hooks_config() {
- let policy = GuardPolicy::new(
+ let policy = HostGuardPolicy::new(
"tinycortex",
DriverClass::Embedded,
MemoryHooksConfig {
@@ -352,7 +352,7 @@ fn budgets_come_from_the_hooks_config() {
#[test]
fn a_zero_budget_reads_as_disabled_not_as_deny_everything() {
- let policy = GuardPolicy::new(
+ let policy = HostGuardPolicy::new(
"tinycortex",
DriverClass::Embedded,
MemoryHooksConfig {
diff --git a/crates/openhuman-core/src/memory/guard/provider_tests.rs b/crates/openhuman-core/src/memory/guard/provider_tests.rs
index c3c3f37858..f77ea597f5 100644
--- a/crates/openhuman-core/src/memory/guard/provider_tests.rs
+++ b/crates/openhuman-core/src/memory/guard/provider_tests.rs
@@ -1,17 +1,14 @@
-//! The guard as a [`MemoryProvider`]: capability mirroring, the mandatory
-//! three, and step 7's audit event.
+//! The host wiring of the guard: `HostGuardPolicy` fed by the ambient source
+//! scope and the configured hook budgets, and step 7's bus event.
+//!
+//! The decorator's own behaviour (capability mirroring, taint raising, scope
+//! narrowing, per-family enforcement) is tested with it, in `tinymemory-guard`.
-use super::*;
use std::sync::Arc;
-use crate::memory::api::capabilities::{Capabilities, Capability};
-use crate::memory::api::provider::types::SourceScope;
-use crate::memory::api::provider::{
- audit_provider, MemoryCore, MemoryPortability, MemoryProvider, MemoryRecall,
-};
+use crate::memory::api::provider::{MemoryCore, MemoryProvider, MemoryRecall};
use crate::memory::api::recall::OwnedRecallOpts;
use crate::memory::api::types::{MemoryCategory, MemoryTaint};
-use tinymemory_api::null::NullMemoryProvider;
use crate::config::schema::MemoryHooksConfig;
use crate::core::bus::BUS;
@@ -19,14 +16,13 @@ use crate::core::events::DomainEvent;
use crate::core::subsystem::DriverClass;
use crate::memory::guard::policy::TRUSTED;
use crate::memory::guard::test_support::{
- embedded_policy, entry, export_record, external_policy, guarded, guarded_with,
- RecordingProvider,
+ embedded_policy, entry, external_policy, guarded, guarded_with, RecordingProvider,
};
-use crate::memory::guard::GuardPolicy;
+use crate::memory::guard::HostGuardPolicy;
use crate::memory::source_scope::with_source_scope;
-fn budgeted(recall_max_chars: usize, capture_max_chars: usize) -> GuardPolicy {
- GuardPolicy::new(
+fn budgeted(recall_max_chars: usize, capture_max_chars: usize) -> HostGuardPolicy {
+ HostGuardPolicy::new(
"recording",
DriverClass::Embedded,
MemoryHooksConfig {
@@ -38,53 +34,7 @@ fn budgeted(recall_max_chars: usize, capture_max_chars: usize) -> GuardPolicy {
)
}
-// ── Identity + capability mirroring ─────────────────────────────────────────
-
-#[tokio::test]
-async fn guard_reports_the_wrapped_drivers_identity() {
- let (_driver, guard) = guarded(embedded_policy());
- assert_eq!(
- guard.driver_id(),
- "recording",
- "the guard is a policy layer, not a driver"
- );
- assert_eq!(guard.capabilities(), Capabilities::all());
-}
-
-#[tokio::test]
-async fn guard_passes_audit_provider_against_its_own_capabilities() {
- let (_driver, guard) = guarded(embedded_policy());
- audit_provider(&guard).expect("advertised set and reachable accessors must agree");
-}
-
-#[tokio::test]
-async fn guard_accessor_presence_mirrors_inner_provides_for_every_family() {
- let (_driver, guard) = guarded(embedded_policy());
- for capability in Capability::ALL {
- assert!(
- guard.provides(capability),
- "{capability} must be reachable through the guard"
- );
- }
-
- // The other direction: a driver with only the mandatory three must not
- // acquire families merely by being guarded.
- let inner = Arc::new(NullMemoryProvider::new());
- let null = MemoryGuard::new(
- Arc::clone(&inner) as Arc<dyn MemoryProvider>,
- Arc::new(embedded_policy()),
- );
- for capability in Capability::ALL {
- assert_eq!(
- null.provides(capability),
- inner.provides(capability),
- "{capability} presence must mirror the inner driver exactly"
- );
- }
- audit_provider(&null).expect("mandatory-only driver stays consistent when guarded");
-}
-
-// ── The mandatory three ─────────────────────────────────────────────────────
+// ── Ambient scope and hook budgets ──────────────────────────────────────────
#[tokio::test]
async fn guard_stamps_taint_on_store_rather_than_trusting_the_caller() {
@@ -142,56 +92,6 @@ async fn guard_truncates_recall_results_to_recall_max_chars() {
assert_eq!(hits[1].content, "bb");
}
-/// Pins the departure argued in `mandatory.rs`: the embedded driver *refuses* a
-/// `Some(scope)` on recall, so the guard must NOT fill it from the task-local.
-#[tokio::test]
-async fn guard_never_fills_scope_on_recall() {
- let (driver, guard) = guarded(embedded_policy());
- with_source_scope(Some(vec!["slack:#eng".into()]), async {
- guard
- .recall("q", 10, &OwnedRecallOpts::default(), None)
- .await
- .expect("recall must not become an error merely by being scoped");
- })
- .await;
- assert_eq!(driver.only_call().scoped, Some(false));
-}
-
-#[tokio::test]
-async fn guard_forwards_an_explicit_recall_scope_untouched() {
- let (driver, guard) = guarded(embedded_policy());
- let scope = SourceScope::new(["slack:#eng"]);
- let _ = guard
- .recall("q", 10, &OwnedRecallOpts::default(), Some(&scope))
- .await;
- assert_eq!(driver.only_call().scoped, Some(true));
-}
-
-#[tokio::test]
-async fn guard_preserves_import_taint_rather_than_restamping_it() {
- let (driver, guard) = guarded(embedded_policy());
- // Inside a source scope, so a naive "stamp everything" would show up.
- with_source_scope(Some(vec!["slack:#eng".into()]), async {
- guard
- .import_records(vec![export_record(MemoryTaint::Internal)])
- .await
- .expect("import");
- })
- .await;
- assert_eq!(
- driver.only_call().taint,
- Some(MemoryTaint::Internal),
- "a restore must not have its provenance rewritten wholesale"
- );
-}
-
-#[tokio::test]
-async fn guard_does_not_budget_trim_an_export() {
- let (driver, guard) = guarded(budgeted(1, 1));
- guard.export_page(None, 10).await.expect("export");
- assert_eq!(driver.only_call().method, "portability.export_page");
-}
-
// ── Step 7 ──────────────────────────────────────────────────────────────────
struct DeniedRecorder {
diff --git a/crates/openhuman-core/src/memory/guard/test_support.rs b/crates/openhuman-core/src/memory/guard/test_support.rs
index 1cb5acbc84..1122176a46 100644
--- a/crates/openhuman-core/src/memory/guard/test_support.rs
+++ b/crates/openhuman-core/src/memory/guard/test_support.rs
@@ -1,21 +1,149 @@
-//! A recording fake [`MemoryProvider`] for the guard's tests.
+//! Fixtures for the guard's tests and for the domains that test through it.
//!
-//! `NullMemoryProvider` cannot serve here: it advertises only the mandatory
-//! three and returns `None` from every `as_*` accessor, so a guard built over
-//! it would have no family decorators at all — which is precisely what the
-//! interesting tests are about. This fake implements **all thirteen** families
-//! and records what actually reached it, so a test can assert both "the driver
-//! saw the value the guard rewrote" and "the driver saw nothing at all".
+//! The recording fake itself is `tinymemory_conformance::RecordingProvider`: it
+//! implements **all** the optional families and records what actually reached
+//! it, so a test can assert both "the driver saw the value the guard rewrote"
+//! and "the driver saw nothing at all". `NullMemoryProvider` cannot serve here —
+//! it advertises only the mandatory three, so a guard built over it would have
+//! no family decorators. What stays in the host is the part that names host
+//! types: policies over a [`DriverClass`], and the guard wrapping.
#![cfg(test)]
-mod fixtures;
+use std::sync::Arc;
-mod core_and_docs_impls;
-mod provider_and_sync_impls;
-mod retrieval_and_ingest_impls;
-
-pub use fixtures::{
- document, embedded_policy, entry, export_record, external_policy, guarded, guarded_with,
- namespace_hit, RecordingProvider,
+use crate::config::schema::MemoryHooksConfig;
+use crate::core::subsystem::DriverClass;
+use crate::memory::api::provider::types::ExportRecord;
+use crate::memory::api::provider::MemoryProvider;
+use crate::memory::api::types::{
+ MemoryCategory, MemoryEntry, MemoryItemKind, MemoryTaint, NamespaceDocumentInput,
+ NamespaceMemoryHit, NamespaceSummary, RetrievalScoreBreakdown,
};
+use crate::memory::guard::{HostGuardPolicy, MemoryGuard};
+
+pub use tinymemory_conformance::RecordingProvider;
+
+/// A [`HostGuardPolicy`] over an embedded driver with default budgets — the
+/// shipped configuration.
+pub fn embedded_policy() -> HostGuardPolicy {
+ HostGuardPolicy::new(
+ "recording",
+ DriverClass::Embedded,
+ MemoryHooksConfig::default(),
+ super::policy::TRUSTED,
+ )
+}
+
+/// A policy over an *external* driver. No such driver can bind today
+/// (`binding::admit` refuses them), so this is the only way to reach the class
+/// branches that land for real in M6.
+pub fn external_policy(trust_state: &str) -> HostGuardPolicy {
+ HostGuardPolicy::new(
+ "supermemory",
+ DriverClass::External,
+ MemoryHooksConfig::default(),
+ trust_state,
+ )
+}
+
+/// An [`ExportRecord`] fixture.
+pub fn export_record(taint: MemoryTaint) -> ExportRecord {
+ ExportRecord {
+ kind: "entry".into(),
+ id: "r1".into(),
+ namespace: Some("ns".into()),
+ taint,
+ payload: serde_json::Value::Null,
+ }
+}
+
+/// A guard over a fresh recording provider, plus a handle on that provider.
+pub fn guarded(policy: HostGuardPolicy) -> (Arc<RecordingProvider>, MemoryGuard) {
+ guarded_with(RecordingProvider::new(), policy)
+}
+
+/// As [`guarded`], over a caller-configured provider.
+pub fn guarded_with(
+ provider: RecordingProvider,
+ policy: HostGuardPolicy,
+) -> (Arc<RecordingProvider>, MemoryGuard) {
+ let provider = Arc::new(provider);
+ let guard = MemoryGuard::new(
+ Arc::clone(&provider) as Arc<dyn MemoryProvider>,
+ Arc::new(policy),
+ );
+ (provider, guard)
+}
+
+/// A [`MemoryEntry`] fixture.
+pub fn entry(content: &str) -> MemoryEntry {
+ MemoryEntry {
+ id: "id".into(),
+ key: "key".into(),
+ content: content.into(),
+ namespace: Some("ns".into()),
+ category: MemoryCategory::Core,
+ timestamp: "2026-01-01T00:00:00Z".into(),
+ session_id: None,
+ score: None,
+ taint: MemoryTaint::Internal,
+ }
+}
+
+/// A [`NamespaceDocumentInput`] fixture.
+pub fn document(content: &str, taint: MemoryTaint) -> NamespaceDocumentInput {
+ NamespaceDocumentInput {
+ namespace: "ns".into(),
+ key: "k".into(),
+ title: "t".into(),
+ content: content.into(),
+ source_type: "chat".into(),
+ priority: "normal".into(),
+ tags: vec![],
+ metadata: serde_json::Value::Null,
+ category: "core".into(),
+ session_id: None,
+ document_id: None,
+ taint,
+ }
+}
+
+/// A [`NamespaceSummary`] fixture.
+pub fn namespace_summary(namespace: &str, count: usize) -> NamespaceSummary {
+ NamespaceSummary {
+ namespace: namespace.into(),
+ count,
+ last_updated: None,
+ }
+}
+
+/// A [`NamespaceMemoryHit`] with only the vector component set — the signal the
+/// vector-floored recall paths (Lane B, the contradiction check) filter on.
+pub fn namespace_hit(
+ namespace: &str,
+ key: &str,
+ content: &str,
+ vector_similarity: f64,
+) -> NamespaceMemoryHit {
+ NamespaceMemoryHit {
+ id: format!("{namespace}/{key}"),
+ kind: MemoryItemKind::Kv,
+ namespace: namespace.into(),
+ key: key.into(),
+ title: None,
+ content: content.into(),
+ category: "core".into(),
+ source_type: None,
+ updated_at: 0.0,
+ score: vector_similarity,
+ score_breakdown: RetrievalScoreBreakdown {
+ vector_similarity,
+ ..Default::default()
+ },
+ document_id: None,
+ chunk_id: None,
+ supporting_relations: Vec::new(),
+ taint: MemoryTaint::default(),
+ }
+}