The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(memory): remove unused confinement and user scope modules
Steven Enamakeld208de4821f0
diff --git a/crates/openhuman-core/src/memory/confine.rs b/crates/openhuman-core/src/memory/confine.rsdeleted file mode 100644index 40f97de1ba..0000000000--- a/crates/openhuman-core/src/memory/confine.rs+++ /dev/null@@ -1,237 +0,0 @@-//! Confinement of the ambient memory surface: the `openhuman.memory_*` RPCs-//! and the MCP memory tools, which dispatch through them.-//!-//! The agent `memory` tool ([`super::tools`]) always reads and forgets within-//! the acting identity's layout: `Reach::subtree(<root>)`. The RPCs used to-//! take whatever filter the caller sent, and with no `reach` an engine reads-//! every namespace, so an RPC or MCP caller could list, read and forget-//! another root's memory (another team's, or another host-bound agent's).-//!-//! Every RPC resolves the identity the caller passes ([`tinymemory_tools::layout::identity::Identity`]; the-//! RPC handlers pass [`tinymemory_tools::layout::identity::Identity::root`], the config's own root-//! identity) and:-//!-//! - fills an unset `reach` with that identity's subtree ([`allowed_reach`]);-//! - keeps a caller's reach only when it is [`Reach::within`] the allowed-//! one, and refuses a wider one with `INVALID_REQUEST`;-//! - places a `learn` with no namespace at the identity's learnings node and-//! refuses one aimed outside the subtree.--use tinymemory_api::{ExplorePage, MemoryMeta, MetaFilter, Namespace, Reach};--use crate::config::Config;--use super::explore::{self, ExploreParams, ItemsGetParams, ItemsGetView};-use super::ops;-use tinymemory_tools::layout::identity::Identity;-use super::types::{- FetchParams, FetchView, ForgetParams, ForgetView, ItemsListParams, ItemsListView, LearnParams,- LearnView, RecallParams, RecallView,-};-use tinymemory_api::{Error, Result};--/// What `identity` under `config` may read and forget: the subtree of its-/// layout root.-#[must_use]-pub fn allowed_reach(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> Reach {- Reach::subtree(identity.resolve(&crate::memory::scope::identity_pins(config)).root().clone())-}--/// `reach` confined to `allowed`: unset becomes `allowed`, a reach within it-/// is kept.-///-/// # Errors-///-/// [`Error::InvalidRequest`] when `reach` reads outside `allowed`.-pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> Result<Reach> {- match reach {- None => Ok(allowed.clone()),- Some(reach) if reach.within(allowed) => Ok(reach),- Some(reach) => {- tracing::warn!(- asked = %reach.at,- allowed = %allowed.at,- "[memory:confine] refused a reach outside the caller's root"- );- Err(Error::InvalidRequest(format!(- "the reach `{}` is outside this caller's memory (`{}`)",- reach.at, allowed.at- )))- }- }-}--/// `filter` with its reach confined to `allowed` ([`confine_reach`]).-///-/// # Errors-///-/// [`Error::InvalidRequest`] when the filter's reach reads outside-/// `allowed`.-pub fn confine_filter(filter: Option<MetaFilter>, allowed: &Reach) -> Result<MetaFilter> {- let mut filter = filter.unwrap_or_default();- filter.reach = Some(confine_reach(filter.reach.take(), allowed)?);- Ok(filter)-}--/// The metadata a `memory_learn` caller sent, with its namespace inside the-/// `identity`'s layout: an unset namespace (the root) lands at the-/// layout's learnings node when that is not the root itself.-///-/// # Errors-///-/// [`Error::InvalidRequest`] when the namespace is outside the-/// layout's subtree.-pub fn confine_learn_meta(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- meta: Option<MemoryMeta>,-) -> Result<MemoryMeta> {- let resolved = identity.resolve(&crate::memory::scope::identity_pins(config));- let allowed = Reach::subtree(resolved.root().clone());- let mut meta = meta.unwrap_or_default();- if meta.namespace == Namespace::ROOT {- meta.namespace = resolved.layout.learnings().clone();- }- if !allowed.admits(&meta.namespace) {- tracing::warn!(- asked = %meta.namespace,- allowed = %allowed.at,- "[memory:confine] refused a learning outside the caller's root"- );- return Err(Error::InvalidRequest(format!(- "the namespace `{}` is outside this caller's memory (`{}`)",- meta.namespace, allowed.at- )));- }- Ok(meta)-}--/// `memory_recall`, confined.-///-/// # Errors-///-/// A reach outside the caller's root, or what [`ops::recall`] returns.-pub async fn recall(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: RecallParams,-) -> Result<RecallView> {- params.filter = Some(confine_filter(- params.filter,- &allowed_reach(config, identity),- )?);- ops::recall(config, params).await-}--/// `memory_fetch`, confined.-///-/// # Errors-///-/// A reach outside the caller's root, or what [`ops::fetch`] returns.-pub async fn fetch(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: FetchParams,-) -> Result<FetchView> {- params.filter = Some(confine_filter(- params.filter,- &allowed_reach(config, identity),- )?);- ops::fetch(config, params).await-}--/// `memory_learn`, confined: the learning lands inside the caller's layout.-///-/// # Errors-///-/// A namespace outside the caller's root, or what [`ops::learn`] returns.-pub async fn learn(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: LearnParams,-) -> Result<LearnView> {- params.meta = Some(confine_learn_meta(config, identity, params.meta)?);- ops::learn(config, params, None).await-}--/// `memory_forget`, confined: an id outside the caller's root is not-/// forgotten.-///-/// # Errors-///-/// A reach outside the caller's root, or what [`ops::forget`] returns.-pub async fn forget(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: ForgetParams,-) -> Result<ForgetView> {- params.reach = Some(confine_reach(- params.reach,- &allowed_reach(config, identity),- )?);- ops::forget(config, params).await-}--/// `memory_items_list`, confined. The explorer path narrows first (a-/// namespace step sets the reach), then the narrowed filter is confined.-///-/// # Errors-///-/// A reach outside the caller's root, an invalid path, or what-/// [`ops::items_list`] returns.-pub async fn items_list(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: ItemsListParams,-) -> Result<ItemsListView> {- let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;- params.filter = Some(confine_filter(- Some(narrowed),- &allowed_reach(config, identity),- )?);- params.path = Vec::new();- ops::items_list(config, params).await-}--/// `memory_explore`, confined like [`items_list`].-///-/// # Errors-///-/// A reach outside the caller's root, an invalid path, or what-/// [`explore::explore`] returns.-pub async fn explore(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: ExploreParams,-) -> Result<ExplorePage> {- let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;- params.filter = Some(confine_filter(- Some(narrowed),- &allowed_reach(config, identity),- )?);- params.path = Vec::new();- explore::explore(config, params).await-}--/// `memory_items_get`, confined: an id outside the caller's root reads as-/// unknown.-///-/// # Errors-///-/// A reach outside the caller's root, or what [`explore::items_get`]-/// returns.-pub async fn items_get(- config: &Config,- identity: &tinymemory_tools::layout::identity::Identity,- mut params: ItemsGetParams,-) -> Result<ItemsGetView> {- params.reach = Some(confine_reach(- params.reach,- &allowed_reach(config, identity),- )?);- explore::items_get(config, params).await-}--#[cfg(test)]-#[path = "confine_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/confinement_tests.rs b/crates/openhuman-core/src/memory/confinement_tests.rsnew file mode 100644index 0000000000..e3ea373c4e--- /dev/null+++ b/crates/openhuman-core/src/memory/confinement_tests.rs@@ -0,0 +1,264 @@+use std::sync::Arc;++use tinymemory_api::conformance::ReferenceEngine;+use tinymemory_api::{+ Error, LearningKind, MemoryEngine, MemoryMeta, MetaFilter, Namespace, Reach, SourceKind,+ SourceRef, StoreItem,+};+use tinymemory_tools::confine::{Confinement, Policy};+use tinymemory_tools::layout::identity::Identity;++use crate::memory::explore::{self, ExploreParams, ItemsGetParams, ItemsListParams, PathStep};+use crate::memory::test_fixtures::{bind_reference, config_in};+use crate::memory::types::{+ FetchParams, ForgetParams, LearnParams, RecallParams,+};++fn ns(raw: &str) -> Namespace {+ raw.parse().unwrap()+}++fn confinement(config: &crate::config::Config, identity: &Identity) -> Confinement {+ let resolved = identity.resolve(&crate::memory::scope::identity_pins(config));+ Confinement {+ allowed: Reach::subtree(resolved.root().clone()),+ policy: Policy::Refuse,+ }+}++fn learning_at(text: &str, namespace: &str) -> StoreItem {+ StoreItem::learning(+ text,+ LearningKind::Fact,+ 0.9,+ MemoryMeta {+ namespace: ns(namespace),+ source: SourceRef {+ kind: SourceKind::Agent,+ id: None,+ },+ ..MemoryMeta::default()+ },+ )+}++async fn two_roots(tmp: &tempfile::TempDir) -> (crate::config::Config, String, String) {+ let mut config = config_in(tmp);+ config.memory.root = Some("team:acme".to_string());+ let engine = bind_reference(&config);+ let mine = engine+ .store(learning_at("acme ships on fridays", "team:acme"))+ .await+ .unwrap()+ .id+ .0;+ let theirs = engine+ .store(learning_at("other team secret plan", "team:other"))+ .await+ .unwrap()+ .id+ .0;+ (config, mine, theirs)+}++fn ids(hits: &[tinymemory_api::Hit]) -> Vec<String> {+ hits.iter().map(|hit| hit.id.0.clone()).collect()+}++#[test]+fn rpc_refuse_uses_the_identity_subtree_and_rejects_wider_reaches() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = config_in(&tmp);+ config.memory.root = Some("project:q4".to_string());+ let rpc = confinement(&config, &Identity::root());+ assert_eq!(rpc.allowed, Reach::subtree(ns("project:q4")));+ assert_eq!(rpc.reach(None).unwrap(), Reach::subtree(ns("project:q4")));++ let narrow = Reach::exact(ns("project:q4/agent:writer"));+ assert_eq!(rpc.reach(Some(narrow.clone())).unwrap(), narrow);+ for wider in [+ Reach::subtree(Namespace::ROOT),+ Reach::subtree(ns("team:other")),+ Reach::of(ns("project:q4/agent:writer")),+ ] {+ assert!(matches!(+ rpc.reach(Some(wider)),+ Err(Error::InvalidRequest(_))+ ));+ }++ let team = confinement(+ &config_in(&tmp),+ &Identity::team_member("acme", "scout"),+ );+ assert_eq!(team.allowed, Reach::subtree(ns("team:acme")));+}++#[tokio::test]+async fn rpc_list_fetch_and_recall_never_read_another_root() {+ let tmp = tempfile::tempdir().unwrap();+ let (config, mine, theirs) = two_roots(&tmp).await;+ let rpc = confinement(&config, &Identity::root());++ let listed = crate::memory::ops::items_list(+ &config,+ ItemsListParams {+ filter: Some(rpc.filter(None).unwrap()),+ ..ItemsListParams::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(ids(&listed.items), std::slice::from_ref(&mine));++ let page = crate::memory::ops::fetch(+ &config,+ FetchParams {+ refers_to: None,+ query: "plan".into(),+ mode: None,+ filter: Some(rpc.filter(None).unwrap()),+ limit: Some(100),+ cursor: None,+ },+ )+ .await+ .unwrap();+ assert!(!ids(&page.hits).contains(&theirs), "{:?}", ids(&page.hits));++ let answer = crate::memory::ops::recall(+ &config,+ RecallParams {+ refers_to: None,+ question: "secret plan".into(),+ filter: Some(rpc.filter(None).unwrap()),+ limit: Some(10),+ },+ )+ .await+ .unwrap();+ assert!(answer+ .citations+ .iter()+ .all(|citation| citation.id.0 != theirs));+}++#[tokio::test]+async fn rpc_filter_and_explorer_paths_outside_the_identity_are_refused() {+ let tmp = tempfile::tempdir().unwrap();+ let (config, _, _) = two_roots(&tmp).await;+ let rpc = confinement(&config, &Identity::root());+ let outside = MetaFilter {+ reach: Some(Reach::subtree(ns("team:other"))),+ ..MetaFilter::default()+ };+ assert!(matches!(+ rpc.filter(Some(outside.clone())),+ Err(Error::InvalidRequest(_))+ ));++ let path = vec![PathStep {+ facet: tinymemory_api::Facet::Namespace,+ value: "team:other".to_string(),+ }];+ let narrowed = explore::narrowed(None, &path).unwrap();+ assert!(matches!(+ rpc.filter(Some(narrowed)),+ Err(Error::InvalidRequest(_))+ ));++ let response = crate::memory::ops::items_list(+ &config,+ ItemsListParams {+ filter: Some(rpc.filter(None).unwrap()),+ ..ItemsListParams::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(response.items.len(), 1);+}++#[tokio::test]+async fn rpc_items_get_and_forget_cannot_reach_another_root() {+ let tmp = tempfile::tempdir().unwrap();+ let (config, _, theirs) = two_roots(&tmp).await;+ let rpc = confinement(&config, &Identity::root());++ let get = explore::items_get(+ &config,+ ItemsGetParams {+ ids: vec![theirs.clone()],+ reach: Some(rpc.reach(None).unwrap()),+ },+ )+ .await+ .unwrap();+ assert!(get.items.is_empty());++ let forgotten = crate::memory::ops::forget(+ &config,+ ForgetParams {+ ids: vec![theirs.clone()],+ reach: Some(rpc.reach(None).unwrap()),+ },+ )+ .await+ .unwrap();+ assert_eq!(forgotten.forgotten, 0);++ let engine: Arc<dyn MemoryEngine> = crate::memory::engine::resolve(&config).engine().unwrap().engine;+ assert_eq!(ids(&engine.list(tinymemory_api::ListRequest {+ filter: MetaFilter { reach: Some(Reach::subtree(ns("team:other"))), ..MetaFilter::default() },+ limit: 10,+ cursor: None,+ }).await.unwrap().items).as_slice(), [theirs]);+}++#[tokio::test]+async fn rpc_learn_uses_the_layout_default_and_refuses_an_explicit_outside_namespace() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = config_in(&tmp);+ config.memory.root = Some("team:acme".to_string());+ let engine = bind_reference(&config);+ let identity = Identity::root().resolve(&crate::memory::scope::identity_pins(&config));+ let rpc = confinement(&config, &Identity::root());+ let default_meta = rpc+ .learn_meta(None, identity.layout.learnings())+ .unwrap();+ let result = crate::memory::ops::learn(+ &config,+ LearnParams {+ text: "my learning".into(),+ kind: None,+ confidence: None,+ meta: Some(default_meta.clone()),+ },+ None,+ )+ .await+ .unwrap();+ let item = engine+ .list(tinymemory_api::ListRequest {+ filter: MetaFilter {+ reach: Some(Reach::subtree(ns("team:acme"))),+ ..MetaFilter::default()+ },+ limit: 10,+ cursor: None,+ })+ .await+ .unwrap()+ .items+ .into_iter()+ .find(|item| item.id.0 == result.id)+ .unwrap();+ assert_eq!(item.meta.namespace, default_meta.namespace);++ let mut outside = MemoryMeta::default();+ outside.namespace = ns("team:other");+ assert!(matches!(+ rpc.learn_meta(Some(outside), identity.layout.learnings()),+ Err(Error::InvalidRequest(_))+ ));+}diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rsindex 39788faf8b..be194ee2f9 100644--- a/crates/openhuman-core/src/memory/mod.rs+++ b/crates/openhuman-core/src/memory/mod.rs@@ -5,7 +5,7 @@//! | --- | --- |//! | [`engine`] | Binds the `[memory]` engine (`tinyhumans` over the host's backend credential, or `cortexdb` with a stored key); memory is **off** without one |//! | [`guard`] | Scrubs secrets and PII from every write, whichever path it takes |-//! | [`scope`] | Who is acting: the layout root and memory agent id a turn runs as |+//! | [`scope`] | Config-to-identity pins and the account layout migration hooks |//! | [`lifecycle`] | The turn hooks (pre-turn pack, post-turn log, compaction recall) and the background job queue |//! | [`ops`] | Engine selection, recall, fetch, learn, forget, list, the pack preview |//! | [`brain`] | The shared brain: documents by source type |@@ -24,7 +24,6 @@ pub mod billing;pub mod brain;pub mod bus;pub mod channels;-pub mod confine;pub mod deletion;pub mod engine;pub mod error;@@ -44,11 +43,14 @@ mod tool_budget;pub(crate) mod tool_writes;pub mod tools;pub mod types;-pub mod user_scope;#[cfg(test)]pub(crate) mod test_fixtures;+#[cfg(test)]+#[path = "confinement_tests.rs"]+mod confinement_tests;+pub use bus::register_memory_subscribers;pub use engine::is_on as memory_is_on;pub use schemas::{diff --git a/crates/openhuman-core/src/memory/user_scope.rs b/crates/openhuman-core/src/memory/user_scope.rsdeleted file mode 100644index 522137bf26..0000000000--- a/crates/openhuman-core/src/memory/user_scope.rs+++ /dev/null@@ -1,86 +0,0 @@-//! Confining a SaaS user's memory to the user's own tree.-//!-//! Every SaaS profile runs with `[memory] root = user:<profile>`, on the-//! legacy layout (`profiles::layout::profile_config`). The lifecycle hooks already read and-//! write below that root, but the memory operations — the `memory.*` RPCs and-//! the agent's memory tools — pass the caller's filter or namespace straight-//! to the engine. Users normally have engines of their own (each is bound to-//! the user's backend credential), so that alone keeps them apart; but users-//! may share an engine (a shared backend key, one CortexDB key), and then a-//! filter that reaches the tree's root would read everyone.-//!-//! So in SaaS mode, for a config that names a root:-//!-//! - every read reaches only the subtree below the root: a reach that already-//! lies inside it keeps its node but loses ancestors (which would climb out-//! of the root); any other reach becomes the root's subtree;-//! - every write lands inside the root: an item addressed elsewhere is moved-//! to the root itself.-//!-//! A SaaS config without a valid root makes memory refuse rather than reach-//! everyone. Single-user processes are left alone.--use tinymemory_api::{MetaFilter, Namespace, Reach, StoreItem};--use crate::config::Config;-use tinymemory_api::{Error, Result};--/// The root `config`'s memory is confined to, in SaaS mode (`None` in single-/// user mode). A SaaS config without a valid root is refused: neither the-/// global root (everyone's memory) nor no confinement at all is safe.-pub fn confinement(config: &Config) -> Result<Option<Namespace>> {- confinement_in(crate::core::runtime::is_saas(), config)-}--/// [`confinement`] as a pure function of the mode.-pub fn confinement_in(saas: bool, config: &Config) -> Result<Option<Namespace>> {- if !saas {- return Ok(None);- }- let raw = config.memory.root.as_deref().map(str::trim).unwrap_or("");- match raw.parse::<Namespace>() {- Ok(root) if root != Namespace::ROOT => Ok(Some(root)),- Ok(_) | Err(_) => {- tracing::error!(- root = raw,- "[memory:user_scope] no valid confinement root in SaaS mode"- );- Err(Error::InvalidRequest(- ("memory is unavailable: this agent has no valid memory root").into(),- ))- }- }-}--/// Whether `namespace` is `root` or lies below it.-pub fn within(namespace: &Namespace, root: &Namespace) -> bool {- namespace.segments().starts_with(root.segments())-}--/// `reach`, confined to `root`.-pub fn clamp_reach(reach: Option<Reach>, root: &Namespace) -> Reach {- match reach {- Some(reach) if within(&reach.at, root) => Reach {- inherit: false,- ..reach- },- _ => Reach::subtree(root.clone()),- }-}--/// `filter`, with its reach confined to `root`.-pub fn clamp_filter(mut filter: MetaFilter, root: &Namespace) -> MetaFilter {- filter.reach = Some(clamp_reach(filter.reach.take(), root));- filter-}--/// `item`, addressed inside `root`.-pub fn clamp_item(item: &mut StoreItem, root: &Namespace) {- if !within(&item.meta().namespace, root) {- item.meta_mut().namespace = root.clone();- }-}--#[cfg(test)]-#[path = "user_scope_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/user_scope_tests.rs b/crates/openhuman-core/src/memory/user_scope_tests.rsdeleted file mode 100644index d54868a64c..0000000000--- a/crates/openhuman-core/src/memory/user_scope_tests.rs+++ /dev/null@@ -1,247 +0,0 @@-use std::sync::{- atomic::{AtomicUsize, Ordering},- Arc,-};--use tinymemory_api::conformance::ReferenceEngine;-use tinymemory_api::{- EngineDescriptor, FetchRequest, ForgetReport, ForgetTarget, LearningKind, ListRequest,- MemoryEngine, MemoryMeta, RecallRequest, StoreItem, StoreReceipt,-};--use super::*;--fn ns(raw: &str) -> Namespace {- raw.parse().unwrap()-}--fn user_config(root: &str) -> Config {- let mut config = Config::default();- config.memory.root = Some(root.to_string());- config-}--#[test]-fn only_saas_configs_are_confined() {- assert!(confinement_in(false, &user_config("user:u-a"))- .unwrap()- .is_none());- assert_eq!(- confinement_in(true, &user_config("user:u-a")).unwrap(),- Some(ns("user:u-a"))- );-}--#[test]-fn a_saas_config_without_a_valid_root_is_refused() {- // No root, an unparseable one, or the global root: memory refuses rather- // than reaching every user.- assert!(confinement_in(true, &Config::default()).is_err());- assert!(confinement_in(true, &user_config("")).is_err());- assert!(confinement_in(true, &user_config("not a namespace!")).is_err());-}--#[test]-fn invalid_saas_identity_keeps_the_existing_rpc_error() {- for config in [- Config::default(),- user_config("not a namespace!"),- user_config("root"),- ] {- let error = confinement_in(true, &config).unwrap_err();- assert!(matches!(- error,- Error::InvalidRequest(message)- if message == "memory is unavailable: this agent has no valid memory root"- ));- }-}--#[test]-fn invalid_saas_root_is_refused_before_store_reaches_the_engine() {- const CHILD: &str = "OPENHUMAN_TEST_SAAS_MEMORY_STORE_GUARD";- const TEST_NAME: &str = "memory::user_scope::tests::invalid_saas_root_is_refused_before_store_reaches_the_engine";-- if std::env::var_os(CHILD).is_none() {- let output = std::process::Command::new(std::env::current_exe().unwrap())- .args(["--exact", TEST_NAME, "--nocapture"])- .env(CHILD, "1")- .output()- .unwrap();- assert!(- output.status.success()- && String::from_utf8_lossy(&output.stdout)- .contains("SAAS_MEMORY_STORE_GUARD_CHILD_PASSED"),- "isolated SaaS test process failed or ran zero tests:\n{}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- return;- }-- crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();- let runtime = tokio::runtime::Builder::new_current_thread()- .enable_all()- .build()- .unwrap();- for root in [None, Some("not a namespace!"), Some("root")] {- let tmp = tempfile::tempdir().unwrap();- let mut config = crate::memory::test_fixtures::config_in(&tmp);- config.memory.root = root.map(str::to_string);- let calls = Arc::new(AtomicUsize::new(0));- crate::memory::engine::install_test_engine(- &config.workspace_dir,- Arc::new(CountingEngine {- inner: ReferenceEngine::new(),- calls: calls.clone(),- }),- );- let item = StoreItem::learning(- "should not be stored",- LearningKind::Fact,- 0.9,- MemoryMeta::default(),- );- let error = runtime- .block_on(crate::memory::ops::store_item(&config, item))- .unwrap_err();-- assert!(matches!(- error,- Error::InvalidRequest(message)- if message == "memory is unavailable: this agent has no valid memory root"- ));- assert_eq!(calls.load(Ordering::SeqCst), 0, "root: {root:?}");- }- println!("SAAS_MEMORY_STORE_GUARD_CHILD_PASSED");-}--struct CountingEngine {- inner: ReferenceEngine,- calls: Arc<AtomicUsize>,-}--#[async_trait::async_trait]-impl MemoryEngine for CountingEngine {- fn descriptor(&self) -> &EngineDescriptor {- self.inner.descriptor()- }-- async fn health(&self) -> tinymemory_api::EngineHealth {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.health().await- }-- async fn recall(- &self,- request: RecallRequest,- ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.recall(request).await- }-- async fn fetch(- &self,- request: FetchRequest,- ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.fetch(request).await- }-- async fn store(&self, item: StoreItem) -> tinymemory_api::Result<StoreReceipt> {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.store(item).await- }-- async fn forget(- &self,- target: ForgetTarget,- ) -> tinymemory_api::Result<ForgetReport> {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.forget(target).await- }-- async fn list(- &self,- request: ListRequest,- ) -> tinymemory_api::Result<tinymemory_api::ListPage> {- self.calls.fetch_add(1, Ordering::SeqCst);- self.inner.list(request).await- }-}--#[test]-fn reads_never_climb_out_of_the_root() {- let root = ns("user:u-a");- assert_eq!(clamp_reach(None, &root), Reach::subtree(root.clone()));- assert_eq!(- clamp_reach(Some(Reach::of(Namespace::ROOT)), &root),- Reach::subtree(root.clone()),- "the tree's root reads everyone"- );- assert_eq!(- clamp_reach(Some(Reach::subtree(ns("user:u-b"))), &root),- Reach::subtree(root.clone()),- "another user's tree"- );- let inside = clamp_reach(Some(Reach::of(ns("user:u-a/agent:u-a"))), &root);- assert_eq!(inside.at, ns("user:u-a/agent:u-a"));- assert!(!inside.inherit, "ancestors would include the shared root");-}--#[test]-fn writes_land_inside_the_root() {- let root = ns("user:u-a");- let mut meta = MemoryMeta::default();- meta.namespace = ns("user:u-b");- let mut item = StoreItem::learning("x", LearningKind::Fact, 0.8, meta);- clamp_item(&mut item, &root);- assert_eq!(item.meta().namespace, root);-- let mut meta = MemoryMeta::default();- meta.namespace = ns("user:u-a/agent:u-a");- let mut item = StoreItem::learning("x", LearningKind::Fact, 0.8, meta);- clamp_item(&mut item, &root);- assert_eq!(item.meta().namespace, ns("user:u-a/agent:u-a"));-}--/// Two users on one shared engine: a clamped filter lists only the caller's-/// items, even when the caller asked for the whole tree.-#[tokio::test]-async fn a_shared_engine_keeps_users_apart_once_clamped() {- let engine: Arc<dyn MemoryEngine> = Arc::new(ReferenceEngine::new());- for (user, text) in [("user:u-a", "alice's fact"), ("user:u-b", "bob's fact")] {- let mut item = StoreItem::learning(text, LearningKind::Fact, 0.8, MemoryMeta::default());- clamp_item(&mut item, &ns(user));- engine.store(item).await.unwrap();- }- let everyone = MetaFilter {- reach: Some(Reach::subtree(Namespace::ROOT)),- ..MetaFilter::default()- };- let unclamped = engine- .list(ListRequest {- filter: everyone.clone(),- limit: 100,- cursor: None,- })- .await- .unwrap();- assert_eq!(- unclamped.items.len(),- 2,- "unclamped, the tree root reads both"- );-- let clamped = engine- .list(ListRequest {- filter: clamp_filter(everyone, &ns("user:u-a")),- limit: 100,- cursor: None,- })- .await- .unwrap();- let texts: Vec<_> = clamped.items.iter().map(|hit| format!("{hit:?}")).collect();- assert_eq!(clamped.items.len(), 1, "{texts:?}");- assert!(texts[0].contains("alice"), "{texts:?}");-}