Skip to content

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

refactor(memory): adopt upstream TinyMemory identity and confinement

Steven Enamakel757e3da0a8fe
diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md
index a9fa95c0fb..d2735efe7f 100644
--- a/crates/openhuman-core/src/memory/README.md
+++ b/crates/openhuman-core/src/memory/README.md
@@ -65,15 +65,15 @@ Memory follows TinyMemory's standard layout (`tinymemory_tools::MemoryLayout`):
+-- agent:<memory agent> one agent's conversations, one turn per item
```
-A `MemoryIdentity` (in [`scope.rs`](./scope.rs)) is the acting agent definition and, for a
-team member, its team. It is explicit, never ambient: a turn's
-`OpenHumanRunContext::memory_identity` carries it (`MemoryIdentity::child` for
-each sub-agent, `team_member` from the team runtime through
-`HostTurnEnv::memory_identity`), the RPC handlers and the embed facade pass
-`MemoryIdentity::root()`, and the `confine`, `brain`, `lifecycle` and `ops`
-entry points take a `&MemoryIdentity`.
-`MemoryIdentity::resolve` turns it into a `ResolvedIdentity` (layout root plus
-memory agent id), first match wins:
+TinyMemory's `Identity` is the acting agent definition and, for a team member,
+its team. It is explicit, never ambient: a turn's
+`OpenHumanRunContext::memory_identity` carries it (`Identity::child` for each
+sub-agent, `team_member` from the team runtime through
+`HostTurnEnv::memory_identity`), and RPC/embed entry points construct
+`Identity::root()`. OpenHuman projects its config once into upstream
+`IdentityPins` in [`scope.rs`](./scope.rs); `Identity::resolve(&pins)` returns
+the upstream `ResolvedIdentity` (layout root plus memory agent id), with this
+first-match precedence:
| Rule | Memory agent id | Layout root |
| --- | --- | --- |
@@ -87,10 +87,12 @@ The host binding is how a coordinating host (an embedder through
its own: it derives a per-agent config with those two keys set. The
identity is never taken from model arguments.
-Under `[memory] layout = "v3"` everything sits below the signed-in person's
-own scope root (`org:<id>`, `scope::user_root`), and every agent's chats
-share one chat node (`ws:main`, `scope::chat_node`), with the agent id kept
-on each turn. The person's actor is `user:<id>` (`scope::actor_of_root`),
+Under `[memory] layout = "v3"` the engine binds below the signed-in person's
+tenant root (`org:<id>`, `scope::user_root`), while namespace placement stays
+within the configured TinyMemory layout. Every agent's chats share the
+absolute `ws:main` child of that layout root (`tinymemory_tools::layout::identity::chat_node`),
+with the agent id kept on each turn. The person's actor is `user:<id>`
+(`tinymemory_tools::layout::identity::actor_of_root`),
which is also the retired root still read during the move while
`[memory] legacy_user_segment_read` is on. A signed-out session gets its
root from a random install id minted once and recorded in
@@ -268,13 +270,12 @@ Anything unknown counts as not free.
### The RPC surface is confined
-The `memory_*` RPCs (and the MCP memory tools that dispatch through them)
-go through [`confine.rs`](./confine.rs). It resolves the identity in scope (the agent of a
-running turn, else the config's own root identity), fills an unset `reach`
-with that identity's subtree, refuses a wider reach with `INVALID_REQUEST`,
-and places a `learn` with no namespace at the identity's learnings node.
-The agent `memory` tool applies the same confinement and overwrites any
-`reach` in the model's filter.
+The `memory_*` RPC handlers apply TinyMemory `Confinement` with
+`Policy::Refuse`: an unset `reach` becomes the root identity's subtree, wider
+reaches return `INVALID_REQUEST`, and a `learn` with no namespace uses the
+identity's learnings node. SaaS operations use `Policy::Clamp` selected from
+the configured profile root in `ops.rs`. The agent `memory` tool keeps its
+existing trusted reach and applies the same upstream confinement methods.
## Layout
@@ -283,7 +284,7 @@ The agent `memory` tool applies the same confinement and overwrites any
| [`mod.rs`](./mod.rs) | Module declarations and re-exports (`memory_is_on`, `MemoryTool`, the controller aggregators, `register_memory_subscribers`). |
| [`engine.rs`](./engine.rs) | `resolve` binds the configured engine or says why memory is off; per-fingerprint cache; host engine install; CortexDB key storage. |
| [`guard.rs`](./guard.rs) | `ScrubbingEngine`: scrubs every write and times every engine call. |
-| [`scope.rs`](./scope.rs) | `MemoryIdentity`, `ResolvedIdentity`, resolution order, layout v3 roots. |
+| [`scope.rs`](./scope.rs) | Config-to-`IdentityPins` adapter, account root and layout migration switch. |
| [`local_root.rs`](./local_root.rs) | The persistent install-id root of a signed-out session. |
| [`lifecycle/mod.rs`](./lifecycle/mod.rs) | Builds `AgentMemory` for an identity under the `[memory.recall]` policy. |
| [`lifecycle/hooks.rs`](./lifecycle/hooks.rs) | Lifecycle operations and bounded manual wrappers; `TurnPack`, `MemoryTurn`. |
@@ -294,7 +295,6 @@ The agent `memory` tool applies the same confinement and overwrites any
| [`lifecycle/date_hint.rs`](./lifecycle/date_hint.rs) | Optional model call that works out which days a turn refers to. |
| [`ops.rs`](./ops.rs) | Engine list/get/set, recall, fetch, learn, forget, erase all, items list. |
| [`tool_budget.rs`](./tool_budget.rs), [`tool_writes.rs`](./tool_writes.rs) | Agent call deadlines; owner-scoped admission and file store for optional writes. The FIFO, coalescing and fencing are `tinymemory_tools::pending`. |
-| [`confine.rs`](./confine.rs) | Confines the RPC surface to the acting identity's subtree. |
| [`explore.rs`](./explore.rs) | The facet explorer behind `memory_explore` and `memory_items_get`. |
| [`brain.rs`](./brain.rs) | Brain source mapping and the `memory_brain_*` ops. |
| [`sources/`](./sources/) | The `[[memory.sources]]` registry (`mod.rs`), sync state (`state.rs`) and the `SourceRegistry` adapter over `tinymemory_integrations::sources::sync` (`sync.rs`). |
@@ -320,8 +320,9 @@ The agent `memory` tool applies the same confinement and overwrites any
`BoundEngine`, or learn that memory is off.
- `engine::install_host_engine` (`engine.rs`): lets an embedder or test
supply its own `MemoryEngine`.
-- `MemoryIdentity::child` and `MemoryIdentity::resolve` (`scope.rs`): derive
- and resolve the acting identity a turn's run context carries.
+- TinyMemory `Identity::child` / `Identity::resolve` with
+ `scope::identity_pins` (`scope.rs`): derive and resolve the acting identity
+ a turn's run context carries.
- `lifecycle::prefetch::pre_turn` and `compaction`
(`lifecycle/prefetch.rs`): synchronous reads of completed packs plus scoped
background refresh. `lifecycle::hooks` contains the underlying operations;
@@ -419,15 +420,16 @@ sits in the app directory shared by all accounts
## Gotchas
-- The acting identity is a task-local. Work spawned off a turn without
- `scope::within` runs as the config's root identity, not the agent.
+- The acting identity is passed explicitly. Work spawned without an identity
+ runs as the config's root identity, not the agent.
- Turn hooks run under the session's own config, which may be a derived
context carrying a host binding (`[memory] agent_id` / `root`). Loading the
global config instead would write to the wrong memory.
- Every write must go through a bound engine so the scrubber sees it. Do not
hold a raw `MemoryEngine` outside `engine.rs`.
-- RPC handlers must call through `confine.rs`, not [`ops.rs`](./ops.rs) directly, or a
- caller can read another root's memory.
+- RPC handlers must apply upstream `Confinement` with `Policy::Refuse` in
+ [`schemas/handlers.rs`](./schemas/handlers.rs) before calling [`ops.rs`](./ops.rs),
+ or a caller can read another root's memory.
- A new local state file should be written with `files::write_private`.
- `engine::invalidate` clears the engine cache; tests that swap engines rely
on the `CACHE_STABLE` lock and `install_test_engine`.
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
index 0f9f40af77..4cbf395965 100644
--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
@@ -84,7 +84,6 @@ impl lm::LayoutHost for AppHost {
// switch.
let mut v3 = self.config.clone();
v3.memory.layout = MemoryLayoutMode::V3;
- v3.memory.root = Some(signed_in_root(&self.config).map_err(to_module)?);
let layout = tinymemory_tools::layout::identity::Identity::root()
.resolve(&crate::memory::scope::identity_pins(&v3))
.layout;
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
index 0b407bb934..fc1c072953 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
@@ -47,8 +47,8 @@ async fn binds_the_legacy_tree_and_the_users_own() {
assert!(scan(&AppHost::new(config.clone())).await.unwrap().needed);
let placement = AppHost::new(config.clone()).placement().unwrap();
- assert_eq!(placement.layout.root().to_string(), root);
- assert_eq!(placement.chat_node.to_string(), format!("{root}/ws:main"));
+ assert_eq!(placement.layout.root().to_string(), "root");
+ assert_eq!(placement.chat_node.to_string(), "ws:main");
assert!(matches!(placement.flows, FlowPlacement::WithRoot));
}
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index 93cc858fac..f127ed1f08 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -213,10 +213,11 @@ pub async fn recall_with(
mode: RecallMode,
exclude_thread: Option<ThreadWindow>,
) -> Result<RecallView> {
+ let filter = confine_filter(config, params.filter.unwrap_or_default())?;
let bound = bound(config)?;
let request = RecallRequest {
question: params.question,
- filter: confine_filter(config, params.filter.unwrap_or_default())?,
+ filter,
limit: clamp_limit(params.limit),
instructions: None,
refers_to: time_hint(config, params.refers_to)?,
@@ -250,6 +251,7 @@ pub async fn fetch_with(
params: FetchParams,
exclude_thread: Option<ThreadWindow>,
) -> Result<FetchView> {
+ let filter = confine_filter(config, params.filter.unwrap_or_default())?;
let bound = bound(config)?;
let descriptor = bound.engine.descriptor();
let mode = match params.mode {
@@ -265,7 +267,7 @@ pub async fn fetch_with(
let request = FetchRequest {
query: params.query,
mode,
- filter: confine_filter(config, params.filter.unwrap_or_default())?,
+ filter,
limit: clamp_limit(params.limit),
cursor: params.cursor,
beliefs: 0,
diff --git a/crates/openhuman-core/src/memory/ops_tests.rs b/crates/openhuman-core/src/memory/ops_tests.rs
index 94e24bc7ab..d398932096 100644
--- a/crates/openhuman-core/src/memory/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_tests.rs
@@ -13,10 +13,10 @@ use tinymemory_api::{
};
#[test]
-fn invalid_saas_root_is_refused_before_store_reaches_the_engine() {
+fn invalid_saas_root_is_refused_before_engine_operations() {
const CHILD: &str = "OPENHUMAN_TEST_SAAS_MEMORY_STORE_GUARD";
const TEST_NAME: &str =
- "memory::ops::tests::invalid_saas_root_is_refused_before_store_reaches_the_engine";
+ "memory::ops::tests::invalid_saas_root_is_refused_before_engine_operations";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
@@ -52,19 +52,61 @@ fn invalid_saas_root_is_refused_before_store_reaches_the_engine() {
calls: calls.clone(),
}),
);
+ let expected = "memory is unavailable: this agent has no valid memory root";
+ let check = |error: Error| {
+ assert!(matches!(error, Error::InvalidRequest(message) if message == expected));
+ };
let item = StoreItem::learning(
"should not be stored",
tinymemory_api::LearningKind::Fact,
0.9,
MemoryMeta::default(),
);
- let error = runtime.block_on(store_item(&config, item)).unwrap_err();
-
- assert!(matches!(
- error,
- Error::InvalidRequest(message)
- if message == "memory is unavailable: this agent has no valid memory root"
- ));
+ check(runtime.block_on(store_item(&config, item)).unwrap_err());
+ check(
+ runtime
+ .block_on(recall(
+ &config,
+ RecallParams {
+ refers_to: None,
+ question: "anything".into(),
+ filter: None,
+ limit: None,
+ },
+ ))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(fetch(
+ &config,
+ FetchParams {
+ refers_to: None,
+ query: "anything".into(),
+ mode: None,
+ filter: None,
+ limit: None,
+ cursor: None,
+ },
+ ))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(items_list(&config, ItemsListParams::default()))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(forget(
+ &config,
+ ForgetParams {
+ ids: vec!["not-present".into()],
+ reach: None,
+ },
+ ))
+ .unwrap_err(),
+ );
assert_eq!(calls.load(Ordering::SeqCst), 0, "root: {root:?}");
}
println!("SAAS_MEMORY_STORE_GUARD_CHILD_PASSED");
diff --git a/crates/openhuman-core/src/memory/scope_tests.rs b/crates/openhuman-core/src/memory/scope_tests.rs
index cfbc8db41c..7931494e94 100644
--- a/crates/openhuman-core/src/memory/scope_tests.rs
+++ b/crates/openhuman-core/src/memory/scope_tests.rs
@@ -94,17 +94,20 @@ fn upstream_identity_and_confinement_keep_embedded_root_and_rpc_policy() {
}
#[test]
-fn upstream_v3_identity_pools_at_the_account_root_workspace() {
+fn account_v3_identity_pools_at_the_absolute_layout_workspace() {
let mut config = Config::default();
config.config_path = "/srv/openhuman/users/6512ab0f6512ab0f6512ab0f/config.toml".into();
- config.memory.root = user_root(&config);
config.memory.layout = MemoryLayoutMode::V3;
let resolved = Identity::root().resolve(&super::identity_pins(&config));
- assert_eq!(resolved.root(), &ns("org:6512ab0f6512ab0f6512ab0f"));
+ assert_eq!(
+ user_root(&config).as_deref(),
+ Some("org:6512ab0f6512ab0f6512ab0f")
+ );
+ assert_eq!(resolved.root(), &Namespace::ROOT);
assert_eq!(
resolved.layout.pooled_conversations_node(),
- Some(&ns("org:6512ab0f6512ab0f6512ab0f/ws:main"))
+ Some(&ns("ws:main"))
);
}
diff --git a/crates/openhuman-core/src/profiles/README.md b/crates/openhuman-core/src/profiles/README.md
index 622619480f..0f1ce659b0 100644
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@ -228,7 +228,7 @@ A profile holds one thread per conversation, whatever interface it came in on:
- Memory is bound to the profile (`[memory] agent_id`, `root = user:<id>`).
That binding wins over definition pins and team roots.
- The memory layout is pinned to the legacy tree (confined to that root by
- `memory::user_scope`). Layout v3 would bind the engine below
+ upstream `Confinement` with `Policy::Clamp`, selected by `memory::ops`). Layout v3 would bind the engine below
`memory::scope::user_root`, which reads `users/<id>` from the config path
and would answer `org:<id>` or a minted local root instead.
- The autonomy policy is on and supervised, with no auto-approval, no tool
diff --git a/docs/gitbooks/en/developing/architecture/memory.md b/docs/gitbooks/en/developing/architecture/memory.md
index 81312d456e..fa92c2871a 100644
--- a/docs/gitbooks/en/developing/architecture/memory.md
+++ b/docs/gitbooks/en/developing/architecture/memory.md
@@ -25,7 +25,7 @@ The behavior is specified in [`docs/specs/memory-v2.md`](https://github.com/tiny
| --- | --- |
| `engine` | Binds `[memory] engine`: `tinyhumans` over the host's backend credential (resolved per request) with the transport's attribution headers, or `cortexdb` with the key stored as `memory-cortexdb`. Off when neither is usable. |
| `guard` | `ScrubbingEngine`: every write is scrubbed under the host policy, whichever path makes it. |
-| `scope` | `MemoryIdentity` scoped around every turn, resolved to a layout root and a memory agent id (host binding, definition pin, team, default). |
+| `scope` | Projects OpenHuman config into TinyMemory `IdentityPins`; callers use upstream `Identity` / `ResolvedIdentity` for each turn. |
| `lifecycle::prefetch` | Scoped, bounded in-memory cache and background workers for automatic turn and compaction recall. |
| `lifecycle::hooks` | Lifecycle primitives; explicit/manual `pre_turn` and `compaction` retain configured deadlines. |
| `lifecycle::jobs` | The persisted background queue and the `memory_background` cron job. |
diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.md
index 076dbc5a6a..22ffe81b44 100644
--- a/docs/specs/memory-v2.md
+++ b/docs/specs/memory-v2.md
@@ -33,13 +33,14 @@ With no usable engine (signed out and no CortexDB key), memory is **off**:
## Who is acting (`memory::scope`)
-A `MemoryIdentity` (an agent definition and, for a team member, its team) is
-carried explicitly on every turn's run context (`OpenHumanRunContext::memory_identity`):
-set by the session host and channel dispatch for top-level agents, derived with
-`child` by the sub-agent runner for children, and handed down by the team
-runtime for members. RPC handlers and the embed facade act as the root
-identity. Memory resolves it against the config of whoever reads or writes,
-first match wins:
+TinyMemory's `Identity` (an agent definition and, for a team member, its team)
+is carried explicitly on every turn's run context
+(`OpenHumanRunContext::memory_identity`): set by the session host and channel
+dispatch for top-level agents, derived with `child` by the sub-agent runner
+for children, and handed down by the team runtime for members. RPC handlers
+and the embed facade act as the root identity. OpenHuman adapts its config to
+`IdentityPins` once in `memory::scope`; callers resolve the identity against
+those pins, first match wins:
| | memory agent id | layout root |
| --- | --- | --- |
@@ -69,9 +70,8 @@ does not use the ambient-config RPCs.
The ambient-config RPCs (`openhuman.memory_recall`, `_fetch`, `_learn`,
`_forget`, `_items_list`, `_explore`, `_items_get`) and the MCP memory tools,
-which dispatch through them, are confined the same way to the identity in
-scope (`memory::confine`): the agent of a running turn, else the config's own
-root identity (`[memory] root`, else the root). An unset `reach` becomes
+which dispatch through them, use upstream `Confinement` with `Policy::Refuse`
+for the config's root identity (`[memory] root`, else the root). An unset `reach` becomes
`Reach::subtree(<root>)`; a caller's reach is kept only when it is
`Reach::within` that subtree, and a wider one is refused with
`INVALID_REQUEST`; `forget` and `items_get` skip ids outside it; `learn` with
diff --git a/scripts/ci/check-agent-runtime-boundary.mjs b/scripts/ci/check-agent-runtime-boundary.mjs
index f28d5601e4..c4ccb50fd9 100644
--- a/scripts/ci/check-agent-runtime-boundary.mjs
+++ b/scripts/ci/check-agent-runtime-boundary.mjs
@@ -203,7 +203,7 @@ const taskLocalAccessors = [
"current_meter",
"with_turn_activity",
// `memory::scope` (the acting memory identity) is explicit now: a run's
- // `OpenHumanRunContext::memory_identity`, or a `&MemoryIdentity` argument.
+ // `OpenHumanRunContext::memory_identity`, or a `&Identity` argument.
"resolve_current",
];
const taskLocalStatics = [
diff --git a/tests/memory_v2_e2e.rs b/tests/memory_v2_e2e.rs
index 95a9fa7c67..0a329a25f3 100644
--- a/tests/memory_v2_e2e.rs
+++ b/tests/memory_v2_e2e.rs
@@ -917,7 +917,7 @@ async fn the_agent_learn_returns_on_accept_and_recall_finds_it() {
.expect("the signed-in config");
let facts = openhuman_core::memory::tools::CallFacts::of(
&config,
- &openhuman_core::memory::scope::MemoryIdentity::agent("orchestrator"),
+ &Default::default(),
);
// Control: `memory_learn` over RPC returns once the write is readable, so
diff --git a/tests/saas_mode/memory.rs b/tests/saas_mode/memory.rs
index ee7cfc2081..d3b6043da9 100644
--- a/tests/saas_mode/memory.rs
+++ b/tests/saas_mode/memory.rs
@@ -3,9 +3,8 @@
//!
//! Each profile runs the hosted `tinyhumans` engine with its own credential,
//! confined to `user:<id>` on the legacy layout (`profiles::layout`). The
-//! mock keeps one store for every bearer, so nothing but the core's own
-//! confinement keeps the profiles apart: the case `memory::user_scope`
-//! defends, users sharing one engine.
+//! mock keeps one store for every bearer, so the core's `Policy::Clamp`
+//! boundary in `memory::ops` keeps users sharing one engine apart.
//!
//! `ann` and `anna` are deliberate: one root is a string prefix of the
//! other, and a scope listing is a string-prefix match.
diff --git a/tests/saas_mode/mock_memory.rs b/tests/saas_mode/mock_memory.rs
index eb6801db2a..646f4ab157 100644
--- a/tests/saas_mode/mock_memory.rs
+++ b/tests/saas_mode/mock_memory.rs
@@ -7,8 +7,8 @@
//! one deliberate difference: **every bearer shares one store**. The real
//! backend keeps each credential's memory apart, which would hide a core
//! that read or wrote outside a profile's `user:<id>` root. Here the only
-//! thing keeping profiles apart is the core's own confinement, the worst case
-//! `memory::user_scope` defends (users sharing one engine). Every request is
+//! thing keeping profiles apart is the core's upstream `Policy::Clamp`, the
+//! worst case `memory::ops` defends (users sharing one engine). Every request is
//! recorded with its bearer and the scopes it names, so a test can check
//! both what each profile read back and what it asked the backend for.
//!