Skip to content

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

Bind memory in layout v3 below the person's own root

M3gA-Mind4884f95b572f
diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs
index 79fba8ffa3..1afb278d20 100644
--- a/crates/openhuman-core/src/config/mod.rs
+++ b/crates/openhuman-core/src/config/mod.rs
@@ -49,9 +49,9 @@ pub use schema::{
HttpHeader, HttpRequestConfig, IMessageConfig, IntegrationToggle, IntegrationsConfig,
LarkConfig, LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, MatrixConfig,
McpAuthConfig, McpClientConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure,
- MemoryConfig, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, ObservabilityConfig,
- OrchestratorModelConfig, PrivacyConfig, PrivacyMode, ProxyConfig, ProxyScope,
- ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, RuntimePoolConfig,
+ MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig,
+ ObservabilityConfig, OrchestratorModelConfig, PrivacyConfig, PrivacyMode, ProxyConfig,
+ ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, RuntimePoolConfig,
RuntimePoolLangConfig, SandboxBackend, SandboxConfig, SchedulerConfig, SchedulerGateConfig,
SchedulerGateMode, SearchConfig, SearchEngineCredentials, SearchPresentation,
SearchProviderSettings, SearchRoute, SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig,
diff --git a/crates/openhuman-core/src/config/schema/memory.rs b/crates/openhuman-core/src/config/schema/memory.rs
index 134f20ad30..daa7caca08 100644
--- a/crates/openhuman-core/src/config/schema/memory.rs
+++ b/crates/openhuman-core/src/config/schema/memory.rs
@@ -105,6 +105,12 @@ pub struct MemoryConfig {
/// Unset is the default root.
#[serde(skip_serializing_if = "Option::is_none")]
pub root: Option<String>,
+ /// Where memory sits on the engine: `legacy` (the shared
+ /// `app:tinymemory` tree, the default) or `v3` (the signed-in person's
+ /// own `user:<id>` subtree, chats pooled at `ws:main`). Switched by the
+ /// layout migration once the person's memory has moved, never by hand.
+ #[serde(skip_serializing_if = "MemoryLayoutMode::is_legacy")]
+ pub layout: MemoryLayoutMode,
/// Turn logging.
pub conversations: MemoryConversationsConfig,
/// The per-turn context pack and the lifecycle's timings.
@@ -129,6 +135,26 @@ pub struct MemoryConfig {
pub agents: BTreeMap<String, MemoryAgentConfig>,
}
+/// `[memory] layout`: where memory sits on the engine.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum MemoryLayoutMode {
+ /// The shared `app:tinymemory` tree, as before layout v3.
+ #[default]
+ Legacy,
+ /// The person's own `user:<id>` subtree, every kind under a leaf of its
+ /// own, chats pooled at `ws:main`.
+ V3,
+}
+
+impl MemoryLayoutMode {
+ /// Whether this is the legacy layout (the default, so it is not written).
+ #[must_use]
+ pub fn is_legacy(&self) -> bool {
+ *self == Self::Legacy
+ }
+}
+
/// `[memory.agents.<definition>]`: one agent definition's memory.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
@@ -167,6 +193,7 @@ impl Default for MemoryConfig {
engines: BTreeMap::new(),
agent_id: None,
root: None,
+ layout: MemoryLayoutMode::Legacy,
conversations: MemoryConversationsConfig::default(),
recall: MemoryRecallConfig::default(),
sources: Vec::new(),
diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs
index b77790000c..ba91256a59 100644
--- a/crates/openhuman-core/src/config/schema/mod.rs
+++ b/crates/openhuman-core/src/config/schema/mod.rs
@@ -93,8 +93,8 @@ pub use identity_cost::{CostConfig, ModelPricing};
pub use local_ai::{LocalAiConfig, LocalAiUsage};
pub use memory::{
migrate_legacy_source, MemoryAgentConfig, MemoryConfig, MemoryConversationsConfig,
- MemoryEngineSettings, MemoryRecallConfig, MemorySourceConfig, MemorySourceKind,
- MEMORY_CORTEXDB_KEY_NAME,
+ MemoryEngineSettings, MemoryLayoutMode, MemoryRecallConfig, MemorySourceConfig,
+ MemorySourceKind, MEMORY_CORTEXDB_KEY_NAME,
};
pub use modules::{ModuleOverride, ModulesConfig};
pub use node::NodeConfig;
diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs
index e4c81646b1..e34c06249a 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -9,9 +9,15 @@
//! | `cortexdb` | `[memory.engines.cortexdb] endpoint`, else CortexDB's managed API | the API key stored as [`MEMORY_CORTEXDB_KEY_NAME`] | no key stored |
//!
//! Built engines are cached per config fingerprint (engine id, endpoint,
-//! credential identity), so a config change, a sign-in or a new key rebuilds
-//! the engine on the next call without any event plumbing, and repeated calls
-//! reuse one HTTP client.
+//! credential identity, layout), so a config change, a sign-in or a new key
+//! rebuilds the engine on the next call without any event plumbing, and
+//! repeated calls reuse one HTTP client.
+//!
+//! **Layout.** Under `[memory] layout = "v3"` the engine keeps everything
+//! below the signed-in person's own scope root (`user:<id>`, see
+//! [`super::scope::user_root`]), registered as owned by them; otherwise the
+//! legacy shared tree. [`bind_with_root`] binds either layout explicitly,
+//! for the layout migration, which holds both at once.
//!
//! An embedding host can bring its own engine instead ([`install_host_engine`]):
//! it then wins over the configured one for every config in the process — one
@@ -116,6 +122,30 @@ pub(crate) fn install_test_engine(workspace: &std::path::Path, engine: Arc<dyn M
.insert(workspace.to_path_buf(), engine);
}
+/// Test engines for one layout of a workspace (`None` legacy, `Some(root)`
+/// v3), read by [`bind_with_root`] ahead of everything else, so a test can
+/// hold both layouts at once as the layout migration does.
+#[cfg(test)]
+type RootEngines = HashMap<(std::path::PathBuf, Option<String>), Arc<dyn MemoryEngine>>;
+
+#[cfg(test)]
+static TEST_ROOT_ENGINES: LazyLock<RwLock<RootEngines>> =
+ LazyLock::new(|| RwLock::new(HashMap::new()));
+
+/// Binds `engine` for [`bind_with_root`] with `root` on configs whose
+/// workspace is `workspace` (tests only).
+#[cfg(test)]
+pub(crate) fn install_test_engine_for_root(
+ workspace: &std::path::Path,
+ root: Option<&str>,
+ engine: Arc<dyn MemoryEngine>,
+) {
+ TEST_ROOT_ENGINES
+ .write()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert((workspace.to_path_buf(), root.map(str::to_string)), engine);
+}
+
/// The engine an embedding host installed, if any ([`install_host_engine`]).
static HOST_ENGINE: LazyLock<RwLock<Option<BoundEngine>>> = LazyLock::new(|| RwLock::new(None));
@@ -176,10 +206,72 @@ pub fn resolve(config: &Config) -> Binding {
if let Some(bound) = host_engine() {
return Binding::On(bound);
}
+ let root = if super::scope::layout_is_v3(config) {
+ match super::scope::user_root(config) {
+ Some(root) => Some(root),
+ None => return off(None, None, "sign in to use memory in its own layout"),
+ }
+ } else {
+ None
+ };
+ resolve_configured(config, root.as_deref())
+}
+
+/// The engine the layout migration needs, for an explicit layout whatever
+/// `[memory] layout` says: `None` the legacy tree, `Some("user:<id>")` the
+/// person's v3 subtree, with `user:<id>` as its owner. Same endpoint,
+/// credential, headers and scrubbing as [`resolve`]; the two layouts are
+/// cached apart, so both can be held at once.
+///
+/// # Errors
+///
+/// Memory is off for `config`, or an embedding host's (or a test's)
+/// installed engine is bound, which has one layout of its own and cannot be
+/// bound below a scope root.
+pub fn bind_with_root(config: &Config, root: Option<&str>) -> MemoryResult<BoundEngine> {
+ #[cfg(test)]
+ {
+ let installed = TEST_ROOT_ENGINES
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(&(config.workspace_dir.clone(), root.map(str::to_string)))
+ .cloned();
+ if let Some(engine) = installed {
+ return Ok(BoundEngine {
+ id: engine.descriptor().id.to_string(),
+ endpoint: "test://engine".to_string(),
+ engine: super::guard::ScrubbingEngine::wrap(engine),
+ });
+ }
+ let one_engine = TEST_ENGINES
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains_key(&config.workspace_dir);
+ if one_engine && root.is_some() {
+ return Err(MemoryError::Engine(
+ "the installed test engine cannot be bound below a scope root".to_string(),
+ ));
+ }
+ }
+ if host_engine().is_some() && root.is_some() {
+ return Err(MemoryError::Engine(
+ "the host's memory engine cannot be bound below a scope root".to_string(),
+ ));
+ }
+ if root.is_none() {
+ if let Some(bound) = host_engine() {
+ return Ok(bound);
+ }
+ }
+ resolve_configured(config, root).engine()
+}
+
+/// The configured engine with its scope root (`None` legacy).
+fn resolve_configured(config: &Config, root: Option<&str>) -> Binding {
let engine_id = config.memory.engine.trim().to_string();
match engine_id.as_str() {
- TINYHUMANS_ENGINE => resolve_tinyhumans(config),
- CORTEXDB_ENGINE => resolve_cortexdb(config),
+ TINYHUMANS_ENGINE => resolve_tinyhumans(config, root),
+ CORTEXDB_ENGINE => resolve_cortexdb(config, root),
"" => {
let reason = if config.memory.legacy_backend_unsupported
|| config.memory.legacy_backend.is_some()
@@ -216,7 +308,18 @@ fn off(engine: Option<&str>, endpoint: Option<String>, reason: &str) -> Binding
}
}
-fn resolve_tinyhumans(config: &Config) -> Binding {
+/// The engine settings' scope root and owner, and the fingerprint suffix
+/// that keeps each layout's engine apart in the cache.
+fn rooted(settings: EngineSettings, root: Option<&str>) -> (EngineSettings, String) {
+ let settings = EngineSettings {
+ scope_root: root.map(str::to_string),
+ scope_owner: root.map(str::to_string),
+ ..settings
+ };
+ (settings, format!("|root={}", root.unwrap_or("legacy")))
+}
+
+fn resolve_tinyhumans(config: &Config, root: Option<&str>) -> Binding {
let endpoint = match config.memory.endpoint_for(TINYHUMANS_ENGINE) {
Some(endpoint) => endpoint,
None => match crate::backend::base_url(&config.api_url) {
@@ -249,14 +352,18 @@ fn resolve_tinyhumans(config: &Config) -> Binding {
let source: Arc<dyn BearerSource> = Arc::new(HostBearer {
config: Arc::new(config.clone()),
});
- build_cached(
- TINYHUMANS_ENGINE,
+ let (settings, layout) = rooted(
EngineSettings {
endpoint: Some(endpoint),
headers,
..EngineSettings::default()
},
- fingerprint,
+ root,
+ );
+ build_cached(
+ TINYHUMANS_ENGINE,
+ settings,
+ fingerprint + &layout,
EngineCredential::Dynamic(source),
)
}
@@ -276,7 +383,7 @@ fn attribution_headers() -> std::collections::BTreeMap<String, String> {
.collect()
}
-fn resolve_cortexdb(config: &Config) -> Binding {
+fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {
let configured = config.memory.endpoint_for(CORTEXDB_ENGINE);
let endpoint = configured
.clone()
@@ -301,13 +408,17 @@ fn resolve_cortexdb(config: &Config) -> Binding {
};
let fingerprint = format!("{CORTEXDB_ENGINE}|{endpoint}|{}", key_digest(&key));
// A third-party endpoint: no TinyHumans attribution headers.
- build_cached(
- CORTEXDB_ENGINE,
+ let (settings, layout) = rooted(
EngineSettings {
endpoint: Some(endpoint),
..EngineSettings::default()
},
- fingerprint,
+ root,
+ );
+ build_cached(
+ CORTEXDB_ENGINE,
+ settings,
+ fingerprint + &layout,
EngineCredential::Static(key),
)
}
diff --git a/crates/openhuman-core/src/memory/scope.rs b/crates/openhuman-core/src/memory/scope.rs
index 81f03a751c..5f39f7a7ee 100644
--- a/crates/openhuman-core/src/memory/scope.rs
+++ b/crates/openhuman-core/src/memory/scope.rs
@@ -31,13 +31,19 @@
//! 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.
use std::future::Future;
use tinymemory_api::{Namespace, Segment, SegmentKind};
use tinymemory_tools::MemoryLayout;
-use crate::config::Config;
+use crate::config::{Config, MemoryLayoutMode};
+use crate::memory::error::{MemoryError, MemoryResult};
/// The memory agent id of work no agent is running (RPC, sync jobs, the UI).
pub const DEFAULT_AGENT_ID: &str = "assistant";
@@ -131,6 +137,11 @@ impl MemoryIdentity {
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);
@@ -142,6 +153,95 @@ impl MemoryIdentity {
}
}
+/// 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 (`user:<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())
+}
+
+/// Whether `config` keeps memory in layout v3 (`[memory] layout = "v3"`).
+#[must_use]
+pub fn layout_is_v3(config: &Config) -> bool {
+ config.memory.layout == MemoryLayoutMode::V3
+}
+
+/// The engine scope root of the person `config` belongs to: `user:<id>`
+/// for a TinyHumans account (its 24-hex id), `user:local-<digest>` for a
+/// local session (hashed, so no device name reaches the engine), and `None`
+/// before anyone signs in. Read from where the config lives
+/// (`<root>/users/<id>/config.toml`).
+#[must_use]
+pub fn user_root(config: &Config) -> Option<String> {
+ let dir = config.config_path.parent()?;
+ if dir.parent()?.file_name()? != "users" {
+ return None;
+ }
+ user_root_for(dir.file_name()?.to_str()?)
+}
+
+/// [`user_root`] for the user id `id`.
+fn user_root_for(id: &str) -> Option<String> {
+ use sha2::{Digest, Sha256};
+ if id.is_empty() || id == crate::config::PRE_LOGIN_USER_ID {
+ return None;
+ }
+ let account = id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit());
+ if account {
+ return Some(format!("user:{}", id.to_ascii_lowercase()));
+ }
+ let digest: String = Sha256::digest(id.as_bytes())
+ .iter()
+ .take(8)
+ .map(|byte| format!("{byte:02x}"))
+ .collect();
+ Some(format!("user:local-{digest}"))
+}
+
+/// Switches the signed-in person's memory to layout v3: loads the config
+/// fresh (a long migration's own copy would revert settings changed since),
+/// 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.
+///
+/// # Errors
+///
+/// The config could not be loaded or saved.
+pub async fn switch_to_v3() -> MemoryResult<()> {
+ let mut config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(MemoryError::Engine)?;
+ config.memory.layout = MemoryLayoutMode::V3;
+ config
+ .save()
+ .await
+ .map_err(|error| MemoryError::Engine(format!("saving config failed: {error:#}")))?;
+ super::engine::invalidate();
+ tracing::info!("[memory:scope] memory switched to layout v3");
+ Ok(())
+}
+
/// The layout `team`'s members share.
fn team_root(team: &str) -> Namespace {
Namespace::ROOT