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): move identity types into tinymemory-tools
Steven Enamakelffd8d0d0b4f9
diff --git a/crates/openhuman-core/src/agent/bus.rs b/crates/openhuman-core/src/agent/bus.rsindex 2af6756156..14a9f5f58d 100644--- a/crates/openhuman-core/src/agent/bus.rs+++ b/crates/openhuman-core/src/agent/bus.rs@@ -299,7 +299,7 @@ async fn handle_agent_run_turn(req: AgentTurnRequest) -> Result<AgentTurnRespons);// Memory acts as the target agent (the root when none is named) for// the whole channel turn.- let memory_identity = crate::memory::scope::MemoryIdentity::root()+ let memory_identity = tinymemory_tools::layout::identity::Identity::root().child(target_agent_id.as_deref().unwrap_or_default());let graph_origin = origin.clone();let outcome = turn_origin::with_origin(diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rsindex b2ed10ef19..e1d41a4204 100644--- a/crates/openhuman-core/src/agent/harness/graph.rs+++ b/crates/openhuman-core/src/agent/harness/graph.rs@@ -59,7 +59,7 @@ pub(crate) async fn run_channel_turn_via_graph(origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,sandbox_mode: tinyagents_definition::SandboxMode,approval: crate::security::approval::ApprovalTurnContext,- memory_identity: crate::memory::scope::MemoryIdentity,+ memory_identity: tinymemory_tools::layout::identity::Identity,) -> Result<crate::agent::tinyagents::TinyagentsTurnOutcome> {let extra_arc = Arc::new(extra_tools);// A channel/CLI turn is entered without a run context: the model sourcediff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rsindex 54ea31fa34..0f8355651e 100644--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs@@ -238,7 +238,7 @@ async fn run_member_loop(// never read each other's.// The member acts on memory as itself, in its team: it rides the parent's// host environment, so every run started from that parent keeps it.- let identity = crate::memory::scope::MemoryIdentity::team_member(team_id, agent_id);+ let identity = tinymemory_tools::layout::identity::Identity::team_member(team_id, agent_id);let member_turn = with_root_parent(ctx,parent_override,diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rsindex dfd09a5e6e..6813d0a275 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs@@ -26,7 +26,7 @@ use tinyinference_llm::message::Message;use super::OpenHumanTurnPrelude;use crate::agent::tinyagents::host::OpenHumanRunContext;use crate::memory::lifecycle::hooks::{self, MemoryTurn, ToolCallSummary};-use crate::memory::scope::ResolvedIdentity;+use tinymemory_tools::layout::identity::ResolvedIdentity;/// The memory side of the turn in flight, held from pre-turn to commit.#[derive(Clone)]@@ -122,7 +122,7 @@ impl OpenHumanTurnPrelude {// The identity the turn's run context carries: the host environment's// (a team member's), narrowed to this agent.let acting = self.host_env.memory_identity.clone().unwrap_or_default();- let mut identity = acting.child(&self.agent_definition_id).resolve(&config);+ let mut identity = acting.child(&self.agent_definition_id).resolve(&crate::memory::scope::identity_pins(&config));if self.omit_memory_context {identity.recall = false;}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rsindex 3fd41a08de..0c828e38f0 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs@@ -52,7 +52,7 @@ pub(crate) struct HostOperationContext {pub(crate) parent_agent_id: Option<String>,/// Who the run acts as on memory; see/// [`OpenHumanRunContext::memory_identity`](super::OpenHumanRunContext::memory_identity).- pub(crate) memory_identity: Option<crate::memory::scope::MemoryIdentity>,+ pub(crate) memory_identity: Option<tinymemory_tools::layout::identity::Identity>,/// The turn's memory, read live for the thread's turns still verbatim in/// the run's prompt (see [`MemoryTurn::in_prompt`](crate::memory::lifecycle::hooks::MemoryTurn::in_prompt))./// `None` when the turn has no memory, as a sub-agent's run does.@@ -113,7 +113,7 @@ pub(crate) fn parent_agent_id_for_tool(/// dispatch has none.pub(crate) fn memory_identity_for_tool(context: Option<&dyn tinytools::ToolRunContext>,-) -> Option<crate::memory::scope::MemoryIdentity> {+) -> Option<tinymemory_tools::layout::identity::Identity> {context.and_then(tinytools::ToolRunContext::host_extension).and_then(|extension| {diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 6d45f0535b..8e7a275727 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -308,7 +308,7 @@ pub struct OpenHumanRunContext {/// Context-preparation sources already consumed in this turn.pub prepared_context_sources: Arc<Vec<AgentContextPreparedSource>>,/// Who the run acts as on memory; `None` is the root identity.- pub memory_identity: Option<crate::memory::scope::MemoryIdentity>,+ pub memory_identity: Option<tinymemory_tools::layout::identity::Identity>,/// The context the turn runs under, read by tools, middleware and the/// provider factory instead of the ambient scope. Children inherit it.pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsindex 821af67226..3c96f65763 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -576,32 +576,32 @@ async fn the_approval_context_survives_await_points_and_a_move_between_tasks() {/// an environment without one leaves the run's own alone.#[test]fn the_memory_identity_rides_the_run_and_its_children() {- use crate::memory::scope::MemoryIdentity;+ use tinymemory_tools::layout::identity::Identity;let mut context = OpenHumanRunContext::new();assert_eq!(context.memory_identity, None);let env = crate::agent::turn_env::HostTurnEnv {- memory_identity: Some(MemoryIdentity::team_member("acme", "lead")),+ memory_identity: Some(tinymemory_tools::layout::identity::Identity::team_member("acme", "lead")),..Default::default()};context = context.with_host_env(&env);assert_eq!(context.memory_identity,- Some(MemoryIdentity::team_member("acme", "lead"))+ Some(tinymemory_tools::layout::identity::Identity::team_member("acme", "lead")));let child = context.child();assert_eq!(child.memory_identity, context.memory_identity);assert_eq!(child.memory_identity.unwrap().child("scout"),- MemoryIdentity::team_member("acme", "scout")+ tinymemory_tools::layout::identity::Identity::team_member("acme", "scout"));let unchanged = context.with_host_env(&crate::agent::turn_env::HostTurnEnv::default());assert_eq!(unchanged.memory_identity,- Some(MemoryIdentity::team_member("acme", "lead"))+ Some(tinymemory_tools::layout::identity::Identity::team_member("acme", "lead")));}@@ -692,7 +692,7 @@ fn the_turns_still_in_the_prompt_reach_the_runs_tools() {let mut host = OpenHumanRunContext::new();host.memory_turn = Some(std::sync::Arc::new(crate::memory::lifecycle::hooks::MemoryTurn {- identity: crate::memory::scope::MemoryIdentity::agent("a").resolve(&config),+ identity: tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config)),config: std::sync::Arc::new(config),thread_id: "thread-long".into(),pack: None,diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rsindex 88d02f2b86..ebb77df653 100644--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs@@ -4,7 +4,7 @@ use chrono::Utc;use tinyagents_harness::summarization::ConcatSummarizer;use crate::memory::lifecycle::hooks::{post_turn, pre_turn_work};-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in};struct Failing;@@ -21,7 +21,7 @@ impl Summarizer for Failing {async fn bound_turn(tmp: &tempfile::TempDir) -> Arc<MemoryTurn> {let config = config_in(tmp);bind_reference(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));pre_turn_work(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -250,7 +250,7 @@ async fn a_held_memory_engine_does_not_delay_transcript_compaction() {inner: tinymemory_api::conformance::ReferenceEngine::new(),}),);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let turn = Arc::new(MemoryTurn {config: Arc::new(config),identity,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rsindex 5e6295d4f9..0499ef1457 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs@@ -9,13 +9,13 @@ use tinyagents_harness::context::RunConfig;use tinyinference_llm::message::Message;use crate::memory::lifecycle::hooks::{MemoryTurn, TurnPack, OPEN_TAG};-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;fn context(pack: Option<TurnPack>) -> RunContext<OpenHumanRunContext> {let config = crate::config::Config::default();let mut data = OpenHumanRunContext::new();data.memory_turn = Some(Arc::new(MemoryTurn {- identity: MemoryIdentity::agent("a").resolve(&config),+ identity: tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config)),config: Arc::new(config),thread_id: "t".into(),pack,diff --git a/crates/openhuman-core/src/agent/turn_env.rs b/crates/openhuman-core/src/agent/turn_env.rsindex f01d542d01..1960138e93 100644--- a/crates/openhuman-core/src/agent/turn_env.rs+++ b/crates/openhuman-core/src/agent/turn_env.rs@@ -56,7 +56,7 @@ pub struct HostTurnEnv {/// a turn or sub-agent narrows with `child(<definition id>)`. `None` is the/// root identity. Unlike `approval` it follows delegation, so runs started/// from a parent snapshot keep the parent's team.- pub memory_identity: Option<crate::memory::scope::MemoryIdentity>,+ pub memory_identity: Option<tinymemory_tools::layout::identity::Identity>,/// The [`CoreContext`](crate::core::runtime::CoreContext) the turn runs/// under (the tenant's, an embedded agent's, or the host's own), held/// weakly: the env outlives a turn, and a strong handle would keep thediff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rsindex 567dda778f..f76eb249f1 100644--- a/crates/openhuman-core/src/memory/backfill.rs+++ b/crates/openhuman-core/src/memory/backfill.rs@@ -38,7 +38,7 @@ use serde::{Deserialize, Serialize};use crate::config::Config;use crate::memory::engine::{self, BoundEngine};-use crate::memory::scope::{MemoryIdentity, ResolvedIdentity};+use tinymemory_tools::layout::identity::{Identity, ResolvedIdentity};use crate::threads::store::blocking as threads;use tinymemory_api::{Error, Result};use tinymemory_integrations::import::ImportPhase;@@ -254,7 +254,7 @@ pub async fn start(turns = pending_turns,"[memory:backfill] started");- let identity = MemoryIdentity::agent(MAIN_AGENT).resolve(config);+ let identity = tinymemory_tools::layout::identity::Identity::agent(MAIN_AGENT).resolve(&crate::memory::scope::identity_pins(config));tokio::spawn(async move {run(&workspace_dir, &bound, &identity, file, plans).await;release(&workspace_dir);diff --git a/crates/openhuman-core/src/memory/backfill_tests.rs b/crates/openhuman-core/src/memory/backfill_tests.rsindex 2d5f95faf4..7c6c066a3d 100644--- a/crates/openhuman-core/src/memory/backfill_tests.rs+++ b/crates/openhuman-core/src/memory/backfill_tests.rs@@ -114,7 +114,7 @@ async fn stores_past_chats_once_and_skips_what_live_logging_took() {).await;// The lifecycle logged live-thread's second turn (user index 2).- let identity = MemoryIdentity::agent(MAIN_AGENT).resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent(MAIN_AGENT).resolve(&crate::memory::scope::identity_pins(&config));crate::memory::lifecycle::hooks::pre_turn_work(&crate::core::runtime::DispatchCtx::ambient(),&config,diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rsindex c74d9346ec..0a98cd3e0b 100644--- a/crates/openhuman-core/src/memory/brain.rs+++ b/crates/openhuman-core/src/memory/brain.rs@@ -21,7 +21,7 @@ use crate::config::Config;use super::engine;use super::lifecycle::jobs;-use super::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use tinymemory_api::{Error, Result};/// Largest file `memory_brain_ingest` reads, in bytes.@@ -52,11 +52,11 @@ pub fn brain_node(}/// The layout the brain RPCs act on: `identity`'s.-fn layout(config: &Config, identity: &MemoryIdentity) -> MemoryLayout {- identity.resolve(config).layout+fn layout(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> MemoryLayout {+ identity.resolve(&crate::memory::scope::identity_pins(config)).layout}-fn brain(config: &Config, identity: &MemoryIdentity) -> Result<Brain> {+fn brain(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> Result<Brain> {let bound = engine::resolve(config).engine()?;Ok(Brain::new(bound.engine, layout(config, identity)))}@@ -87,7 +87,7 @@ pub struct BrainSourcesView {}/// `memory_brain_sources`: the brain's sources and their sizes.-pub async fn sources(config: &Config, identity: &MemoryIdentity) -> Result<BrainSourcesView> {+pub async fn sources(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> Result<BrainSourcesView> {let bound = engine::resolve(config).engine()?;let layout = layout(config, identity);let page = bound@@ -149,7 +149,7 @@ pub struct BrainSearchView {/// `memory_brain_search`.pub async fn search(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,params: BrainSearchParams,) -> Result<BrainSearchView> {let query = params.query.trim();@@ -218,7 +218,7 @@ async fn ingest_path(config: &Config, path: &str) -> Result<std::path::PathBuf>/// source's belief build. The write waits only for the engine to accept it.pub async fn ingest(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,params: BrainIngestParams,) -> Result<BrainIngestView> {let source = params.source.as_deref().map(parse_source).transpose()?;@@ -299,7 +299,7 @@ pub struct BrainForgetView {/// `memory_brain_forget`: forgets every document of one source.pub async fn forget(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,params: BrainForgetParams,) -> Result<BrainForgetView> {let source = parse_source(¶ms.source)?;diff --git a/crates/openhuman-core/src/memory/brain_tests.rs b/crates/openhuman-core/src/memory/brain_tests.rsindex 245532cb24..2f77d0aee7 100644--- a/crates/openhuman-core/src/memory/brain_tests.rs+++ b/crates/openhuman-core/src/memory/brain_tests.rs@@ -1,6 +1,6 @@use super::*;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use tinymemory_tools::layout::placement::file_into;use tinymemory_api::{ItemKind, MemoryMeta, MetaFilter};@@ -57,7 +57,7 @@ async fn a_sources_collections_count_and_forget_with_it() {};engine.store(StoreItem::document(text, meta)).await.unwrap();}- let view = sources(&config, &MemoryIdentity::root()).await.unwrap();+ let view = sources(&config, &tinymemory_tools::layout::identity::Identity::root()).await.unwrap();let counts: Vec<(&str, u64)> = view.sources.iter()@@ -68,7 +68,7 @@ async fn a_sources_collections_count_and_forget_with_it() {let gone = forget(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainForgetParams {source: "github".into(),},@@ -94,7 +94,7 @@ async fn text_is_ingested_searched_counted_and_forgotten_per_source() {let ingested = ingest(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainIngestParams {path: None,text: Some("Refunds are issued within 14 days.".into()),@@ -107,7 +107,7 @@ async fn text_is_ingested_searched_counted_and_forgotten_per_source() {assert_eq!(ingested.source, "notion");ingest(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainIngestParams {path: None,text: Some("Onboarding takes a week.".into()),@@ -126,14 +126,14 @@ async fn text_is_ingested_searched_counted_and_forgotten_per_source() {"one belief build per source");- let counts = sources(&config, &MemoryIdentity::root()).await.unwrap();+ let counts = sources(&config, &tinymemory_tools::layout::identity::Identity::root()).await.unwrap();assert_eq!(counts.root, "root");assert_eq!(counts.sources.len(), 2);assert_eq!(counts.unfiled, 0);let found = search(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainSearchParams {query: "refunds".into(),source: Some("notion".into()),@@ -146,7 +146,7 @@ async fn text_is_ingested_searched_counted_and_forgotten_per_source() {let gone = forget(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainForgetParams {source: "notion".into(),},@@ -188,13 +188,13 @@ async fn ingest_refuses_bad_input() {},] {assert!(matches!(- ingest(&config, &MemoryIdentity::root(), params).await,+ ingest(&config, &tinymemory_tools::layout::identity::Identity::root(), params).await,Err(Error::InvalidRequest(_))));}assert!(search(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainSearchParams {query: " ".into(),source: None,@@ -214,7 +214,7 @@ async fn a_file_is_converted_and_filed_under_files() {std::fs::write(&path, "# Guide\n\nAlways tag releases.").unwrap();let ingested = ingest(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainIngestParams {path: Some(path.display().to_string()),text: None,@@ -244,7 +244,7 @@ async fn an_ingest_queues_a_belief_build_only_for_an_engine_that_waits_for_one());ingest(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainIngestParams {path: None,text: Some("Refunds are issued within 14 days.".into()),@@ -289,7 +289,7 @@ async fn ingest_refuses_a_credential_store_a_system_root_traversal_and_null_byteformat!("{}/../guide.md", notes.display()),format!("{}\0.md", tmp.path().join("guide").display()),] {- let result = ingest(&config, &MemoryIdentity::root(), path_params(path.clone())).await;+ let result = ingest(&config, &tinymemory_tools::layout::identity::Identity::root(), path_params(path.clone())).await;assert!(matches!(result, Err(Error::InvalidRequest(_))),"{path:?}: {result:?}"@@ -312,7 +312,7 @@ async fn ingest_refuses_a_symlink_into_a_credential_store() {let result = ingest(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),path_params(link.display().to_string()),).await;diff --git a/crates/openhuman-core/src/memory/confine.rs b/crates/openhuman-core/src/memory/confine.rsindex 949074431b..40f97de1ba 100644--- a/crates/openhuman-core/src/memory/confine.rs+++ b/crates/openhuman-core/src/memory/confine.rs@@ -7,8 +7,8 @@//! 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 ([`MemoryIdentity`]; the-//! RPC handlers pass [`MemoryIdentity::root`], the config's own root+//! 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`]);@@ -23,7 +23,7 @@ use crate::config::Config;use super::explore::{self, ExploreParams, ItemsGetParams, ItemsGetView};use super::ops;-use super::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use super::types::{FetchParams, FetchView, ForgetParams, ForgetView, ItemsListParams, ItemsListView, LearnParams,LearnView, RecallParams, RecallView,@@ -33,8 +33,8 @@ 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: &MemoryIdentity) -> Reach {- Reach::subtree(identity.resolve(config).root().clone())+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@@ -83,10 +83,10 @@ pub fn confine_filter(filter: Option<MetaFilter>, allowed: &Reach) -> Result<Met/// layout's subtree.pub fn confine_learn_meta(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,meta: Option<MemoryMeta>,) -> Result<MemoryMeta> {- let resolved = identity.resolve(config);+ 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 {@@ -113,7 +113,7 @@ pub fn confine_learn_meta(/// A reach outside the caller's root, or what [`ops::recall`] returns.pub async fn recall(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: RecallParams,) -> Result<RecallView> {params.filter = Some(confine_filter(@@ -130,7 +130,7 @@ pub async fn recall(/// A reach outside the caller's root, or what [`ops::fetch`] returns.pub async fn fetch(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: FetchParams,) -> Result<FetchView> {params.filter = Some(confine_filter(@@ -147,7 +147,7 @@ pub async fn fetch(/// A namespace outside the caller's root, or what [`ops::learn`] returns.pub async fn learn(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: LearnParams,) -> Result<LearnView> {params.meta = Some(confine_learn_meta(config, identity, params.meta)?);@@ -162,7 +162,7 @@ pub async fn learn(/// A reach outside the caller's root, or what [`ops::forget`] returns.pub async fn forget(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: ForgetParams,) -> Result<ForgetView> {params.reach = Some(confine_reach(@@ -181,7 +181,7 @@ pub async fn forget(/// [`ops::items_list`] returns.pub async fn items_list(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: ItemsListParams,) -> Result<ItemsListView> {let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;@@ -201,7 +201,7 @@ pub async fn items_list(/// [`explore::explore`] returns.pub async fn explore(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: ExploreParams,) -> Result<ExplorePage> {let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;@@ -222,7 +222,7 @@ pub async fn explore(/// returns.pub async fn items_get(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,mut params: ItemsGetParams,) -> Result<ItemsGetView> {params.reach = Some(confine_reach(diff --git a/crates/openhuman-core/src/memory/confine_tests.rs b/crates/openhuman-core/src/memory/confine_tests.rsindex c2681bab30..19f9f1048f 100644--- a/crates/openhuman-core/src/memory/confine_tests.rs+++ b/crates/openhuman-core/src/memory/confine_tests.rs@@ -3,7 +3,7 @@ use super::*;use tinymemory_api::{LearningKind, MemoryEngine, SourceKind, SourceRef, StoreItem};use crate::memory::explore::PathStep;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in};fn ns(value: &str) -> Namespace {@@ -75,12 +75,12 @@ fn the_allowed_reach_is_the_identity_roots_subtree() {let tmp = tempfile::tempdir().unwrap();let mut config = config_in(&tmp);assert_eq!(- allowed_reach(&config, &MemoryIdentity::root()),+ allowed_reach(&config, &tinymemory_tools::layout::identity::Identity::root()),Reach::subtree(Namespace::ROOT));config.memory.root = Some("project:q4".to_string());assert_eq!(- allowed_reach(&config, &MemoryIdentity::root()),+ allowed_reach(&config, &tinymemory_tools::layout::identity::Identity::root()),Reach::subtree(ns("project:q4")));}@@ -89,7 +89,7 @@ fn the_allowed_reach_is_the_identity_roots_subtree() {fn a_team_members_reach_is_its_teams_subtree() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let reach = allowed_reach(&config, &MemoryIdentity::team_member("acme", "scout"));+ let reach = allowed_reach(&config, &tinymemory_tools::layout::identity::Identity::team_member("acme", "scout"));assert_eq!(reach, Reach::subtree(ns("team:acme")));}@@ -98,14 +98,14 @@ async fn list_fetch_and_recall_never_read_another_root() {let tmp = tempfile::tempdir().unwrap();let (config, mine, theirs) = two_roots(&tmp).await;- let listed = items_list(&config, &MemoryIdentity::root(), ItemsListParams::default())+ let listed = items_list(&config, &tinymemory_tools::layout::identity::Identity::root(), ItemsListParams::default()).await.unwrap();assert_eq!(ids(&listed.items), std::slice::from_ref(&mine));let page = fetch(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),FetchParams {refers_to: None,query: "plan".into(),@@ -121,7 +121,7 @@ async fn list_fetch_and_recall_never_read_another_root() {let answer = recall(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),RecallParams {refers_to: None,question: "secret plan".into(),@@ -148,7 +148,7 @@ async fn a_caller_reach_into_another_root_is_refused() {let error = items_list(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsListParams {filter: Some(elsewhere.clone()),..ItemsListParams::default()@@ -160,7 +160,7 @@ async fn a_caller_reach_into_another_root_is_refused() {let error = fetch(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),FetchParams {refers_to: None,query: "plan".into(),@@ -176,7 +176,7 @@ async fn a_caller_reach_into_another_root_is_refused() {let error = recall(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),RecallParams {refers_to: None,question: "plan".into(),@@ -200,7 +200,7 @@ async fn an_explorer_path_into_another_root_is_refused() {let error = items_list(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsListParams {path: path.clone(),..ItemsListParams::default()@@ -212,7 +212,7 @@ async fn an_explorer_path_into_another_root_is_refused() {let error = explore(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ExploreParams {facet: tinymemory_api::Facet::Kind,path,@@ -228,7 +228,7 @@ async fn an_explorer_path_into_another_root_is_refused() {// Exploring inside the root still works and counts only its items.let page = explore(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ExploreParams {facet: tinymemory_api::Facet::Kind,path: Vec::new(),@@ -249,7 +249,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {let read = items_get(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsGetParams {ids: vec![mine.clone(), theirs.clone()],reach: None,@@ -261,7 +261,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {let error = items_get(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsGetParams {ids: vec![theirs.clone()],reach: Some(Reach::subtree(Namespace::ROOT)),@@ -273,7 +273,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {let forgotten = forget(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ForgetParams {ids: vec![theirs.clone()],reach: None,@@ -285,7 +285,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {let error = forget(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ForgetParams {ids: vec![theirs.clone()],reach: Some(Reach::subtree(ns("team:other"))),@@ -300,7 +300,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {other.memory.root = Some("team:other".to_string());let still = items_get(&other,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsGetParams {ids: vec![theirs.clone()],reach: None,@@ -313,7 +313,7 @@ async fn items_get_and_forget_leave_another_roots_items_alone() {// Its own items are forgotten as before.let forgotten = forget(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ForgetParams {ids: vec![mine],reach: None,@@ -331,7 +331,7 @@ async fn learn_lands_inside_the_root_and_refuses_another() {let learned = learn(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),LearnParams {text: "acme prefers short standups".into(),kind: None,@@ -343,7 +343,7 @@ async fn learn_lands_inside_the_root_and_refuses_another() {.unwrap();let read = items_get(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),ItemsGetParams {ids: vec![learned.id],reach: None,@@ -356,7 +356,7 @@ async fn learn_lands_inside_the_root_and_refuses_another() {let error = learn(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),LearnParams {text: "planted in another team".into(),kind: None,diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rsindex 665b0662a5..e5e393ba7e 100644--- a/crates/openhuman-core/src/memory/engine.rs+++ b/crates/openhuman-core/src/memory/engine.rs@@ -258,7 +258,7 @@ pub fn resolve(config: &Config) -> Binding {}tracing::warn!("[memory:engine] ignoring the host engine in SaaS mode");}- let root = if super::scope::layout_is_v3(config) {+ let root = if super::config.memory.layout == crate::config::MemoryLayoutMode::V3 {match super::scope::user_root(config) {Some(root) => Some(root),None => return off(None, None, "sign in to use memory in its own layout"),@@ -415,7 +415,7 @@ fn rooted(let Some(root) = root else {return (settings, "|root=legacy".to_string());};- let actor = super::scope::actor_of_root(root);+ let actor = super::tinymemory_tools::layout::identity::actor_of_root(root);let retired = legacy_read.then(|| actor.clone());let fingerprint = format!("|root={root}|tenant={tenant}|retired={}",diff --git a/crates/openhuman-core/src/memory/engine_tests.rs b/crates/openhuman-core/src/memory/engine_tests.rsindex 2782417bff..f60268f51a 100644--- a/crates/openhuman-core/src/memory/engine_tests.rs+++ b/crates/openhuman-core/src/memory/engine_tests.rs@@ -376,7 +376,7 @@ async fn switching_to_v3_persists_and_rebinds_the_persons_own_config() {"the switch rebinds");assert!(- !super::super::scope::layout_is_v3(&config),+ !super::super::config.memory.layout == crate::config::MemoryLayoutMode::V3,"the caller's copy is not the source of truth");}diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rsindex b7448a891b..0caa6586dd 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs@@ -12,7 +12,8 @@ use super::claim::ClaimKey;use super::state::FileStateStore;use crate::config::{Config, MemoryLayoutMode};use crate::memory::engine::{self, CORTEXDB_ENGINE};-use crate::memory::scope::{self, MemoryIdentity};+use crate::memory::scope;+use tinymemory_tools::layout::identity::Identity;use tinymemory_api::{Error, Result};/// The app's [`lm::LayoutHost`], bound to one account's config.@@ -84,8 +85,8 @@ impl lm::LayoutHost for AppHost {// switch.let mut v3 = self.config.clone();v3.memory.layout = MemoryLayoutMode::V3;- let layout = MemoryIdentity::root().resolve(&v3).layout;- let chat_node = scope::chat_node(&layout);+ let layout = tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(&v3)).layout;+ let chat_node = tinymemory_tools::layout::identity::chat_node(&layout);Ok(Placement {layout,chat_node,@@ -133,7 +134,7 @@ pub(super) fn claim_key(config: &Config) -> Result<Option<ClaimKey>> {}// The account, by its actor (`user:<id>`): a claim made before// `org:` roots named the same string, so it stays this account's.- let owner = scope::actor_of_root(&signed_in_root(config)?);+ let owner = tinymemory_tools::layout::identity::actor_of_root(&signed_in_root(config)?);// `<app>/users/<id>/config.toml`: the app directory every account shares.let app_dir = config.config_pathdiff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rsindex 67faa498a0..00b26f7431 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs@@ -55,11 +55,11 @@ async fn binds_the_legacy_tree_and_the_users_own() {fn places_into_the_v3_layout_before_the_switch() {let tmp = tempfile::tempdir().unwrap();let config = signed_in(&tmp);- assert!(!crate::memory::scope::layout_is_v3(&config));+ assert!(!crate::memory::config.memory.layout == crate::config::MemoryLayoutMode::V3);let mut v3 = config.clone();v3.memory.layout = crate::config::MemoryLayoutMode::V3;- let legacy = crate::memory::scope::MemoryIdentity::root()- .resolve(&config)+ let legacy = tinymemory_tools::layout::identity::Identity::root()+ .resolve(&crate::memory::scope::identity_pins(&config)).layout;let placement = AppHost::new(config.clone()).placement().unwrap();assert_ne!(placement.layout, legacy, "chats are pooled at ws:main");diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex 365e831dd8..07b81bffea 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -21,7 +21,7 @@ use tinymemory_tools::{Compaction, ContextPack, PostTurn, PreTurn, SessionStart}use crate::config::Config;use crate::memory::engine;-use crate::memory::scope::ResolvedIdentity;+use tinymemory_tools::layout::identity::ResolvedIdentity;use super::{agent_memory_on, jobs, log_only};diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs b/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rsindex cb863f056d..ee7c30143b 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs@@ -6,7 +6,7 @@ use tinymemory_api::{};use tinymemory_tools::recall::SkipReason;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in, stored};type PreTurnArgs = (@@ -46,7 +46,7 @@ fn reply(thread: &str, index: u32, text: &str) -> PostTurnArgs {async fn run_pre_turn(ctx: &crate::core::runtime::DispatchCtx,config: &crate::config::Config,- identity: &crate::memory::scope::ResolvedIdentity,+ identity: &tinymemory_tools::layout::identity::ResolvedIdentity,(thread, index, text, in_prompt_from, at, resumed, observed_actor): PreTurnArgs,) -> Option<TurnPack> {pre_turn_work(@@ -66,7 +66,7 @@ async fn run_pre_turn(async fn run_post_turn(config: &crate::config::Config,- identity: &crate::memory::scope::ResolvedIdentity,+ identity: &tinymemory_tools::layout::identity::ResolvedIdentity,(thread, index, text, calls, at): PostTurnArgs,) {post_turn(config, identity, thread, index, text, calls, at).await;@@ -146,7 +146,7 @@ async fn pre_turn_logs_the_user_turn_and_injects_what_memory_holds() {)).await.unwrap();- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),@@ -189,7 +189,7 @@ async fn recall_off_still_logs_and_logging_off_still_recalls() {.unwrap();config.memory.recall.enabled = false;- let quiet = MemoryIdentity::agent("a").resolve(&config);+ let quiet = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -207,7 +207,7 @@ async fn recall_off_still_logs_and_logging_off_still_recalls() {config.memory.recall.enabled = true;config.memory.conversations.enabled = false;- let reader = MemoryIdentity::agent("a").resolve(&config);+ let reader = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -225,7 +225,7 @@ async fn recall_off_still_logs_and_logging_off_still_recalls() {);config.memory.recall.enabled = false;- let none = MemoryIdentity::agent("a").resolve(&config);+ let none = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -240,7 +240,7 @@ async fn recall_off_still_logs_and_logging_off_still_recalls() {async fn pre_turn_without_an_engine_runs_the_turn_without_a_pack() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -258,7 +258,7 @@ async fn post_turn_logs_the_reply_and_queues_belief_builds() {let mut config = config_in(&tmp);config.memory.recall.build_beliefs_every = 2;let engine = bind_reference(&config);- let identity = MemoryIdentity::agent("writer").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("writer").resolve(&crate::memory::scope::identity_pins(&config));let mut first = reply("t", 1, "Here is the draft.");first.3.push(ToolCallSummary {@@ -294,7 +294,7 @@ async fn compaction_recalls_from_the_dropped_turns() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);bind_reference(&config);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let _ = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -320,7 +320,7 @@ async fn an_out_of_credits_recall_tells_the_turn_memory_is_unavailable() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),@@ -350,7 +350,7 @@ async fn an_unreachable_engine_is_named_as_unreachable() {"connection refused".into(),)).bind(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),@@ -377,7 +377,7 @@ async fn an_engine_fault_that_is_not_account_wide_injects_nothing() {"index corrupt".into(),)).bind(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),@@ -467,7 +467,7 @@ async fn a_turn_pack_stays_within_its_budget_against_a_large_store() {let config = config_in(&tmp);let engine = bind_reference(&config);fill_with_learnings(&engine, 1500).await;- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),@@ -506,7 +506,7 @@ async fn a_resumed_session_pack_stays_within_one_budget_and_repeats_nothing() {let config = config_in(&tmp);let engine = bind_reference(&config);fill_with_learnings(&engine, 1500).await;- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));// Earlier turns of the thread, logged the way a session logs them. Each// line is distinct, so a repeat can only be one item injected twice.for turn in 0..6u32 {@@ -576,7 +576,7 @@ async fn a_resumed_session_without_logging_still_opens_with_the_thread() {let tmp = tempfile::tempdir().unwrap();let mut config = config_in(&tmp);let _engine = bind_reference(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let _ = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -592,7 +592,7 @@ async fn a_resumed_session_without_logging_still_opens_with_the_thread() {.await;config.memory.conversations.enabled = false;- let reader = MemoryIdentity::agent("orchestrator").resolve(&config);+ let reader = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let mut resumed = input("t-quiet", 2, "remind me where the offsite is");resumed.5 = true;resumed.3 = 2;@@ -613,7 +613,7 @@ async fn a_blank_turn_is_refused_without_a_pack_with_or_without_logging() {let tmp = tempfile::tempdir().unwrap();let mut config = config_in(&tmp);let engine = bind_reference(&config);- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -630,7 +630,7 @@ async fn a_blank_turn_is_refused_without_a_pack_with_or_without_logging() {);config.memory.conversations.enabled = false;- let reader = MemoryIdentity::agent("orchestrator").resolve(&config);+ let reader = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));assert!(run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -677,7 +677,7 @@ async fn a_date_hint_asks_the_model_in_the_users_zone_and_never_costs_the_pack())).await.unwrap();- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator").resolve(&crate::memory::scope::identity_pins(&config));let pack = run_pre_turn(&crate::core::runtime::DispatchCtx::ambient(),diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rsindex f8565d22f8..73537fc4e4 100644--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs@@ -32,7 +32,7 @@ use crate::config::schema::MemoryRecallConfig;use crate::config::Config;use super::engine;-use super::scope::ResolvedIdentity;+use tinymemory_tools::layout::identity::ResolvedIdentity;use tinymemory_api::{Error, Result};/// TinyMemory's recall policy from `[memory.recall]`.@@ -83,9 +83,9 @@ pub fn agent_memory(config: &Config, identity: &ResolvedIdentity) -> Result<Agen/// The memory of `identity` (the default agent for the root identity).pub fn current_agent_memory(config: &Config,- identity: &super::scope::MemoryIdentity,+ identity: &super::tinymemory_tools::layout::identity::Identity,) -> Result<(AgentMemory, ResolvedIdentity)> {- let identity = identity.resolve(config);+ let identity = identity.resolve(&crate::memory::scope::identity_pins(config));let memory = agent_memory(config, &identity)?;Ok((memory, identity))}@@ -94,10 +94,10 @@ pub fn current_agent_memory(/// itself when none is named.pub fn named_agent_memory(config: &Config,- identity: &super::scope::MemoryIdentity,+ identity: &super::tinymemory_tools::layout::identity::Identity,agent_id: Option<&str>,) -> Result<(AgentMemory, ResolvedIdentity)> {- let mut identity = identity.resolve(config);+ let mut identity = identity.resolve(&crate::memory::scope::identity_pins(config));if let Some(agent_id) = agent_id.map(str::trim).filter(|id| !id.is_empty()) {identity.agent_id = agent_id.to_string();}diff --git a/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs b/crates/openhuman-core/src/memory/lifecycle/mod_tests.rsindex 274b191e3c..ee8449f713 100644--- a/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs@@ -1,6 +1,6 @@use super::*;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in};#[test]@@ -41,7 +41,7 @@ fn the_policy_mirrors_the_recall_config() {async fn agent_memory_needs_an_engine_and_follows_the_identity() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::team_member("acme", "writer").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::team_member("acme", "writer").resolve(&crate::memory::scope::identity_pins(&config));assert!(matches!(agent_memory(&config, &identity),Err(Error::Off(_))@@ -52,10 +52,10 @@ async fn agent_memory_needs_an_engine_and_follows_the_identity() {assert_eq!(memory.agent_id(), "writer");assert_eq!(memory.namespace().to_string(), "team:acme/agent:writer");- let (named, _) = named_agent_memory(&config, &MemoryIdentity::root(), Some("auditor")).unwrap();+ let (named, _) = named_agent_memory(&config, &tinymemory_tools::layout::identity::Identity::root(), Some("auditor")).unwrap();assert_eq!(named.namespace().to_string(), "agent:auditor");let (current, resolved) =- current_agent_memory(&config, &MemoryIdentity::root().child("planner")).unwrap();+ current_agent_memory(&config, &tinymemory_tools::layout::identity::Identity::root().child("planner")).unwrap();assert_eq!(current.agent_id(), "planner");assert_eq!(resolved.agent_id, "planner");}diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch.rsindex 218614962c..c72ab9560d 100644--- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs@@ -12,7 +12,7 @@ use tinymemory_tools::prefetch::{Limits, PrefetchRuntime, Prefetcher, WorkerPooluse crate::config::Config;use crate::core::runtime::{slot_for, DispatchCtx};-use crate::memory::scope::ResolvedIdentity;+use tinymemory_tools::layout::identity::ResolvedIdentity;use super::hooks::{self, TurnPack};diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rsindex e64c2c467d..c129592002 100644--- a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs@@ -1,6 +1,6 @@use super::*;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::config_in;const MAX_PENDING: usize = 16;@@ -33,7 +33,7 @@ async fn held_refresh_returns_immediately_and_later_turn_reads_completed_contextlet _guard = TEST_LOCK.lock().await;let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());let release = Arc::new(tokio::sync::Notify::new());@@ -60,7 +60,7 @@ async fn identity_config_thread_workspace_and_context_are_isolated() {let _guard = TEST_LOCK.lock().await;let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());enqueue(@@ -93,7 +93,7 @@ async fn identity_config_thread_workspace_and_context_are_isolated() {fn prefetch_key_tracks_memory_config_without_hashing_unrelated_config() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let mut memory_changed = config.clone();@@ -118,7 +118,7 @@ async fn invalidation_rejects_late_results_and_preserves_bounded_pending_logs()let _guard = TEST_LOCK.lock().await;let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());CACHES.lock().unwrap().push(Arc::downgrade(&cache));@@ -167,7 +167,7 @@ async fn expiration_failure_and_oversized_packs_are_not_reused() {let _guard = TEST_LOCK.lock().await;let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());enqueue(@@ -194,7 +194,7 @@ async fn credential_invalidation_removes_ready_and_rejects_late_inflight_resultslet _guard = TEST_LOCK.lock().await;let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());CACHES.lock().unwrap().push(Arc::downgrade(&cache));@@ -326,7 +326,7 @@ async fn slow_engine_results_survive_the_manual_pre_turn_cutoff() {.await.unwrap();crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let input = |index| {("slow".to_string(),@@ -401,7 +401,7 @@ async fn queued_work_keeps_the_callers_core_context() {Some(config.workspace_dir.clone()),);crate::core::runtime::CoreContext::scope(ctx.clone(), async {- let identity = MemoryIdentity::agent("scoped-agent").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("scoped-agent").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = cache(&crate::core::runtime::DispatchCtx::ambient());let expected = ctx.clone();@@ -429,7 +429,7 @@ fn runtime_shutdown_releases_worker_and_pending_work() {let _guard = TEST_LOCK.blocking_lock();let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);- let identity = MemoryIdentity::agent("a").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("a").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "t", false);let cache = Arc::new(Cache::default());let runtime = tokio::runtime::Builder::new_current_thread()@@ -468,7 +468,7 @@ async fn an_erase_retires_queued_automatic_work_and_allows_later_work() {use std::sync::atomic::{AtomicUsize, Ordering};let tmp = tempfile::tempdir().unwrap();let config = crate::memory::test_fixtures::config_in(&tmp);- let identity = crate::memory::scope::MemoryIdentity::agent("erase-prefetch").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("erase-prefetch").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "erase-prefetch", false);let cache = Arc::new(Cache::default());let earlier = Arc::new(AtomicUsize::new(0));@@ -519,7 +519,7 @@ async fn an_erase_retires_queued_automatic_work_and_allows_later_work() {async fn erase_waits_for_current_automatic_work_before_returning_its_barrier() {let tmp = tempfile::tempdir().unwrap();let config = crate::memory::test_fixtures::config_in(&tmp);- let identity = crate::memory::scope::MemoryIdentity::agent("erase-active").resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::agent("erase-active").resolve(&crate::memory::scope::identity_pins(&config));let key = Key::new(&config, &identity, "erase-active", false);let cache = Arc::new(Cache::default());let started = Arc::new(tokio::sync::Notify::new());diff --git a/crates/openhuman-core/src/memory/lifecycle/views.rs b/crates/openhuman-core/src/memory/lifecycle/views.rsindex 574ea26e0b..eac65af2e8 100644--- a/crates/openhuman-core/src/memory/lifecycle/views.rs+++ b/crates/openhuman-core/src/memory/lifecycle/views.rs@@ -7,7 +7,8 @@ use tinymemory_tools::{ContextPack, SessionStart};use crate::config::schema::MemoryRecallConfig;use crate::config::Config;-use crate::memory::scope::{self, MemoryIdentity};+use crate::memory::scope;+use tinymemory_tools::layout::identity::Identity;use tinymemory_api::{Error, Result};use super::jobs;@@ -31,7 +32,7 @@ pub struct PolicyView {/// `memory_policy_get`.#[must_use]pub fn policy_view(config: &Config) -> PolicyView {- let resolved = scope::MemoryIdentity::root().resolve(config);+ let resolved = tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(config));PolicyView {log_conversations: config.memory.conversations.enabled,recall: config.memory.recall.clone(),@@ -206,7 +207,7 @@ pub struct PackPreviewView {/// (without one) would be given. Reads only; nothing is logged.pub async fn pack_preview(config: &Config,- identity: &MemoryIdentity,+ identity: &tinymemory_tools::layout::identity::Identity,params: PackPreviewParams,) -> Result<PackPreviewView> {let (memory, identity) =@@ -252,7 +253,7 @@ pub struct AgentsView {}/// `memory_agents_list`: the agents with conversations under the root.-pub async fn agents_list(config: &Config, identity: &MemoryIdentity) -> Result<AgentsView> {+pub async fn agents_list(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> Result<AgentsView> {let (memory, identity) = super::current_agent_memory(config, identity)?;let page = memory.engine()diff --git a/crates/openhuman-core/src/memory/lifecycle/views_tests.rs b/crates/openhuman-core/src/memory/lifecycle/views_tests.rsindex 1202682ca9..9df266e47f 100644--- a/crates/openhuman-core/src/memory/lifecycle/views_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/views_tests.rs@@ -4,7 +4,7 @@ use chrono::Utc;use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem};use crate::memory::lifecycle::hooks::pre_turn_work;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in};#[test]@@ -121,7 +121,7 @@ async fn the_preview_reads_without_logging_and_agents_are_listed() {)).await.unwrap();- let writer = scope::MemoryIdentity::agent("writer").resolve(&config);+ let writer = tinymemory_tools::layout::identity::Identity::agent("writer").resolve(&crate::memory::scope::identity_pins(&config));pre_turn_work(&crate::core::runtime::DispatchCtx::ambient(),&config,@@ -138,7 +138,7 @@ async fn the_preview_reads_without_logging_and_agents_are_listed() {let turn = pack_preview(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),PackPreviewParams {query: Some("when do invoices go out?".into()),agent_id: Some("writer".into()),@@ -153,14 +153,14 @@ async fn the_preview_reads_without_logging_and_agents_are_listed() {let session = pack_preview(&config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),PackPreviewParams::default(),).await.unwrap();assert_eq!(session.mode, "session");- let agents = agents_list(&config, &MemoryIdentity::root()).await.unwrap();+ let agents = agents_list(&config, &tinymemory_tools::layout::identity::Identity::root()).await.unwrap();assert_eq!(agents.agents,[AgentCount {diff --git a/crates/openhuman-core/src/memory/local_root.rs b/crates/openhuman-core/src/memory/local_root.rsindex f43725e0db..906f751234 100644--- a/crates/openhuman-core/src/memory/local_root.rs+++ b/crates/openhuman-core/src/memory/local_root.rs@@ -137,7 +137,7 @@ pub fn legacy_root(user_id: &str) -> String {/// layout migration (which copies into the user root) has started or/// finished.fn has_memory_under_legacy_root(config: &Config) -> bool {- super::scope::layout_is_v3(config)+ super::config.memory.layout == crate::config::MemoryLayoutMode::V3|| super::layout_migration::state::path(&config.workspace_dir).exists()}diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rsindex ee816ebb5e..6a4a55ec1c 100644--- a/crates/openhuman-core/src/memory/ops.rs+++ b/crates/openhuman-core/src/memory/ops.rs@@ -9,9 +9,10 @@use chrono::Utc;use tinymemory_api::{EraseRequest, FetchRequest, ForgetTarget, ItemId, LearningKind, ListRequest, MemoryMeta,- MetaFilter, RecallMode, RecallRequest, StoreItem, StoreReceipt, ThreadWindow, TimeHint,- WriteOptions,+ MetaFilter, Namespace, Reach, RecallMode, RecallRequest, StoreItem, StoreReceipt,+ ThreadWindow, TimeHint, WriteOptions,};+use tinymemory_tools::confine::{Confinement, Policy};use crate::config::Config;@@ -25,6 +26,34 @@ use super::types::{};use tinymemory_api::{Error, Result};+/// Apply the SaaS tenant boundary to a host memory operation. The namespace+/// mechanics live in TinyMemory; this adapter only selects the authenticated+/// profile root and preserves the existing fail-closed error.+pub(crate) fn saas_confinement(config: &Config, policy: Policy) -> Result<Option<Confinement>> {+ if !crate::core::runtime::is_saas() {+ return Ok(None);+ }+ let root = config+ .memory+ .root+ .as_deref()+ .map(str::trim)+ .unwrap_or("")+ .parse::<Namespace>();+ match root {+ Ok(root) if root != Namespace::ROOT => Ok(Some(Confinement {+ allowed: Reach::subtree(root),+ policy,+ })),+ Ok(_) | Err(_) => {+ tracing::error!("[memory:scope] no valid confinement root in SaaS mode");+ Err(Error::InvalidRequest(+ "memory is unavailable: this agent has no valid memory root".into(),+ ))+ }+ }+}+/// Default confidence of a learning stored without one.pub const DEFAULT_LEARNING_CONFIDENCE: f32 = 0.8;@@ -336,8 +365,8 @@ pub async fn learn_with(let mut item = learning_item(params, host_meta)?;// The same confinement as `store_item`: a SaaS user's learning lands in// their own tree whatever namespace it names.- if let Some(root) = super::user_scope::confinement(config)? {- super::user_scope::clamp_item(&mut item, &root);+ if let Some(confinement) = saas_confinement(config, Policy::Clamp)? {+ confinement.item(&mut item)?;}let bound = bound(config)?;let receipt = bound.engine.store_with(item, options).await?;@@ -358,8 +387,8 @@ pub async fn store_item_with(mut item: StoreItem,options: WriteOptions,) -> Result<StoreReceipt> {- if let Some(root) = super::user_scope::confinement(config)? {- super::user_scope::clamp_item(&mut item, &root);+ if let Some(confinement) = saas_confinement(config, Policy::Clamp)? {+ confinement.item(&mut item)?;}let bound = bound(config)?;let receipt = bound.engine.store_with(item, options).await?;@@ -381,12 +410,12 @@ pub async fn forget(config: &Config, params: ForgetParams) -> Result<ForgetView>("forget needs at least one id").into(),));}- let bound = bound(config)?;// A SaaS user forgets only what lies in their own tree.- let reach = match super::user_scope::confinement(config)? {- Some(root) => Some(super::user_scope::clamp_reach(params.reach, &root)),+ let reach = match saas_confinement(config, Policy::Clamp)? {+ Some(confinement) => Some(confinement.reach(params.reach)?),None => params.reach,};+ let bound = bound(config)?;let report = match reach {// With a reach the engine forgets by id inside it: `forget_within`// never looks beyond the reach for an id, where `ForgetTarget::Ids`@@ -476,7 +505,6 @@ async fn within_reach(/// `memory_items_list`.pub async fn items_list(config: &Config, params: ItemsListParams) -> Result<ItemsListView> {- let bound = bound(config)?;let request = ListRequest {filter: confine_filter(config,@@ -486,6 +514,7 @@ pub async fn items_list(config: &Config, params: ItemsListParams) -> Result<Itemcursor: params.cursor,};request.validate()?;+ let bound = bound(config)?;let page = if params.preview {bound.engine.list_preview(request).await?} else {@@ -497,11 +526,10 @@ pub async fn items_list(config: &Config, params: ItemsListParams) -> Result<Item})}-/// `filter`, confined to the SaaS user's tree when `config` has one-/// ([`super::user_scope`]).+/// `filter`, confined to the SaaS user's tree when the process is SaaS.pub(crate) fn confine_filter(config: &Config, filter: MetaFilter) -> Result<MetaFilter> {- Ok(match super::user_scope::confinement(config)? {- Some(root) => super::user_scope::clamp_filter(filter, &root),+ Ok(match saas_confinement(config, Policy::Clamp)? {+ Some(confinement) => confinement.filter(Some(filter))?,None => filter,})}diff --git a/crates/openhuman-core/src/memory/ops_tests.rs b/crates/openhuman-core/src/memory/ops_tests.rsindex 23fd0e9cc4..1320ea9e6b 100644--- a/crates/openhuman-core/src/memory/ops_tests.rs+++ b/crates/openhuman-core/src/memory/ops_tests.rs@@ -483,7 +483,7 @@ async fn erasing_memory_cancels_queued_learning_so_restart_cannot_restore_it() {let engine = bind_reference(&config);let facts = crate::memory::tools::CallFacts::of(&config,- &crate::memory::scope::MemoryIdentity::agent("orchestrator"),+ &tinymemory_tools::layout::identity::Identity::agent("orchestrator"),);let queued = crate::memory::tool_writes::enqueue(&config,diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rsindex e8cb56b3a0..3c16b4d02f 100644--- a/crates/openhuman-core/src/memory/schemas/handlers.rs+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs@@ -7,20 +7,30 @@ use crate::config::Config;use crate::core::all::ControllerFuture;use crate::core::runtime::DispatchCtx;use crate::core::{Outcome, StructuredRpcError};-use crate::memory::explore::{ExploreParams, ItemsGetParams};+use crate::memory::explore::{self, ExploreParams, ItemsGetParams};use crate::memory::lifecycle::views::{self, JobsRunParams, PackPreviewParams, PolicySetParams};-use crate::memory::scope::MemoryIdentity;+use crate::memory::scope;use crate::memory::types::{EmptyParams, EngineSetParams, EraseAllParams, FetchParams, ForgetParams, ImportStartParams,ImportStateView, ItemsListParams, LearnParams, RecallParams, SourceAddedView,SourceRemovedView, SourcesAddParams, SourcesListView, SourcesRemoveParams, SourcesSyncParams,SourcesSyncView,};-use crate::memory::{backfill, brain, confine, engine, import, layout_migration, ops, sources};+use crate::memory::{backfill, brain, engine, import, layout_migration, ops, sources};use serde::de::DeserializeOwned;use serde::Serialize;use serde_json::{json, Map, Value};-use tinymemory_api::{Error, Result};+use tinymemory_api::{Error, Reach, Result};+use tinymemory_tools::confine::{Confinement, Policy};+use tinymemory_tools::layout::identity::Identity;++fn rpc_confinement(config: &Config) -> Confinement {+ let identity = Identity::root().resolve(&scope::identity_pins(config));+ Confinement {+ allowed: Reach::subtree(identity.root().clone()),+ policy: Policy::Refuse,+ }+}/// The operation run after the common request parsing and config load.trait RpcOperation<P, R>: Send + 'static {@@ -105,26 +115,34 @@ pub(super) fn engine_set(ctx: DispatchCtx, params: Map<String, Value>) -> Contro}pub(super) fn recall(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<RecallParams, _>(ctx, params, |_, config, params| async move {- confine::recall(&config, &MemoryIdentity::root(), params).await+ rpc::<RecallParams, _>(ctx, params, |_, config, mut params| async move {+ params.filter = Some(rpc_confinement(&config).filter(params.filter)?);+ ops::recall(&config, params).await})}pub(super) fn fetch(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<FetchParams, _>(ctx, params, |_, config, params| async move {- confine::fetch(&config, &MemoryIdentity::root(), params).await+ rpc::<FetchParams, _>(ctx, params, |_, config, mut params| async move {+ params.filter = Some(rpc_confinement(&config).filter(params.filter)?);+ ops::fetch(&config, params).await})}pub(super) fn learn(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<LearnParams, _>(ctx, params, |_, config, params| async move {- confine::learn(&config, &MemoryIdentity::root(), params).await+ rpc::<LearnParams, _>(ctx, params, |_, config, mut params| async move {+ let identity = Identity::root().resolve(&scope::identity_pins(&config));+ params.meta = Some(+ rpc_confinement(&config)+ .learn_meta(params.meta, identity.layout.learnings())?,+ );+ ops::learn(&config, params, None).await})}pub(super) fn forget(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<ForgetParams, _>(ctx, params, |_, config, params| async move {- confine::forget(&config, &MemoryIdentity::root(), params).await+ rpc::<ForgetParams, _>(ctx, params, |_, config, mut params| async move {+ params.reach = Some(rpc_confinement(&config).reach(params.reach)?);+ ops::forget(&config, params).await})}@@ -135,20 +153,27 @@ pub(super) fn erase_all(ctx: DispatchCtx, params: Map<String, Value>) -> Control}pub(super) fn items_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<ItemsListParams, _>(ctx, params, |_, config, params| async move {- confine::items_list(&config, &MemoryIdentity::root(), params).await+ rpc::<ItemsListParams, _>(ctx, params, |_, config, mut params| async move {+ let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;+ params.filter = Some(rpc_confinement(&config).filter(Some(narrowed))?);+ params.path.clear();+ ops::items_list(&config, params).await})}pub(super) fn explore(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<ExploreParams, _>(ctx, params, |_, config, params| async move {- confine::explore(&config, &MemoryIdentity::root(), params).await+ rpc::<ExploreParams, _>(ctx, params, |_, config, mut params| async move {+ let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;+ params.filter = Some(rpc_confinement(&config).filter(Some(narrowed))?);+ params.path.clear();+ explore::explore(&config, params).await})}pub(super) fn items_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- rpc::<ItemsGetParams, _>(ctx, params, |_, config, params| async move {- confine::items_get(&config, &MemoryIdentity::root(), params).await+ rpc::<ItemsGetParams, _>(ctx, params, |_, config, mut params| async move {+ params.reach = Some(rpc_confinement(&config).reach(params.reach)?);+ explore::items_get(&config, params).await})}@@ -168,13 +193,13 @@ pub(super) fn policy_set(ctx: DispatchCtx, params: Map<String, Value>) -> Contropub(super) fn pack_preview(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<PackPreviewParams, _>(ctx, params, |_, config, params| async move {- views::pack_preview(&config, &MemoryIdentity::root(), params).await+ views::pack_preview(&config, &Identity::root(), params).await})}pub(super) fn agents_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<EmptyParams, _>(ctx, params, |_, config, _| async move {- views::agents_list(&config, &MemoryIdentity::root()).await+ views::agents_list(&config, &Identity::root()).await})}@@ -198,25 +223,25 @@ pub(super) fn conversations_backfill_start(pub(super) fn brain_sources(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<EmptyParams, _>(ctx, params, |_, config, _| async move {- brain::sources(&config, &MemoryIdentity::root()).await+ brain::sources(&config, &Identity::root()).await})}pub(super) fn brain_search(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<brain::BrainSearchParams, _>(ctx, params, |_, config, params| async move {- brain::search(&config, &MemoryIdentity::root(), params).await+ brain::search(&config, &Identity::root(), params).await})}pub(super) fn brain_ingest(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<brain::BrainIngestParams, _>(ctx, params, |_, config, params| async move {- brain::ingest(&config, &MemoryIdentity::root(), params).await+ brain::ingest(&config, &Identity::root(), params).await})}pub(super) fn brain_forget(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {rpc::<brain::BrainForgetParams, _>(ctx, params, |_, config, params| async move {- brain::forget(&config, &MemoryIdentity::root(), params).await+ brain::forget(&config, &Identity::root(), params).await})}diff --git a/crates/openhuman-core/src/memory/schemas_tests.rs b/crates/openhuman-core/src/memory/schemas_tests.rsindex 0b38a2cf31..c4f6c7cec5 100644--- a/crates/openhuman-core/src/memory/schemas_tests.rs+++ b/crates/openhuman-core/src/memory/schemas_tests.rs@@ -452,7 +452,7 @@ async fn rpc_learn_invalidates_a_cached_prefetch_pack() {let ctx = CoreContext::for_test_with_config(DomainSet::full(), config.clone());let dispatch = DispatchCtx::new(ctx.clone());- let identity = crate::memory::scope::MemoryIdentity::root().resolve(&config);+ let identity = tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(&config));let thread = "rpc-learn-invalidates-prefetch";let input = || {(diff --git a/crates/openhuman-core/src/memory/scope.rs b/crates/openhuman-core/src/memory/scope.rsindex 7dd2fff84c..0fbd61f82a 100644--- a/crates/openhuman-core/src/memory/scope.rs+++ b/crates/openhuman-core/src/memory/scope.rs@@ -1,198 +1,42 @@-//! Whose memory a turn reads and writes.-//!-//! Memory follows TinyMemory's standard layout (`tinymemory_tools::MemoryLayout`):-//! one tree per tenant, below a root —-//!-//! ```text-//! <root> shared learnings; holistic recall reads it all-//! ├── source:<kind> the brain: synced documents, no agent id-//! └── agent:<memory agent> one agent's conversations, a turn per item-//! ```-//!-//! A [`MemoryIdentity`] is who is acting: an agent definition and, for a team-//! member, its team. It is always explicit: a turn's run context carries its-//! own (`OpenHumanRunContext::memory_identity`, a sub-agent's derived with-//! [`MemoryIdentity::child`]), work the host does on its own behalf passes-//! [`MemoryIdentity::root`], and nothing reads it from the running task.-//! Memory resolves it against the config of whoever reads or writes-//! ([`MemoryIdentity::resolve`]) into a [`ResolvedIdentity`]: the layout root-//! and the memory agent id.-//!-//! Resolution, first match wins:-//!-//! | | memory agent id | layout root |-//! | --- | --- | --- |-//! | 1. host binding | `[memory] agent_id` | `[memory] root` |-//! | 2. definition pin | `[memory.agents.<definition>] agent_id` | `[memory.agents.<definition>] root` |-//! | 3. team member | the definition id | `team:<team>` |-//! | 4. default | the definition id, else [`DEFAULT_AGENT_ID`] | the default root |-//!-//! The host binding is how a coordinating host (OpenCompany, an embedder via-//! `openhuman_embed::AgentSpec::memory`) gives each OpenHuman agent it runs a-//! memory of its own: it derives a per-agent config with those two keys set.-//! Everything that agent runs — sub-agents included — then acts as that one-//! memory agent.-//!-//! The identity is never taken from model arguments.-//!-//! Under layout v3 (`[memory] layout = "v3"`) the engine keeps all of this-//! below the person's own scope root ([`user_root`]), and every agent's-//! chats share one node ([`chat_node`], `ws:main`), each turn carrying its-//! agent id. [`switch_to_v3`] turns it on once the person's memory moved.+//! Adapt OpenHuman's memory configuration to TinyMemory's identity pins, and+//! keep the host-owned account-root migration hooks.-use tinymemory_api::{Namespace, Segment, SegmentKind};-use tinymemory_tools::MemoryLayout;+use std::collections::HashMap;-use crate::config::{Config, MemoryLayoutMode};use tinymemory_api::{Error, Result};+use tinymemory_tools::layout::identity::{self, AgentPin, IdentityPins};-/// The memory agent id of work no agent is running (RPC, sync jobs, the UI).-pub const DEFAULT_AGENT_ID: &str = "assistant";--/// Who is acting on memory: the agent definition and its team. Scoping one-/// needs no config; what it maps to is resolved against the config of-/// whoever reads or writes ([`Self::resolve`]).-#[derive(Debug, Clone, Default, PartialEq, Eq)]-pub struct MemoryIdentity {- /// The agent definition id; `None` outside any agent (RPC, sync jobs).- pub agent_id: Option<String>,- /// The team the agent works in.- pub team: Option<String>,-}--/// An identity resolved against a config: where its memory lives.-#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub struct ResolvedIdentity {- /// The layout below the identity's root.- pub layout: MemoryLayout,- /// The memory agent id its turns are logged under.- pub agent_id: String,- /// Whether its turns get a context pack.- pub recall: bool,-}--impl ResolvedIdentity {- /// The layout root.- #[must_use]- pub fn root(&self) -> &Namespace {- self.layout.root()- }-}--impl MemoryIdentity {- /// No agent: work the host does on its own behalf.- #[must_use]- pub fn root() -> Self {- Self::default()- }-- /// A top-level agent.- #[must_use]- pub fn agent(agent_id: &str) -> Self {- Self {- agent_id: non_blank(agent_id),- team: None,- }- }-- /// `agent_id` as a member of `team`.- #[must_use]- pub fn team_member(team: &str, agent_id: &str) -> Self {- Self {- agent_id: non_blank(agent_id),- team: non_blank(team),- }- }-- /// `agent_id` run by this agent: a sub-agent, in the same team.- #[must_use]- pub fn child(&self, agent_id: &str) -> Self {- Self {- agent_id: non_blank(agent_id),- team: self.team.clone(),- }- }-- /// Where this identity's memory lives under `config`. See the module- /// docs for the resolution order.- #[must_use]- pub fn resolve(&self, config: &Config) -> ResolvedIdentity {- let memory = &config.memory;- let pinned = self- .agent_id- .as_deref()- .and_then(|definition| memory.agents.get(definition));- let agent_id = non_blank_opt(memory.agent_id.as_deref())- .or_else(|| non_blank_opt(pinned.and_then(|pin| pin.agent_id.as_deref())))- .or_else(|| self.agent_id.clone())- .unwrap_or_else(|| DEFAULT_AGENT_ID.to_string());- let root = parse_root(memory.root.as_deref())- .or_else(|| parse_root(pinned.and_then(|pin| pin.root.as_deref())))- .or_else(|| self.team.as_deref().map(team_root))- .unwrap_or(Namespace::ROOT);- let layout = MemoryLayout::new(root).unwrap_or_else(|error| {- tracing::warn!(%error, "[memory:scope] root too deep; using the default root");- MemoryLayout::default()- });- let layout = if layout_is_v3(config) {- pooled(layout)- } else {- layout- };- let recall = pinned- .and_then(|pin| pin.recall)- .unwrap_or(memory.recall.enabled);- ResolvedIdentity {- layout,- agent_id,- recall,- }- }-}--/// The pooled chat node every agent logs to under layout v3: `ws:main`.-const CHAT_WORKSPACE: &str = "main";--/// `layout` with every agent's conversations pooled at its [`chat_node`].-fn pooled(layout: MemoryLayout) -> MemoryLayout {- let node = Namespace::ROOT- .child(Segment::sanitized(SegmentKind::Workspace, CHAT_WORKSPACE))- .unwrap_or(Namespace::ROOT);- match layout.clone().with_pooled_conversations(&node) {- Ok(pooled) => pooled,- Err(error) => {- tracing::warn!(%error, "[memory:scope] chats not pooled; root too deep");- layout- }- }-}--/// Where every agent's chats are under layout v3: `ws:main` below-/// `layout`'s root. Relative to the engine's scope root (`org:<id>`), which-/// is not a namespace segment.-#[must_use]-pub fn chat_node(layout: &MemoryLayout) -> Namespace {- layout- .root()- .child(Segment::sanitized(SegmentKind::Workspace, CHAT_WORKSPACE))- .unwrap_or_else(|_| layout.root().clone())-}+use crate::config::{Config, MemoryLayoutMode};-/// Whether `config` keeps memory in layout v3 (`[memory] layout = "v3"`).+/// Project the host's memory settings into TinyMemory's identity resolver.#[must_use]-pub fn layout_is_v3(config: &Config) -> bool {- config.memory.layout == MemoryLayoutMode::V3+pub fn identity_pins(config: &Config) -> IdentityPins {+ let memory = &config.memory;+ IdentityPins {+ agent_id: memory.agent_id.clone(),+ root: memory.root.clone(),+ agents: memory+ .agents+ .iter()+ .map(|(id, pin)| {+ (+ id.clone(),+ AgentPin {+ agent_id: pin.agent_id.clone(),+ root: pin.root.clone(),+ recall: pin.recall,+ },+ )+ })+ .collect::<HashMap<_, _>>(),+ recall: memory.recall.enabled,+ v3: memory.layout == MemoryLayoutMode::V3,+ }}-/// The engine scope root of the person `config` belongs to: `org:<id>`-/// for a TinyHumans account (its 24-hex id), `org:local-<install id>` for a-/// local session (a random id recorded in the workspace, or the older-/// hostname-derived id an existing install already keeps memory under; see-/// [`super::local_root`]), and `None` before anyone signs in. Read from-/// where the config lives (`<root>/users/<id>/config.toml`). One root per-/// person, with no `user:` segment below it: `user:` names the person's-/// actor ([`actor_of_root`]), which is also the retired root an existing-/// install's memory is still read from during the move.+/// The engine scope root of the person `config` belongs to: `org:<id>` for a+/// TinyHumans account, or the recorded local install root. Before sign-in,+/// there is no user root.#[must_use]pub fn user_root(config: &Config) -> Option<String> {let dir = config.config_path.parent()?;@@ -203,58 +47,18 @@ pub fn user_root(config: &Config) -> Option<String> {if id.is_empty() || id == crate::config::PRE_LOGIN_USER_ID {return None;}- account_root(id).or_else(|| {- super::local_root::resolve(config, id).map(|recorded| org_of_recorded(&recorded))+ identity::account_root(id).or_else(|| {+ super::local_root::resolve(config, id).map(|recorded| identity::org_of_recorded(&recorded))})}-/// `org:<id>` when `id` is a TinyHumans account id (24 hex digits).-fn account_root(id: &str) -> Option<String> {- let account = id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit());- account.then(|| format!("{ROOT_TYPE}:{}", id.to_ascii_lowercase()))-}--/// The scope type of a person's root.-const ROOT_TYPE: &str = "org";--/// A recorded local root (`user:local-<id>`, the form the record file keeps-/// so installs recorded before `org:` roots read back) as the person's-/// `org:local-<id>` root. The `user:local-<id>` it came from is exactly the-/// actor [`actor_of_root`] names, so memory an existing install keeps under-/// that root (the old hostname-derived one included) is the retired root-/// read during the move.-fn org_of_recorded(recorded: &str) -> String {- match recorded.strip_prefix("user:") {- Some(id) => format!("{ROOT_TYPE}:{id}"),- None => recorded.to_string(),- }-}--/// The actor that owns the person's root `root` (`org:<id>` → `user:<id>`).-/// It is also where layout v3 rooted that person before `org:` roots: the-/// retired root read during the move, and the account a legacy-tree claim-/// names.-#[must_use]-pub fn actor_of_root(root: &str) -> String {- match root- .strip_prefix(ROOT_TYPE)- .and_then(|rest| rest.strip_prefix(':'))- {- Some(id) => format!("user:{id}"),- None => root.to_string(),- }-}--/// Switches the memory of the person `config` belongs to to layout v3:-/// reloads that person's own config file (`config.config_path`) fresh, so-/// neither a long migration's stale copy nor a different account signed in-/// meanwhile is written, sets `[memory] layout = "v3"`, saves it and drops-/// the bound engines so the next binding uses the new layout. Called by the-/// layout migration once every scope has moved, never on its own.+/// Switch the memory of this person to layout v3 after its migration finishes.+/// The config is reloaded from its own path so a stale config or a different+/// signed-in account cannot receive the setting change.////// # Errors///-/// The config could not be loaded or saved.+/// Returns an engine error if the config cannot be loaded or saved.pub async fn switch_to_v3(config: &Config) -> Result<()> {let mut config = Config::load_from_config_path(&config.config_path, &config.workspace_dir).await@@ -269,55 +73,6 @@ pub async fn switch_to_v3(config: &Config) -> Result<()> {Ok(())}-/// The layout `team`'s members share.-fn team_root(team: &str) -> Namespace {- Namespace::ROOT- .child(Segment::sanitized(SegmentKind::Team, team))- .unwrap_or(Namespace::ROOT)-}--/// Checks that `root` names a usable layout root (`team:acme`,-/// `project:q4/team:ops`), as a host binding is set.-///-/// # Errors-///-/// Why it is not one.-pub fn validate_root(root: &str) -> std::result::Result<(), String> {- let root: Namespace = root- .trim()- .parse()- .map_err(|error: tinymemory_api::Error| error.to_string())?;- MemoryLayout::new(root)- .map(|_| ())- .map_err(|error| error.to_string())-}--/// A configured root; an invalid one is logged and ignored.-fn parse_root(raw: Option<&str>) -> Option<Namespace> {- let raw = raw?.trim();- if raw.is_empty() {- return None;- }- match raw.parse::<Namespace>() {- Ok(root) => Some(root),- Err(error) => {- tracing::warn!(root = raw, %error, "[memory:scope] ignoring an invalid configured root");- None- }- }-}--fn non_blank(value: &str) -> Option<String> {- non_blank_opt(Some(value))-}--fn non_blank_opt(value: Option<&str>) -> Option<String> {- value- .map(str::trim)- .filter(|value| !value.is_empty())- .map(str::to_string)-}-#[cfg(test)]#[path = "scope_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/memory/scope_tests.rs b/crates/openhuman-core/src/memory/scope_tests.rsindex f36eca1c53..299848afba 100644--- a/crates/openhuman-core/src/memory/scope_tests.rs+++ b/crates/openhuman-core/src/memory/scope_tests.rs@@ -102,15 +102,15 @@ fn upstream_v3_identity_pools_at_the_account_root_workspace() {#[test]fn by_default_an_agent_is_its_definition_under_the_default_root() {let config = Config::default();- let researcher = MemoryIdentity::agent("researcher").resolve(&config);+ let researcher = tinymemory_tools::layout::identity::Identity::agent("researcher").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(researcher.agent_id, "researcher");assert_eq!(researcher.root(), &Namespace::ROOT);assert!(researcher.recall);- let nobody = MemoryIdentity::root().resolve(&config);+ let nobody = tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(nobody.agent_id, DEFAULT_AGENT_ID);assert_eq!(- MemoryIdentity::agent(" ").resolve(&config).agent_id,+ tinymemory_tools::layout::identity::Identity::agent(" ").resolve(&crate::memory::scope::identity_pins(&config)).agent_id,DEFAULT_AGENT_ID);}@@ -118,15 +118,15 @@ fn by_default_an_agent_is_its_definition_under_the_default_root() {#[test]fn a_team_member_shares_its_teams_root() {let config = Config::default();- let writer = MemoryIdentity::team_member("acme", "writer").resolve(&config);+ let writer = tinymemory_tools::layout::identity::Identity::team_member("acme", "writer").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(writer.root(), &ns("team:acme"));assert_eq!(writer.agent_id, "writer");assert_eq!(writer.layout.conversations("writer").unwrap(),ns("team:acme/agent:writer"));- let child = MemoryIdentity::team_member("acme", "lead").child("scout");- assert_eq!(child.resolve(&config).root(), &ns("team:acme"));+ let child = tinymemory_tools::layout::identity::Identity::team_member("acme", "lead").child("scout");+ assert_eq!(child.resolve(&crate::memory::scope::identity_pins(&config)).root(), &ns("team:acme"));}#[test]@@ -147,12 +147,12 @@ fn a_definition_pin_beats_the_team_and_the_default() {..MemoryAgentConfig::default()},);- let analyst = MemoryIdentity::team_member("acme", "analyst").resolve(&config);+ let analyst = tinymemory_tools::layout::identity::Identity::team_member("acme", "analyst").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(analyst.agent_id, "q4-desk");assert_eq!(analyst.root(), &ns("project:q4"));assert!(!analyst.recall);assert_eq!(- MemoryIdentity::agent("broken").resolve(&config).root(),+ tinymemory_tools::layout::identity::Identity::agent("broken").resolve(&crate::memory::scope::identity_pins(&config)).root(),&Namespace::ROOT,"an invalid root falls back to the default");@@ -172,11 +172,11 @@ fn a_host_binding_beats_everything() {},);for identity in [- MemoryIdentity::agent("researcher"),- MemoryIdentity::team_member("acme", "writer"),- MemoryIdentity::root(),+ tinymemory_tools::layout::identity::Identity::agent("researcher"),+ tinymemory_tools::layout::identity::Identity::team_member("acme", "writer"),+ tinymemory_tools::layout::identity::Identity::root(),] {- let resolved = identity.resolve(&config);+ let resolved = identity.resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(resolved.agent_id, "employee-7");assert_eq!(resolved.root(), &ns("project:acme"));}@@ -184,14 +184,14 @@ fn a_host_binding_beats_everything() {#[test]fn a_child_stays_in_the_parents_team() {- let lead = MemoryIdentity::team_member("acme", "lead");+ let lead = tinymemory_tools::layout::identity::Identity::team_member("acme", "lead");assert_eq!(lead.child("lead").child("scout"),- MemoryIdentity::team_member("acme", "scout")+ tinymemory_tools::layout::identity::Identity::team_member("acme", "scout"));assert_eq!(- MemoryIdentity::root().child("solo"),- MemoryIdentity::agent("solo")+ tinymemory_tools::layout::identity::Identity::root().child("solo"),+ tinymemory_tools::layout::identity::Identity::agent("solo"));}@@ -268,7 +268,7 @@ fn the_user_root_is_read_from_where_the_config_lives() {#[test]fn layout_v3_pools_every_agents_chats_at_ws_main() {let mut config = Config::default();- let legacy = MemoryIdentity::agent("researcher").resolve(&config);+ let legacy = tinymemory_tools::layout::identity::Identity::agent("researcher").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(legacy.layout.conversations("researcher").unwrap(),ns("agent:researcher")@@ -277,8 +277,8 @@ fn layout_v3_pools_every_agents_chats_at_ws_main() {config.memory.layout = MemoryLayoutMode::V3;assert!(layout_is_v3(&config));- let researcher = MemoryIdentity::agent("researcher").resolve(&config);- let coder = MemoryIdentity::agent("coder").resolve(&config);+ let researcher = tinymemory_tools::layout::identity::Identity::agent("researcher").resolve(&crate::memory::scope::identity_pins(&config));+ let coder = tinymemory_tools::layout::identity::Identity::agent("coder").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(researcher.layout.conversations("researcher").unwrap(),ns("ws:main")@@ -288,7 +288,7 @@ fn layout_v3_pools_every_agents_chats_at_ws_main() {let history = researcher.layout.conversations_filter(Some("researcher"));assert_eq!(history.agent_id.as_deref(), Some("researcher"));- let team = MemoryIdentity::team_member("acme", "writer").resolve(&config);+ let team = tinymemory_tools::layout::identity::Identity::team_member("acme", "writer").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(chat_node(&team.layout), ns("team:acme/ws:main"));}diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex ec6cbdcb72..3c8847941f 100644--- a/crates/openhuman-core/src/memory/sources/mod.rs+++ b/crates/openhuman-core/src/memory/sources/mod.rs@@ -195,8 +195,8 @@ pub fn layout_of_source(source: &MemorySourceConfig,) -> tinymemory_tools::MemoryLayout {let default = || {- crate::memory::scope::MemoryIdentity::root()- .resolve(config)+ tinymemory_tools::layout::identity::Identity::root()+ .resolve(&crate::memory::scope::identity_pins(config)).layout};let Some(raw) = source@@ -226,8 +226,8 @@ pub fn layout_of(config: &Config, source_id: &str) -> tinymemory_tools::MemoryLa.find(|source| source.id == source_id).map_or_else(|| {- crate::memory::scope::MemoryIdentity::root()- .resolve(config)+ tinymemory_tools::layout::identity::Identity::root()+ .resolve(&crate::memory::scope::identity_pins(config)).layout},|source| layout_of_source(config, source),diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rsindex f280ccd4ce..808c6c37dc 100644--- a/crates/openhuman-core/src/memory/tool_writes.rs+++ b/crates/openhuman-core/src/memory/tool_writes.rs@@ -20,6 +20,7 @@ use async_trait::async_trait;use serde::Deserialize;use sha2::{Digest, Sha256};use tinymemory_api::{Namespace, StoreItem, WriteOptions};+use tinymemory_tools::confine::Policy;use tinymemory_tools::list_store::{ListStore, StoreError};use tinymemory_tools::pending::{Ack, Binding, Entry, Epoch, FenceToken, Limits, PendingError, PendingWrites, WriteExecutor,@@ -107,7 +108,7 @@ fn binding_of(root: Option<String>, layout_v3: bool) -> Binding {fn binding(config: &Config) -> Binding {binding_of(super::scope::user_root(config),- super::scope::layout_is_v3(config),+ super::config.memory.layout == crate::config::MemoryLayoutMode::V3,)}@@ -136,7 +137,7 @@ fn owner_prefix(config: &Config) -> String {fn queue_path(config: &Config, root: &Namespace) -> PathBuf {let partition = serde_json::to_vec(&(&config.memory.root,- super::scope::layout_is_v3(config),+ super::config.memory.layout == crate::config::MemoryLayoutMode::V3,root,)).expect("partition fields serialize");@@ -161,9 +162,9 @@ pub(super) fn enqueue(if super::engine::switched_off(config) {return Err(Error::Off("memory is disabled".into()));}- let confinement = super::user_scope::confinement(config)?;+ let confinement = super::ops::saas_confinement(config, Policy::Clamp)?;let reach = match confinement {- Some(ref root) => super::user_scope::clamp_reach(Some(facts.reach.clone()), root),+ Some(ref confinement) => confinement.reach(Some(facts.reach.clone()))?,None => facts.reach.clone(),};let scope_root = reach.at.clone();@@ -174,10 +175,10 @@ pub(super) fn enqueue(.map_err(|_| Error::InvalidRequest("invalid learning arguments".into()))?;params.meta = None;let mut item = super::ops::learning_item(params, Some(facts.learn_meta()))?;- if let Some(root) = confinement {- super::user_scope::clamp_item(&mut item, &root);+ if let Some(ref confinement) = confinement {+ confinement.item(&mut item)?;}- if !super::user_scope::within(&item.meta().namespace, &reach.at) || reach.inherit {+ if !reach.admits(&item.meta().namespace) || reach.inherit {return Err(Error::InvalidRequest(("learning namespace is outside the trusted reach").into(),));@@ -557,7 +558,7 @@ fn schedule_partition(ctx: &crate::core::runtime::DispatchCtx, config: Arc<Confipub(crate) async fn drain(config: &Config) -> usize {let file = queue_path(config,- super::scope::MemoryIdentity::root().resolve(config).root(),+ super::tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(config)).root(),);let owner = owner_state(config);let _owner = owner.barrier.read().await;diff --git a/crates/openhuman-core/src/memory/tool_writes_tests.rs b/crates/openhuman-core/src/memory/tool_writes_tests.rsindex 1f08abaf91..1f79b0c827 100644--- a/crates/openhuman-core/src/memory/tool_writes_tests.rs+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs@@ -1,12 +1,12 @@use super::*;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in, stored, RefusingEngine};use serde_json::json;use tinymemory_api::Reach;use tinymemory_api::{MetaFilter, Namespace};fn facts(config: &Config) -> CallFacts {- CallFacts::of(config, &MemoryIdentity::agent("outbox-agent"))+ CallFacts::of(config, &tinymemory_tools::layout::identity::Identity::agent("outbox-agent"))}#[test]@@ -375,7 +375,7 @@ async fn model_supplied_forget_reach_cannot_remove_another_identitys_item() {let tmp = tempfile::tempdir().unwrap();let config = config_in(&tmp);let engine = bind_reference(&config);- let other_facts = CallFacts::of(&config, &MemoryIdentity::agent("different-agent"));+ let other_facts = CallFacts::of(&config, &tinymemory_tools::layout::identity::Identity::agent("different-agent"));let item = StoreItem::learning("Other identity's learning",LearningKind::Fact,diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rsindex 39e7ab8bc5..54c6c0189a 100644--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@ -98,8 +98,8 @@ impl CallFacts {crate::agent::tinyagents::host::run_context::memory_identity_for_tool(context).unwrap_or_else(|| {crate::agent::tinyagents::host::run_context::parent_agent_id_for_tool(context)- .map_or_else(super::scope::MemoryIdentity::root, |parent_agent_id| {- super::scope::MemoryIdentity::agent(&parent_agent_id)+ .map_or_else(super::tinymemory_tools::layout::identity::Identity::root, |parent_agent_id| {+ super::tinymemory_tools::layout::identity::Identity::agent(&parent_agent_id)})});Self {@@ -119,8 +119,8 @@ impl CallFacts {/// The facts of a call made by `identity` under `config`, with no run/// context.#[must_use]- pub fn of(config: &Config, identity: &super::scope::MemoryIdentity) -> Self {- let resolved = identity.resolve(config);+ pub fn of(config: &Config, identity: &super::tinymemory_tools::layout::identity::Identity) -> Self {+ let resolved = identity.resolve(&crate::memory::scope::identity_pins(config));Self {agent_id: Some(resolved.agent_id.clone()),namespace: resolved.layout.learnings().clone(),diff --git a/crates/openhuman-core/src/memory/tools_agent_tests.rs b/crates/openhuman-core/src/memory/tools_agent_tests.rsindex c77d247214..84956fcbf1 100644--- a/crates/openhuman-core/src/memory/tools_agent_tests.rs+++ b/crates/openhuman-core/src/memory/tools_agent_tests.rs@@ -2,7 +2,7 @@ use super::*;/// A tool context for a run that acts on memory as `identity`.fn tool_context_acting_as(- identity: crate::memory::scope::MemoryIdentity,+ identity: tinymemory_tools::layout::identity::Identity,) -> tinyagents_harness::tool::ToolExecutionContext {let mut host = crate::agent::tinyagents::host::OpenHumanRunContext::new();host.memory_identity = Some(identity);@@ -19,7 +19,7 @@ fn tool_context_acting_as(#[test]fn gather_acts_as_the_identity_the_run_carries() {let config = Config::default();- let context = tool_context_acting_as(crate::memory::scope::MemoryIdentity::team_member(+ let context = tool_context_acting_as(tinymemory_tools::layout::identity::Identity::team_member("acme", "scout",));let facts = CallFacts::gather(&config, Some(&context));diff --git a/crates/openhuman-core/src/memory/tools_read_tests.rs b/crates/openhuman-core/src/memory/tools_read_tests.rsindex e192b87666..c73c42071b 100644--- a/crates/openhuman-core/src/memory/tools_read_tests.rs+++ b/crates/openhuman-core/src/memory/tools_read_tests.rs@@ -2,7 +2,7 @@//! and fetch leave the calling thread out.use super::*;-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in};use tinymemory_api::MemoryEngine;@@ -10,7 +10,7 @@ fn facts() -> CallFacts {CallFacts {thread_id: Some("thread-tool-1".into()),agent_id: Some("orchestrator".into()),- ..CallFacts::of(&Config::default(), &MemoryIdentity::agent("orchestrator"))+ ..CallFacts::of(&Config::default(), &tinymemory_tools::layout::identity::Identity::agent("orchestrator"))}}diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rsindex 0b10253b29..62379a2808 100644--- a/crates/openhuman-core/src/memory/tools_tests.rs+++ b/crates/openhuman-core/src/memory/tools_tests.rs@@ -3,7 +3,7 @@ use super::*;fn ambient() -> DispatchCtx {DispatchCtx::ambient()}-use crate::memory::scope::MemoryIdentity;+use tinymemory_tools::layout::identity::Identity;use crate::memory::test_fixtures::{bind_reference, config_in, stored};use std::path::{Path, PathBuf};use tinymemory_api::{ItemKind, MetaFilter, Namespace};@@ -28,7 +28,7 @@ fn facts() -> CallFacts {thread_id: Some("thread-tool-1".into()),agent_id: Some("orchestrator".into()),tool_call_id: Some("call-9".into()),- ..CallFacts::of(&Config::default(), &MemoryIdentity::agent("orchestrator"))+ ..CallFacts::of(&Config::default(), &tinymemory_tools::layout::identity::Identity::agent("orchestrator"))}}@@ -36,7 +36,7 @@ fn facts() -> CallFacts {fn facts_of(agent_id: &str) -> CallFacts {CallFacts {thread_id: Some(format!("thread-{agent_id}")),- ..CallFacts::of(&Config::default(), &MemoryIdentity::agent(agent_id))+ ..CallFacts::of(&Config::default(), &tinymemory_tools::layout::identity::Identity::agent(agent_id))}}@@ -332,7 +332,7 @@ async fn learnings_are_shared_under_a_root_and_a_team_root_is_kept_apart() {let engine = bind_reference(&config);let member = || CallFacts {thread_id: Some("thread-team".into()),- ..CallFacts::of(&config, &MemoryIdentity::team_member("acme", "writer"))+ ..CallFacts::of(&config, &tinymemory_tools::layout::identity::Identity::team_member("acme", "writer"))};let learn = |facts: CallFacts, text: &'static str| {let config = config.clone();diff --git a/crates/openhuman-core/src/modules/documents/memory_converter_tests.rs b/crates/openhuman-core/src/modules/documents/memory_converter_tests.rsindex 05f814953a..865ba33241 100644--- a/crates/openhuman-core/src/modules/documents/memory_converter_tests.rs+++ b/crates/openhuman-core/src/modules/documents/memory_converter_tests.rs@@ -309,7 +309,7 @@ async fn brain_ingest_files_a_pdf_by_path() {let view = ingest(&config,- &crate::memory::scope::MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),BrainIngestParams {path: Some(path.display().to_string()),text: None,diff --git a/crates/openhuman-core/src/profiles/layout_tests.rs b/crates/openhuman-core/src/profiles/layout_tests.rsindex 029b9456a6..3dae6ddad4 100644--- a/crates/openhuman-core/src/profiles/layout_tests.rs+++ b/crates/openhuman-core/src/profiles/layout_tests.rs@@ -44,7 +44,7 @@ fn the_config_is_rooted_in_the_profile_and_bound_to_its_memory() {#[test]fn the_memory_root_is_a_valid_layout_root() {- crate::memory::scope::validate_root(&memory_root(&id())).unwrap();+ tinymemory_tools::layout::identity::validate_root(&memory_root(&id())).unwrap();}/// Under `users/<id>`, `memory::scope::user_root` reads an account id out of@@ -53,7 +53,8 @@ fn the_memory_root_is_a_valid_layout_root() {/// ignore `user:<id>`. The pin keeps a profile on the root it is forced to.#[test]fn a_profile_binds_its_user_root_never_an_org_root() {- use crate::memory::scope::{self, MemoryIdentity};+ use crate::memory::scope;+use tinymemory_tools::layout::identity::Identity;let id = ProfileId::for_user("65f1c0ffee0123456789abcd", ProfileIdMode::Raw).unwrap();assert_eq!(id.as_str(), "65f1c0ffee0123456789abcd");let layout = profile_layout(Path::new("/srv/oh"), &id);@@ -67,8 +68,8 @@ fn a_profile_binds_its_user_root_never_an_org_root() {// The pin: legacy layout, so `memory::engine::resolve` binds no org root// and every operation is confined to `user:<id>`.assert_eq!(config.memory.layout, MemoryLayoutMode::Legacy);- assert!(!scope::layout_is_v3(&config));- let bound = MemoryIdentity::root().resolve(&config);+ assert!(!config.memory.layout == crate::config::MemoryLayoutMode::V3);+ let bound = tinymemory_tools::layout::identity::Identity::root().resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(bound.root().to_string(), "user:65f1c0ffee0123456789abcd");assert_eq!(bound.agent_id, id.as_str());let confined = crate::memory::user_scope::confinement_in(true, &config)@@ -79,14 +80,14 @@ fn a_profile_binds_its_user_root_never_an_org_root() {#[test]fn the_memory_binding_wins_over_pins_and_teams() {- use crate::memory::scope::MemoryIdentity;+ use tinymemory_tools::layout::identity::Identity;let layout = profile_layout(Path::new("/srv/oh"), &id());let mut config = profile_config(&layout, &id());config.memory.agents.insert("planner".into(),toml::from_str("agent_id = \"other\"\nroot = \"team:shared\"").unwrap(),);- let resolved = MemoryIdentity::team_member("shared", "planner").resolve(&config);+ let resolved = tinymemory_tools::layout::identity::Identity::team_member("shared", "planner").resolve(&crate::memory::scope::identity_pins(&config));assert_eq!(resolved.agent_id, id().as_str());assert_eq!(resolved.root().to_string(), memory_root(&id()));}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex af5bef46ac..62f02e8f51 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -169,7 +169,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn));}if let Some(root) = binding.root_namespace() {- openhuman_core::memory::scope::validate_root(root)+ openhuman_core::memory::tinymemory_tools::layout::identity::validate_root(root).map_err(|reason| AgentError::Invalid(format!("memory root {root:?}: {reason}")))?;}log::debug!("[embed][agent] id={id} binds its memory agent_id={agent_id}");diff --git a/crates/openhuman-embed/src/memory.rs b/crates/openhuman-embed/src/memory.rsindex 57c8cbc0c8..50b0c0c383 100644--- a/crates/openhuman-embed/src/memory.rs+++ b/crates/openhuman-embed/src/memory.rs@@ -36,7 +36,7 @@use openhuman_core::config::Config;use openhuman_core::memory::engine::{self, Binding};-use openhuman_core::memory::scope::MemoryIdentity;+use openhuman_core::memory::tinymemory_tools::layout::identity::Identity;use openhuman_core::memory::{brain, explore, lifecycle, ops, types};use tinymemory_api::{ItemKind, MemoryMeta, MetaFilter, Namespace, Reach, StoreItem, StoreReceipt, WriteOptions,@@ -131,7 +131,7 @@ impl Memory {/// Binds `base` to the layout root `root` (`team:acme`).pub(crate) fn bind(mut base: Config, root: &str) -> Result<Self> {let root = root.trim();- openhuman_core::memory::scope::validate_root(root).map_err(Error::InvalidRequest)?;+ openhuman_core::memory::tinymemory_tools::layout::identity::validate_root(root).map_err(Error::InvalidRequest)?;let namespace: Namespace = root.parse().map_err(|error: tinymemory_api::Error| Error::InvalidRequest(error.to_string()))?;@@ -194,7 +194,7 @@ impl Memory {/// The agents with logged turns under the root, most first.pub async fn agents(&self) -> Result<AgentsView> {- lifecycle::views::agents_list(&self.config, &MemoryIdentity::root()).await+ lifecycle::views::agents_list(&self.config, &tinymemory_tools::layout::identity::Identity::root()).await}/// A page of items, newest first.@@ -378,7 +378,7 @@ impl Memory {/// The brain's sources under the root and their sizes.pub async fn brain_sources(&self) -> Result<BrainSourcesView> {- brain::sources(&self.config, &MemoryIdentity::root()).await+ brain::sources(&self.config, &tinymemory_tools::layout::identity::Identity::root()).await}/// Brain documents matching `query`, optionally of one source.@@ -390,7 +390,7 @@ impl Memory {) -> Result<BrainSearchView> {brain::search(&self.config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),brain::BrainSearchParams {query: query.into(),source,@@ -402,14 +402,14 @@ impl Memory {/// Files a document (a file on disk, or text) in the root's brain.pub async fn brain_ingest(&self, params: BrainIngestParams) -> Result<BrainIngestView> {- brain::ingest(&self.config, &MemoryIdentity::root(), params).await+ brain::ingest(&self.config, &tinymemory_tools::layout::identity::Identity::root(), params).await}/// Forgets every brain document of one source under the root.pub async fn brain_forget(&self, source: impl Into<String>) -> Result<BrainForgetView> {brain::forget(&self.config,- &MemoryIdentity::root(),+ &tinymemory_tools::layout::identity::Identity::root(),brain::BrainForgetParams {source: source.into(),},