Skip to content

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

Stop booting the second in-process memory engine

Shanu1bf2037a089d
diff --git a/Cargo.toml b/Cargo.toml
index 3720cdba6e..3c60de8b9f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1152,6 +1152,25 @@ whatsapp-web = ["channels", "tinychannels/whatsapp-web"]
# build (app/scripts/e2e-build.sh) flips it on. Shipped binaries never have
# this feature so the wipe RPC isn't even registered, let alone reachable.
e2e-test-support = []
+# Compiles `memory::host_impls`, the host side of the seam traits the memory
+# ENGINE declares, for builds that embed that engine in-process.
+#
+# The shipped product does not: its driver is the loaded TinyMemory module,
+# which installs its own seams and calls back over the bus through
+# `modules::memory_host`. What still embeds the engine is the test suite, which
+# binds the in-process TinyCortex driver directly — legitimate there, because
+# `tinymemory-core` is a dev-dependency and dev-dependency features are not
+# linked into the shipped binary.
+#
+# Unit tests get it from `cfg(test)`. Integration tests under `tests/` are
+# separate crates and `cfg(test)` does NOT reach them, which is the whole reason
+# this feature exists rather than a bare `#[cfg(test)]`.
+#
+# Deliberately absent from `scripts/ci/product-features.txt` and from `default`,
+# and allow-listed in `check-feature-forwarding.mjs`: forwarding it to the
+# desktop shell would put the engine back into the shipped graph, which is the
+# single thing #5560 exists to prevent.
+memory-embedded-test-seams = []
# Builds the `rss-bench` benchmark binary (#5046). Default-OFF, so it is never
# part of the shipped desktop/library build and the feature-forwarding gate
# (which only inspects the `default` list) never requires forwarding it.
diff --git a/scripts/test-rust-with-mock.sh b/scripts/test-rust-with-mock.sh
index 90c388b4a3..c44b15f0a3 100755
--- a/scripts/test-rust-with-mock.sh
+++ b/scripts/test-rust-with-mock.sh
@@ -75,9 +75,18 @@ fi
# Source of truth: scripts/ci/product-features.txt.
PRODUCT_FEATURES="$(bash "$REPO_ROOT/scripts/ci/product-features.sh")"
+# `memory-embedded-test-seams` is added on top of the product set, and only
+# here. It compiles `memory::host_impls`, the host side of the seam traits the
+# memory ENGINE declares, which the integration tests under `tests/` need
+# because they bind the in-process TinyCortex driver. `cfg(test)` cannot serve
+# them — an integration test is a separate crate and never sees it.
+#
+# It must NOT reach the product build: forwarding it to the desktop shell would
+# put the engine back into the shipped dependency graph, which is precisely what
+# #5560 removed. That is why it lives here rather than in product-features.txt.
cargo_test() {
cargo test --manifest-path Cargo.toml --workspace \
- --features "${PRODUCT_FEATURES},bin-tools" "$@"
+ --features "${PRODUCT_FEATURES},bin-tools,memory-embedded-test-seams" "$@"
}
integration_test_targets() {
diff --git a/src/core/memory_cli.rs b/src/core/memory_cli.rs
index 81cb957cf3..be0fa61070 100644
--- a/src/core/memory_cli.rs
+++ b/src/core/memory_cli.rs
@@ -15,8 +15,8 @@ use anyhow::Result;
use std::io::Read;
use std::path::PathBuf;
+use crate::openhuman::memory::api::provider::MemoryDocuments;
use crate::openhuman::memory::api::types::NamespaceDocumentInput;
-use tinymemory_core::ingestion::{MemoryIngestionConfig, MemoryIngestionRequest};
/// Entry point for `openhuman memory <subcommand>`.
pub fn run_memory_command(args: &[String]) -> Result<()> {
@@ -149,8 +149,14 @@ fn run_ingest(args: &[String]) -> Result<()> {
.enable_all()
.build()?;
- let result = rt.block_on(async {
- let client = create_memory_client("ingest").await?;
+ let document_id = rt.block_on(async {
+ let binding = create_memory_binding("ingest").await?;
+ let documents = binding.provider().as_documents().ok_or_else(|| {
+ anyhow::anyhow!(
+ "the bound memory driver '{}' does not serve documents",
+ binding.driver_id()
+ )
+ })?;
let document = NamespaceDocumentInput {
namespace: namespace.clone(),
@@ -167,39 +173,33 @@ fn run_ingest(args: &[String]) -> Result<()> {
taint: crate::openhuman::memory::MemoryTaint::Internal,
};
- let ingestion_config = MemoryIngestionConfig::default();
-
- eprintln!(
- "[memory:cli] starting ingestion with model={}",
- ingestion_config.model_name,
- );
-
- let result = client
- .ingest_doc(MemoryIngestionRequest {
- document,
- config: ingestion_config,
- })
+ documents
+ .put_document(document)
.await
- .map_err(anyhow::Error::msg)?;
-
- Ok::<_, anyhow::Error>(result)
+ .map_err(|e| anyhow::anyhow!("{e}"))
})?;
eprintln!();
eprintln!("=== Ingestion Result ===");
- eprintln!(" document_id: {}", result.document_id);
- eprintln!(" namespace: {}", result.namespace);
- eprintln!(" model: {}", result.model_name);
- eprintln!(" mode: {}", result.extraction_mode);
- eprintln!(" chunks: {}", result.chunk_count);
- eprintln!(" entities: {}", result.entity_count);
- eprintln!(" relations: {}", result.relation_count);
- eprintln!(" preferences: {}", result.preference_count);
- eprintln!(" decisions: {}", result.decision_count);
- eprintln!(" tags: {:?}", result.tags);
-
- // Print full JSON to stdout for piping/scripting
- println!("{}", serde_json::to_string_pretty(&result)?);
+ eprintln!(" document_id: {document_id}");
+ eprintln!(" namespace: {namespace}");
+ // Narrower than this command used to print, and the reason is worth stating
+ // rather than leaving as an apparent regression. It used to call the
+ // engine's `ingest_doc` directly and report the extraction tally it
+ // returned — chunk, entity, relation, preference and decision counts, the
+ // model and the extraction mode. The module contract's `put_document`
+ // answers a document id, and `IngestOutcome` carries only written/skipped
+ // counts and ids, so there is nothing on the wire to print those from.
+ // The extraction still happens; only the report is smaller. Widening it
+ // means a new contract member and a release, not a host change.
+
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "document_id": document_id,
+ "namespace": namespace,
+ }))?
+ );
Ok(())
}
@@ -362,14 +362,24 @@ fn run_query(args: &[String]) -> Result<()> {
.build()?;
let result = rt.block_on(async {
- let client = create_memory_client("query").await?;
- client
- .query_namespace(&namespace, &query, limit)
+ let binding = create_memory_binding("query").await?;
+ let documents = binding.provider().as_documents().ok_or_else(|| {
+ anyhow::anyhow!(
+ "the bound memory driver '{}' does not serve documents",
+ binding.driver_id()
+ )
+ })?;
+ documents
+ .query_documents(&namespace, &query, limit as usize)
.await
- .map_err(anyhow::Error::msg)
+ .map_err(|e| anyhow::anyhow!("{e}"))
})?;
- println!("{result}");
+ // The contract answers a structured context where the engine handed back a
+ // rendered string, so the CLI does the rendering. JSON rather than a guess
+ // at the engine's old prose layout: a scripted caller can read it, and it
+ // cannot silently diverge from what the driver actually returned.
+ println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
@@ -536,12 +546,10 @@ async fn create_memory_binding(
}
}
- // Same seams, same reason as `create_memory_client` — plus the `[modules]`
- // policy, which a module-backed driver needs published before it can load
- // and which only the runtime bootstrap otherwise sets. Both are idempotent.
- crate::openhuman::memory::host_impls::install_memory_host_seams(std::sync::Arc::new(
- config.clone(),
- ));
+ // The `[modules]` policy, which a module-backed driver needs published
+ // before it can load and which only the runtime bootstrap otherwise sets.
+ // Idempotent. The engine seams that used to be installed alongside it are
+ // gone: this process embeds no engine, so there is nothing to call back.
#[cfg(feature = "modules")]
crate::openhuman::modules::memory::set_modules_policy(std::sync::Arc::new(config.clone()));
@@ -594,45 +602,6 @@ fn documents_family(
/// Both gates are default-OPEN when the binding cannot be resolved, mirroring
/// [`crate::core::all::capability_allowed`]: denying is only ever correct after
/// a driver has actually answered `capabilities()`.
-async fn create_memory_client(subcommand: &str) -> Result<tinymemory_core::store::MemoryClientRef> {
- let config = crate::openhuman::config::Config::load_or_init()
- .await
- .unwrap_or_default();
-
- // Resolved through `cli_capability` rather than `binding::for_workspace`
- // here, so the memory-guard bypass ratchet carries ONE allowlisted line
- // for the whole CLI layer instead of one per entry point. Default-OPEN
- // when the binding cannot be resolved.
- let invocation = format!("openhuman memory {subcommand}");
- if let Some((driver_id, class, advertised)) =
- crate::core::cli_capability::bound_memory_driver_for(
- &config.workspace_dir,
- &config.subsystems.memory,
- )
- {
- crate::core::cli_capability::legacy_client_verdict(&driver_id, class, &invocation)?;
- if let Some(required) = required_capability(subcommand) {
- crate::core::cli_capability::capability_verdict(
- &driver_id,
- advertised,
- Some(required),
- &invocation,
- )?;
- }
- }
-
- // The CLI dispatches straight to a subcommand and never runs the runtime
- // bootstrap, so nothing else installs these. They must be in place before
- // the first memory call: the embedding, chat, Composio and config seams
- // fail loudly when unwired rather than degrading, and a `memory` subcommand
- // that reached one would report a broken subsystem rather than a missing
- // one. Idempotent, so calling it per invocation is safe.
- crate::openhuman::memory::host_impls::install_memory_host_seams(std::sync::Arc::new(
- config.clone(),
- ));
- tinymemory_core::global::init(config.workspace_dir).map_err(anyhow::Error::msg)
-}
-
fn print_memory_help() {
println!("Usage: openhuman memory <subcommand> [options]");
println!();
diff --git a/src/core/runtime/context.rs b/src/core/runtime/context.rs
index a067cf997f..4583100da1 100644
--- a/src/core/runtime/context.rs
+++ b/src/core/runtime/context.rs
@@ -224,7 +224,7 @@ impl CoreContext {
}
Err(e) => {
log::error!(
- "[boot] memory::global init SKIPPED — \
+ "[boot] workspace-bound store init SKIPPED — \
Config::load_or_init failed ({e:#}). Memory persistence is \
DISABLED for this run; no silent fallback to the default \
workspace (which would cause chunk loss / cross-workspace \
@@ -524,10 +524,14 @@ impl CoreContext {
}
}
-/// Initialize the global `MemoryClient` and the other workspace-bound stores so
-/// composio providers (gmail/slack/notion) can persist their `sync_state`, and
-/// so any subsystem that calls `memory::global::client_if_ready()` gets a live
-/// handle.
+/// Bind the memory driver for this workspace and initialize the other
+/// workspace-bound stores.
+///
+/// This no longer initializes an in-process `MemoryClient`: the memory
+/// subsystem is reached through [`crate::openhuman::memory::binding`], which is
+/// a workspace-keyed cache rather than a process-global slot (#5560). The
+/// engine handle that `memory::global` still hands out is a lazy singleton, so
+/// the remaining holders construct it on first use.
///
/// A `Config::load_or_init` failure here is operator-visible and serious
/// (corrupt toml, bad permissions, missing/unwritable `OPENHUMAN_WORKSPACE` —
@@ -551,7 +555,8 @@ impl CoreContext {
/// `DomainSet` needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StoreInitPlan {
- /// `memory::global` — gated on [`DomainGroup::Memory`].
+ /// The memory driver binding (`memory::binding`) — gated on
+ /// [`DomainGroup::Memory`].
pub memory: bool,
/// `agent::multimodal` attachments sidecar dir — gated on [`DomainGroup::Agent`].
pub agent_attachments: bool,
@@ -591,13 +596,11 @@ pub async fn init_stores(
domains,
);
if plan.memory {
- // The extracted memory subsystem reaches back into this crate through
- // process-global seams. They must be installed BEFORE the first memory
- // call: the embedding, chat, Composio and config seams fail loudly when
- // unwired rather than degrading, because a quiet degrade would write
- // vectors into the wrong embedding space or make a sync run look empty
- // instead of broken.
- crate::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(cfg.clone()));
+ // No seam installation here any more. Those seams exist so an engine
+ // running INSIDE this process can call back into it, and this process
+ // no longer runs one: the driver is the loaded TinyMemory module, which
+ // installs its own seams and reaches this host over the bus through
+ // `modules::memory_host` instead.
// Publish the config a module-backed memory driver should load
// against, before the binding below can construct one. Boot-only and
// idempotent (first call wins) — see `modules::memory::set_modules_policy`
@@ -605,13 +608,27 @@ pub async fn init_stores(
// `MemoryBinding::for_workspace`.
#[cfg(feature = "modules")]
crate::openhuman::modules::memory::set_modules_policy(Arc::new(cfg.clone()));
- match tinymemory_core::global::init(cfg.workspace_dir.clone()) {
- Ok(_) => log::info!(
- "[boot] memory::global initialized (workspace={})",
- cfg.workspace_dir.display()
- ),
- Err(e) => log::warn!("[boot] memory::global init failed: {e}"),
- }
+ // ── No second engine is booted here any more (#5560 phase F) ────────
+ //
+ // This block used to call `tinymemory_core::global::init(...)` directly
+ // above the bind below, so boot left **two** live `MemoryClient`s over
+ // one `<workspace>/memory/memory.db`: the loadable TinyMemory module
+ // reached over TinyBus, and a second in-process copy of the engine
+ // crate. `memory::binding`'s module docs and
+ // `CoreContext::memory_binding`'s both already argued that the
+ // workspace-keyed binding map supersedes that process-global slot —
+ // the slot needs a clear-on-failed-rebind guard, the map structurally
+ // cannot hand workspace B's caller workspace A's driver — and this is
+ // where that argument is executed.
+ //
+ // `memory::global` is a lazy singleton, so the callers that still hold
+ // an in-process handle (`memory::ops::helpers::active_memory_client`,
+ // `agent::experience::ops`, the session builder's shared-experience
+ // handle, `openhuman memory ingest`/`query`) construct it on first use
+ // exactly as before. What changes is that a boot which never reaches
+ // one no longer pays for it — and that the engine's own lifetime is now
+ // owned by the code that still needs it rather than by kernel boot.
+ //
// Bind the memory driver for this workspace (kernel.md §3.1), on the
// same `plan.memory` gate as the store above — the binding is part of
// the memory domain's init, not a separate gate. Warmed here rather
@@ -637,7 +654,6 @@ pub async fn init_stores(
Err(e) => log::warn!("[boot] memory driver bind failed: {e}"),
}
} else {
- log::debug!("[boot] memory::global init SKIPPED — Memory domain disabled");
log::debug!("[boot] memory driver bind SKIPPED — Memory domain disabled");
}
// Install the on-disk image-attachment sidecar dir so inbound
@@ -811,7 +827,7 @@ mod tests {
fn store_init_plan_harness_gates_by_owning_group() {
let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::harness());
// harness() = agent + memory + threads + config + security.
- assert!(plan.memory, "harness keeps memory::global (Memory)");
+ assert!(plan.memory, "harness keeps the memory binding (Memory)");
assert!(
plan.agent_attachments,
"harness keeps agent attachments sidecar (Agent)"
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rs
index 65024a860b..ea85c1113a 100644
--- a/src/core/runtime/services.rs
+++ b/src/core/runtime/services.rs
@@ -12,9 +12,10 @@
//! spawned at all) up to a `ServiceSet` chosen by the embedder, while these
//! functions keep their config gates (is it enabled for this user).
-// `to_arc` / the config accessors are `MemoryHostConfig` trait methods.
-use tinymemory_api::host::MemoryHostConfig;
-
+// `MemoryHostConfig` was imported here for `config.to_arc()`, the argument to
+// the engine's `queue::start`. That call left with the in-process engine
+// (openhuman#5560 — see `start_bootstrap_jobs`); every remaining `config.…` in
+// this file is plain field access on OpenHuman's own `Config`.
use crate::core::runtime::ServiceSet;
use crate::openhuman::config::Config;
@@ -247,13 +248,40 @@ pub(crate) fn bootstrap_job_plan(services: &ServiceSet) -> BootstrapJobPlan {
/// `services.channels` — a channels-off + memory/integrations-on embedder
/// silently lost all of them (#5028) — so they now sit behind `integrations` /
/// `memory_sync` / `orchestration` instead.
-pub fn start_bootstrap_jobs(services: ServiceSet, config: &Config) {
+///
+/// `config` is unread as of openhuman#5560 — the engine's `queue::start` was
+/// this function's only consumer of it, and the loaded TinyMemory module starts
+/// that pool itself now. The parameter is **kept** rather than dropped: every
+/// other job here is one config read away from needing it again (the periodic
+/// sync loops below already re-load config internally), and removing it would
+/// churn every embedder that calls `start_bootstrap_jobs` for no gain. Named
+/// `_config` so the compiler does not have to be told to ignore it.
+pub fn start_bootstrap_jobs(services: ServiceSet, _config: &Config) {
let plan = bootstrap_job_plan(&services);
log::debug!("[runtime.bootstrap] starting bootstrap jobs with plan {plan:?}");
+ // ── The queue pool moved into the module, and must NOT be started here ──
+ //
+ // This block used to call `tinymemory_core::queue::start(config.to_arc())`,
+ // and it was the only caller of the engine's worker pool in any tree.
+ // openhuman#5560 deletes the host's second, in-process engine, so that call
+ // has no engine to drain — and `tinymemory` v1.5.0's module starts its own
+ // pool at load (`tinymemory-module/src/lib.rs`, `start_queue_pool`), which
+ // is what keeps ingest, `retry_failed` and `ensure_reembed_backfill` alive.
+ //
+ // **Restoring the call would not be a duplicate, it would be a second pool
+ // that cannot see the first.** The `cdylib` links its own copy of
+ // `tinymemory-core`, so the `Once` inside `queue::start` is a *different*
+ // static from the host's: two pools would claim jobs from one SQLite queue
+ // with neither aware of the other. That is why the line is gone rather than
+ // gated.
+ //
+ // `plan.memory_queue` is kept — it is `ServiceSet`'s statement of intent
+ // and other jobs may hang off it — but the host has no work to do for it.
if plan.memory_queue {
- log::debug!("[runtime.bootstrap] starting memory queue workers");
- tinymemory_core::queue::start(config.to_arc());
+ log::debug!(
+ "[runtime.bootstrap] memory queue workers are owned by the tinymemory module (start_queue_pool); host starts none"
+ );
} else {
log::debug!("[runtime.bootstrap] memory queue workers disabled by ServiceSet");
}
@@ -261,41 +289,31 @@ pub fn start_bootstrap_jobs(services: ServiceSet, config: &Config) {
// Integrations — Composio periodic connection sync + one-shot source
// reconcile. Both no-op without active Composio connections.
//
- // ── This call comes out with the in-process engine, and not before ──────
+ // ── This call is STILL host-side, and deleting it is not tidying ────────
//
// `start_periodic_sync` is not host code. It re-exports through
// `integrations::composio::mod.rs` to `memory::sync::composio::periodic`,
// and that module is `pub use tinymemory_core::sync::composio::*` — so the
- // loop this line starts is engine code running in the host process against
- // the engine this binary still compiles in. `ensure_composio_sources` below
- // reaches `tinymemory_core::sources` the same way.
+ // loop this line starts is engine code running in the host process.
+ // `ensure_composio_sources` below reaches `tinymemory_core::sources` the
+ // same way.
//
- // openhuman#5560 deletes that second, in-process engine and leaves the
- // loaded TinyMemory module as the only one. Deleting this line before then
- // stops Composio sync outright; leaving it after would run a loop against
- // an engine that is no longer there. Both are silent — the sync layer
- // reports "no connections", which is indistinguishable from a user who has
- // none — so the removal is ordered, and every step before the last has to
- // land first:
+ // The queue pool above moved into the module; **these two loops did not**,
+ // and the pinned release says so in its own words. `tinymemory` v1.5.0's
+ // `tinymemory-module/src/lib.rs` carries a section headed "The periodic
+ // sync loops are deliberately NOT started here" listing three reasons they
+ // cannot be: the pipeline reads Composio credentials off `Config` rather
+ // than off the `ComposioHost` seam, `global::client_if_ready()` is `None`
+ // inside the module, and `EngineRuntimeConfig::memory_sync_interval_secs()`
+ // answers `Some(0)` — "manual only" — so every tick would skip every
+ // source without logging anything.
//
- // 1. The host serves `ai.tinyhumans.tinymemory.ComposioHost` over the
- // module bus. Done — `modules/memory_host.rs`.
- // 2. The module installs a bus-backed `ComposioHost` seam, so engine code
- // running *inside* the module can reach this host's Composio client.
- // Without it `require_composio_host()` returns `Err` and `is_available`
- // reads `false`, which is the quiet failure above.
- // 3. The module starts the sync loop itself at load, because nothing in
- // the host will be able to. `tinymemory-module`'s `install_unserved_
- // seams` names this explicitly: the module starts none of the
- // background loops today; `queue::start`, `start_periodic_sync` and
- // `start_workspace_periodic_sync` are all called host-side.
- // 4. A `tinymemory` **release** carrying 2 and 3, and a re-pin of
- // `modules::registry` to its digest. The registry pins a released,
- // SHA-256-verified artifact, so until the re-pin the loaded module has
- // neither, however far ahead `vendor/tinymemory` is.
- // 5. Only then: delete this line, delete the shim at
- // `memory/sync/composio/mod.rs`, and delete the host's in-process
- // engine.
+ // So this line stays until an upstream release moves the loops, and the
+ // shim at `memory/sync/composio/mod.rs` stays with it. **Both failure modes
+ // here are silent**: removing the call stops Composio sync outright, and
+ // the sync layer reporting "no connections" is indistinguishable from a
+ // user who has none. The first symptom either way is somebody noticing
+ // their mail stopped being indexed weeks later.
if plan.composio_integration_sync {
log::debug!("[runtime.bootstrap] starting composio integration sync + source reconcile");
crate::openhuman::integrations::composio::start_periodic_sync();
diff --git a/src/openhuman/agent/debug/mod.rs b/src/openhuman/agent/debug/mod.rs
index 0a07cf720e..cfa2139725 100644
--- a/src/openhuman/agent/debug/mod.rs
+++ b/src/openhuman/agent/debug/mod.rs
@@ -234,9 +234,9 @@ async fn load_dump_config(
// `dump-all` invocation aborts before rendering a single prompt.
// Idempotent, so calling it per invocation is safe. Same rationale as
// `memory_cli` / `subconscious_cli`.
- crate::openhuman::memory::host_impls::install_memory_host_seams(std::sync::Arc::new(
- config.clone(),
- ));
+ // The seams are the module's to install now — this process embeds no
+ // engine, and the embedding seam a session agent needs is served back to
+ // the module over the bus by `modules::memory_host`.
Ok(config)
}
diff --git a/src/openhuman/agent/learning/linkedin_enrichment.rs b/src/openhuman/agent/learning/linkedin_enrichment.rs
index 990188285b..3f7c18b5f4 100644
--- a/src/openhuman/agent/learning/linkedin_enrichment.rs
+++ b/src/openhuman/agent/learning/linkedin_enrichment.rs
@@ -13,6 +13,8 @@
use crate::openhuman::config::Config;
use crate::openhuman::integrations::{build_client, IntegrationClient};
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use crate::openhuman::memory::api::types::{MemoryTaint, NamespaceDocumentInput};
use regex::Regex;
use serde_json::json;
use std::sync::{Arc, LazyLock};
@@ -193,13 +195,13 @@ pub async fn run_linkedin_enrichment(
tracing::info!(url = %url, "[linkedin_enrichment] stage 2: scraping LinkedIn profile via Apify");
result.log.push("Scraping LinkedIn profile...".into());
- // Build memory client once for all persist calls.
- let memory = match build_memory_client().await {
+ // Resolve the guarded memory driver once for all persist calls.
+ let memory = match profile_memory_writer().await {
Ok(m) => Some(m),
Err(e) => {
tracing::warn!(
error = %e,
- "[linkedin_enrichment] memory client init failed, skipping memory persistence"
+ "[linkedin_enrichment] memory driver unavailable, skipping memory persistence"
);
None
}
@@ -671,48 +673,104 @@ pub async fn scrape_linkedin_profile(
.ok_or_else(|| anyhow::anyhow!("Apify run returned an empty items array"))
}
-/// The process-wide memory client, for profile persistence.
+/// The namespace scraped LinkedIn profiles are persisted into.
///
-/// Deliberately **not** `MemoryClient::new_local()`. That constructor resolves
-/// `~/.openhuman/workspace` from the home directory and never consults
-/// `OPENHUMAN_WORKSPACE`, so on any host that scopes its workspace — every
-/// hosted tenant, and any local run with the variable set — the scraped profile
-/// was written to a store nothing else reads. It failed by *succeeding*, which
-/// is why nothing surfaced it.
-///
-/// It was also a second engine construction against the same data directory,
-/// which `memory::bypass_allowlist_tests` refuses for
-/// `MemoryClient::from_workspace_dir` on the grounds that it "risks a second
-/// ingestion worker on one store". `new_local` reaches the same constructor one
-/// call deeper, so it was the same hazard with none of the enforcement.
-///
-/// Resolved through `memory::ops::helpers::active_memory_client` rather than
-/// `global::client` directly, for two reasons beyond the one above.
+/// `MemoryClient::store_skill_sync("user-profile", ...)` derived this by
+/// prefixing the skill id with `skill-`; that derivation is one line of host
+/// policy, so it moves here rather than needing a contract member (#5560). The
+/// literal must not drift — it is what onboarding RAG recalls against.
+const PROFILE_MEMORY_NAMESPACE: &str = "skill-user-profile";
+
+/// The guarded memory driver's documents family, for profile persistence.
///
-/// It does not lose the write when startup wiring has not run: it falls back to
-/// `global::init(Config::load_or_init().workspace_dir)`, explicitly **not** to
-/// `~/.openhuman/workspace` — so it cannot reintroduce the bug this function
-/// exists to fix. Both entry points reach here inside a running daemon, so init
-/// has almost certainly happened; this is about which failure the remaining case
-/// gets, and silently dropping a scraped profile is the worse one.
+/// Deliberately **not** an engine constructor. `MemoryClient::new_local()`
+/// resolved `~/.openhuman/workspace` from the home directory and never
+/// consulted `OPENHUMAN_WORKSPACE`, so on any host that scopes its workspace —
+/// every hosted tenant, and any local run with the variable set — the scraped
+/// profile was written to a store nothing else reads. It failed by
+/// *succeeding*, which is why nothing surfaced it. It was also a second engine
+/// construction against the same data directory, the hazard
+/// `memory::bypass_allowlist_tests` refuses `MemoryClient::from_workspace_dir`
+/// for ("risks a second ingestion worker on one store").
///
-/// It also resolves the *same* workspace `write_profile_md` writes `PROFILE.md`
-/// into, since both now derive it from `Config`. Taking the global binding here
-/// left the two halves of `run_linkedin_enrichment` deriving their target from
-/// different sources, which can in principle disagree.
+/// `active_memory_guard` cannot reintroduce either: it resolves the ambient
+/// `CoreContext`'s workspace, falling back to `Config::load_or_init` — the
+/// *same* workspace `write_profile_md` writes `PROFILE.md` into, so the two
+/// halves of `run_linkedin_enrichment` cannot target different stores — and it
+/// hands back the one cached driver for that workspace rather than building
+/// anything.
///
/// The caller still treats an error as "skip persistence and warn", for the
/// genuine failures that remain.
-async fn build_memory_client() -> anyhow::Result<tinymemory_core::store::MemoryClientRef> {
- crate::openhuman::memory::ops::helpers::active_memory_client()
+async fn profile_memory_writer(
+) -> anyhow::Result<std::sync::Arc<crate::openhuman::memory::guard::MemoryGuard>> {
+ let guard = crate::openhuman::memory::ops::guard::active_memory_guard()
.await
- .map_err(|e| anyhow::anyhow!("memory client unavailable: {e}"))
+ .map_err(|e| anyhow::anyhow!("memory driver unavailable: {e}"))?;
+ if guard.as_documents().is_none() {
+ anyhow::bail!(
+ "memory driver `{}` does not support the documents family",
+ guard.driver_id()
+ );
+ }
+ Ok(guard)
+}
+
+/// Upsert one LinkedIn-derived document through the guarded documents family.
+///
+/// This is `MemoryClient::store_skill_sync`'s body, minus the engine: that
+/// method built exactly this `NamespaceDocumentInput` and handed it to
+/// `put_doc`, which is what `MemoryDocuments::put_document` resolves to on the
+/// embedded driver — same upsert, same background graph-extraction enqueue.
+/// `ExternalSync` is carried explicitly for the same reason `store_skill_sync`
+/// hard-coded it: a scraped third-party profile is not user-authored, and the
+/// subconscious gate reads that provenance off the persisted chunk.
+///
+/// The dedup key is the title, matching `store_skill_sync`'s `document_id: None`
+/// branch — LinkedIn enrichment has no stable upstream id to key on.
+async fn put_profile_document(
+ memory: &crate::openhuman::memory::guard::MemoryGuard,
+ title: String,
+ content: String,
+ source_type: &str,
+ priority: &str,
+ metadata: serde_json::Value,
+) -> anyhow::Result<()> {
+ let documents = memory.as_documents().ok_or_else(|| {
+ anyhow::anyhow!(
+ "memory driver `{}` does not support the documents family",
+ memory.driver_id()
+ )
+ })?;
+ tracing::debug!(
+ namespace = PROFILE_MEMORY_NAMESPACE,
+ source_type = source_type,
+ "[linkedin_enrichment] upserting profile document through the memory driver"
+ );
+ documents
+ .put_document(NamespaceDocumentInput {
+ namespace: PROFILE_MEMORY_NAMESPACE.to_string(),
+ key: title.clone(),
+ title,
+ content,
+ source_type: source_type.to_string(),
+ priority: priority.to_string(),
+ tags: Vec::new(),
+ metadata,
+ category: "core".to_string(),
+ session_id: None,
+ document_id: None,
+ taint: MemoryTaint::ExternalSync,
+ })
+ .await
+ .map(|_| ())
+ .map_err(|e| anyhow::anyhow!("memory store failed: {e}"))
}
/// Persist the full scraped LinkedIn profile to the user-profile memory
/// namespace so the agent has rich context about the user.
async fn persist_linkedin_profile(
- memory: &tinymemory_core::store::MemoryClient,
+ memory: &crate::openhuman::memory::guard::MemoryGuard,
url: &str,
data: &serde_json::Value,
) -> anyhow::Result<()> {
@@ -721,47 +779,35 @@ async fn persist_linkedin_profile(
serde_json::to_string_pretty(data).unwrap_or_else(|_| data.to_string())
);
- memory
- .store_skill_sync(
- "user-profile", // namespace skill_id
- "linkedin", // integration_id
- &format!("LinkedIn profile: {url}"),
- &content,
- Some("onboarding-linkedin-enrichment".into()),
- Some(json!({
- "source": "apify-linkedin-scraper",
- "url": url,
- "actor": LINKEDIN_SCRAPER_ACTOR,
- })),
- Some("high".into()),
- None, // created_at
- None, // updated_at
- None, // document_id
- )
- .await
- .map_err(|e| anyhow::anyhow!("memory store failed: {e}"))
+ put_profile_document(
+ memory,
+ format!("LinkedIn profile: {url}"),
+ content,
+ "onboarding-linkedin-enrichment",
+ "high",
+ json!({
+ "source": "apify-linkedin-scraper",
+ "url": url,
+ "actor": LINKEDIN_SCRAPER_ACTOR,
+ }),
+ )
+ .await
}
/// Fallback: persist just the LinkedIn URL when the full scrape fails.
async fn persist_linkedin_url_only(
- memory: &tinymemory_core::store::MemoryClient,
+ memory: &crate::openhuman::memory::guard::MemoryGuard,
url: &str,
) -> anyhow::Result<()> {
- memory
- .store_skill_sync(
- "user-profile",
- "linkedin",
- &format!("LinkedIn profile URL: {url}"),
- &format!("User LinkedIn profile: {url}"),
- Some("onboarding-linkedin-url".into()),
- Some(json!({ "source": "gmail-linkedin-extraction", "url": url })),
- Some("medium".into()),
- None, // created_at
- None, // updated_at
- None, // document_id
- )
- .await
- .map_err(|e| anyhow::anyhow!("memory store failed: {e}"))
+ put_profile_document(
+ memory,
+ format!("LinkedIn profile URL: {url}"),
+ format!("User LinkedIn profile: {url}"),
+ "onboarding-linkedin-url",
+ "medium",
+ json!({ "source": "gmail-linkedin-extraction", "url": url }),
+ )
+ .await
}
#[cfg(test)]
diff --git a/src/openhuman/agent/learning/startup.rs b/src/openhuman/agent/learning/startup.rs
index ba4e6a00b0..959ef0336d 100644
--- a/src/openhuman/agent/learning/startup.rs
+++ b/src/openhuman/agent/learning/startup.rs
@@ -29,8 +29,6 @@ use std::path::Path;
use std::sync::OnceLock;
use tinybus::SubscriptionHandle;
-use tinymemory_core::global::client_if_ready;
-use tinymemory_core::store::MemoryClientRef;
static EMAIL_SIG_HANDLE: OnceLock<Option<SubscriptionHandle>> = OnceLock::new();
@@ -53,13 +51,56 @@ pub fn register_learning_subscribers(workspace_dir: std::path::PathBuf) {
});
// Phase 3 + Phase 4 learning: rebuild trigger + periodic loop + the
- // ProfileMdRenderer. All three need the global memory client. The
- // client-dependent work is split into `register_with_client` so both the
- // ready and not-ready arms are unit-testable without touching process
- // globals.
+ // ProfileMdRenderer. All three need a bound memory driver. Readiness is
+ // resolved here and the dependent work is split into `register_with_memory`
+ // so both the ready and not-ready arms are unit-testable without touching
+ // process globals.
static CLIENT_HANDLES: OnceLock<(Option<SubscriptionHandle>, Option<SubscriptionHandle>)> =
OnceLock::new();
- CLIENT_HANDLES.get_or_init(|| register_with_client(client_if_ready(), &workspace_dir));
+ let memory_ready = memory_is_bindable(&workspace_dir);
+ CLIENT_HANDLES.get_or_init(|| register_with_memory(memory_ready, &workspace_dir));
+}
+
+/// Whether this workspace has a usable memory driver to register learning
+/// subscribers against.
+///
+/// This replaces `tinymemory_core::global::client_if_ready().is_some()` (#5560).
+/// The two ask the same question — "is memory reachable yet?" — of different
+/// things: the old call asked whether the in-process engine singleton had been
+/// initialised, which after #5560 nothing does at boot, so it would have
+/// answered `false` on every desktop start and silently taken learning down the
+/// #5003 skip path forever.
+///
+/// `binding::for_workspace` is synchronous, cached, and infallible by design —
+/// an inadmissible driver *falls back* rather than erroring — so the honest
+/// negative here is `MemoryBinding::disables_memory`: memory explicitly
+/// configured off, which is the one state in which a rebuild loop has nothing
+/// to rebuild against.
+fn memory_is_bindable(workspace_dir: &Path) -> bool {
+ use crate::openhuman::config::schema::MemorySubsystemConfig;
+ match crate::openhuman::memory::binding::for_workspace(
+ workspace_dir,
+ &MemorySubsystemConfig::default(),
+ ) {
+ Ok(binding) if binding.disables_memory() => {
+ tracing::warn!(
+ driver = %binding.driver_id(),
+ "[learning::startup] memory is disabled for this workspace — learning subscribers will not register"
+ );
+ false
+ }
+ Ok(binding) => {
+ tracing::debug!(
+ driver = %binding.driver_id(),
+ "[learning::startup] memory driver bound for learning subscribers"
+ );
+ true
+ }
+ Err(error) => {
+ tracing::warn!("[learning::startup] no memory binding for this workspace: {error}");
+ false
+ }
+ }
}
fn register_email_signature_once<F>(handle_cell: &OnceLock<Option<SubscriptionHandle>>, register: F)
@@ -109,32 +150,31 @@ fn facet_cache_for(
/// Returns `(rebuild_trigger_handle, profile_md_renderer_handle)`.
///
-/// When `client` is `Some`, both the Phase 3 rebuild trigger (plus its periodic
-/// 30-minute loop) and the Phase 4 `ProfileMdRenderer` are registered. When
-/// `client` is `None` (the memory client is not yet initialised) both are
+/// When `memory_ready` is true, both the Phase 3 rebuild trigger (plus its
+/// periodic 30-minute loop) and the Phase 4 `ProfileMdRenderer` are registered.
+/// When it is false (this workspace has no usable memory driver) both are
/// skipped and the skip is logged at **warn** — the *silent* skip was the #5003
/// bug, so this must be loud.
///
-/// Taking the client as a parameter (rather than reading
-/// `memory::global::client_if_ready()` internally) keeps both arms testable
-/// without initialising the process-global memory singleton.
-fn register_with_client(
- client: Option<MemoryClientRef>,
+/// Taking readiness as a parameter (rather than resolving the binding
+/// internally) keeps both arms testable without touching process globals; it was
+/// an `Option<MemoryClientRef>` for the same reason before #5560, and the client
+/// itself was never used for anything but its presence.
+fn register_with_memory(
+ memory_ready: bool,
workspace_dir: &Path,
) -> (Option<SubscriptionHandle>, Option<SubscriptionHandle>) {
- let Some(_client) = client else {
+ if !memory_ready {
tracing::warn!(
- "[learning::scheduler] memory client not ready at boot — skipping event-trigger + \
- periodic-rebuild registration; learning rebuilds will not fire until the client \
- initialises (#5003)"
+ "[learning::scheduler] no memory driver for this workspace — skipping event-trigger + \
+ periodic-rebuild registration; learning rebuilds will not fire (#5003)"
);
tracing::warn!(
- "[learning::profile_md_renderer] memory client not ready at boot — skipping \
- ProfileMdRenderer registration; PROFILE.md will not be re-rendered until the client \
- initialises (#5003)"
+ "[learning::profile_md_renderer] no memory driver for this workspace — skipping \
+ ProfileMdRenderer registration; PROFILE.md will not be re-rendered (#5003)"
);
return (None, None);
- };
+ }
// Phase 3 learning: event-driven rebuild trigger + periodic 30-minute loop.
let rebuild_trigger = {
@@ -198,27 +238,21 @@ mod tests {
use crate::openhuman::agent::learning::extract::signature::{
parse_signature, register_email_signature_subscriber_on,
};
- use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
- use tinymemory_core::store::MemoryClient;
- /// Build a real `MemoryClient` against a fresh temp workspace. The temp dir
- /// is returned so callers keep it alive for the client's lifetime.
- fn test_client() -> (TempDir, MemoryClientRef) {
- // Building a real `MemoryClient` needs the host seams wired — an
- // unwired embedding host fails loudly by design. This module never
- // installed them, so it passed only when some *other* test in the same
- // binary happened to run first; alone, or filtered to this module, it
- // failed. `install_for_tests` is `Once`-guarded, so calling it here is
- // free when another test already has.
+ /// A fresh temp workspace for the ready-arm test.
+ ///
+ /// This used to build a real `MemoryClient` and hand it to
+ /// `register_with_client`, which never used it for anything but its
+ /// presence. Readiness is a `bool` now (#5560), so the fixture is just the
+ /// directory — but the host seams still have to be installed, because
+ /// `memory_is_bindable` and the facet cache below both resolve a driver and
+ /// an unwired embedding host fails loudly by design. `install_for_tests` is
+ /// `Once`-guarded, so calling it here is free when another test already has.
+ fn test_workspace() -> TempDir {
crate::openhuman::memory::host_impls::install_for_tests();
- let tmp = TempDir::new().expect("tempdir");
- let client = Arc::new(
- MemoryClient::from_workspace_dir(tmp.path().join("workspace"))
- .expect("client should initialise against a fresh workspace"),
- );
- (tmp, client)
+ TempDir::new().expect("tempdir")
}
/// A body whose trailing lines form a clear email signature — yields several
@@ -259,29 +293,29 @@ mod tests {
}
#[tokio::test]
- async fn register_with_client_registers_both_handles_when_ready() {
+ async fn register_with_memory_registers_both_handles_when_ready() {
crate::core::bus::init().await.expect("bus init");
- let (tmp, client) = test_client();
- let (trigger, renderer) = register_with_client(Some(client), tmp.path());
+ let tmp = test_workspace();
+ let (trigger, renderer) = register_with_memory(true, tmp.path());
assert!(
trigger.is_some(),
- "rebuild trigger must register when the memory client is ready"
+ "rebuild trigger must register when memory is available"
);
assert!(
renderer.is_some(),
- "ProfileMdRenderer must register when the memory client is ready"
+ "ProfileMdRenderer must register when memory is available"
);
}
#[tokio::test]
- async fn register_with_client_skips_and_warns_when_client_absent() {
- // No memory client → both client-dependent subscribers are skipped and
+ async fn register_with_memory_skips_and_warns_when_memory_absent() {
+ // No memory driver → both memory-dependent subscribers are skipped and
// the (now loud) warn path is exercised. This is the else-arm the #5003
// fix upgraded from a silent debug-level skip.
let tmp = TempDir::new().expect("tempdir");
- let (trigger, renderer) = register_with_client(None, tmp.path());
- assert!(trigger.is_none(), "no trigger without a client");
- assert!(renderer.is_none(), "no renderer without a client");
+ let (trigger, renderer) = register_with_memory(false, tmp.path());
+ assert!(trigger.is_none(), "no trigger without a memory driver");
+ assert!(renderer.is_none(), "no renderer without a memory driver");
}
#[tokio::test]
diff --git a/src/openhuman/channels/runtime/startup.rs b/src/openhuman/channels/runtime/startup.rs
index 4dcd5cdfd0..63b9676d67 100644
--- a/src/openhuman/channels/runtime/startup.rs
+++ b/src/openhuman/channels/runtime/startup.rs
@@ -38,9 +38,27 @@ use anyhow::Result;
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
-use tinymemory_core::store as memory_store;
use tokio::sync::mpsc;
+/// What the channel-server banner prints on its `🧠 Memory:` line.
+///
+/// This used to call `tinymemory_core::store::effective_memory_backend_name(
+/// &config.memory.backend, Some(&config.storage.provider.config))`, which is
+/// how it reads in `git log` — as if the label were derived from those two
+/// settings. It never was: that function ignores **both** arguments and
+/// returns the literal `"namespace"` unconditionally (`tinymemory-core`
+/// `store/factories.rs`, and its own doc says so — "Currently, this always
+/// returns 'namespace' as the unified memory system is the standard"). Its
+/// engine-side test is named `effective_memory_backend_name_always_returns_
+/// namespace`.
+///
+/// So this is a display constant, not a capability, and it came home rather
+/// than crossing the bus (openhuman#5560): "which label does the banner show"
+/// is not something a second memory driver would answer differently, and
+/// widening the contract for a fixed string would be the worst of both. The
+/// printed line is byte-identical to before.
+const EFFECTIVE_MEMORY_BACKEND_LABEL: &str = "namespace";
+
/// How the channels runtime should construct its default chat provider.
///
/// Issue #3098 sub-issue 1: the runtime used to ignore the per-workload
@@ -645,13 +663,9 @@ pub async fn start_channels(mut config: Config) -> Result<()> {
println!("🦀 OpenHuman Channel Server");
println!(" 🤖 Model: {model}");
- let effective_backend = memory_store::effective_memory_backend_name(
- &config.memory.backend,
- Some(&config.storage.provider.config),
- );
println!(
" 🧠 Memory: {} (auto-save: {})",
- effective_backend,
+ EFFECTIVE_MEMORY_BACKEND_LABEL,
if config.memory.auto_save { "on" } else { "off" }
);
println!(
diff --git a/src/openhuman/config/migration_helpers/core.rs b/src/openhuman/config/migration_helpers/core.rs
index ddf6f1258d..c93860d30e 100644
--- a/src/openhuman/config/migration_helpers/core.rs
+++ b/src/openhuman/config/migration_helpers/core.rs
@@ -118,6 +118,28 @@ pub async fn migrate_openclaw_memory(
})
}
+/// The memory the import writes into.
+///
+/// **Still the engine's own migration constructor, and #5560 could not change
+/// that.** The contract's only door for this shape is `MemoryCore::store`,
+/// reached through `MemoryGuard` like every other write in the tree — and the
+/// guard applies `MemoryHooksConfig::capture_max_chars`, which defaults to
+/// **500**, to every `store` body (`guard::mandatory`, step 6). An OpenClaw /
+/// Hermes `MEMORY.md` entry is routinely longer than that, so routing the
+/// import through the guard would silently truncate the user's own imported
+/// memories: data loss on a migration path, which is worse than the second
+/// engine handle this keeps.
+///
+/// The other two doors do not fit either. `MemoryDocuments::put_document` does
+/// not trim, but it writes namespace *documents* rather than memory entries, so
+/// the `get`/rename dedupe above would stop seeing what it wrote.
+/// `MemoryPortability::import_records` is the shape a migration wants, but
+/// `ExportRecord::payload` is explicitly "the exporting driver's own shape" —
+/// synthesising one host-side means encoding driver-private structure here.
+///
+/// What unblocks this is a capture budget that distinguishes an *import* from
+/// an auto-capture, or a `MemoryCore::store` variant that opts out of the
+/// budget. Both are upstream asks, not host changes.
fn target_memory_backend(config: &Config) -> Result<Box<dyn Memory>> {
memory_store::create_memory_for_migration(&config.memory, &config.workspace_dir)
}
diff --git a/src/openhuman/desktop/app_state/ops.rs b/src/openhuman/desktop/app_state/ops.rs
index d1b9626b35..420102a17b 100644
--- a/src/openhuman/desktop/app_state/ops.rs
+++ b/src/openhuman/desktop/app_state/ops.rs
@@ -523,11 +523,15 @@ async fn finish_revalidated_user_activation(
user_id: &str,
service_rebind_source: Option<&Config>,
) {
- if let Err(error) = tinymemory_core::global::init(target_config.workspace_dir.clone()) {
- warn!(
- "{LOG_PREFIX} failed to bind memory client after pending session revalidation: {error}"
- );
- }
+ // ── No explicit memory re-point here any more (#5560) ──────────────────
+ //
+ // This was `tinymemory_core::global::init(...)`, the in-process engine's
+ // process-global slot, which had to be re-pointed by hand at every
+ // activation site or it kept writing into the previous workspace.
+ // `memory::binding` is keyed on (workspace, `[subsystems.memory]`), and the
+ // context rebind immediately below re-points both — so memory follows it by
+ // construction. `CoreContext::memory_binding`'s docs state this property as
+ // the reason these sites need no memory call of their own.
if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(
&target_config.workspace_dir,
target_config.subsystems.memory.clone(),
diff --git a/src/openhuman/inference/embeddings/provider_trait.rs b/src/openhuman/inference/embeddings/provider_trait.rs
index b4402f5cb5..44bb7116f0 100644
--- a/src/openhuman/inference/embeddings/provider_trait.rs
+++ b/src/openhuman/inference/embeddings/provider_trait.rs
@@ -10,12 +10,87 @@
//! Every existing `inference::embeddings::EmbeddingProvider` path in this crate
//! keeps resolving, and keeps naming the same type.
//!
-//! [`TinyAgentsEmbeddingProvider`], the adapter from tinyagents' own
-//! embedding-model trait, is re-exported from `tinymemory_core`. It cannot live
-//! in the contract crate, which must not depend on tinyagents; and it cannot
-//! live here, because the summary tree's embedder factory is core code that
-//! builds Ollama models directly and has to wrap them. `tinymemory-core` is the
-//! one crate that can name both sides.
+//! # [`TinyAgentsEmbeddingProvider`] is the host's, not the engine's (#5560)
+//!
+//! This adapter used to be `pub use tinymemory_core::embedding_adapter::…`, on
+//! the reasoning that it could not live in the contract crate (which must not
+//! depend on `tinyagents`) and could not live here either, because the memory
+//! tree's embedder factory — engine code — also needed to wrap a `tinyagents`
+//! model. `tinymemory-core` was the one crate that could name both sides.
+//!
+//! Only the first half of that was ever a constraint on *this* crate. The host
+//! already depends on `tinyagents` directly — every construction site
+//! (`factory.rs`, `cloud_adapter.rs`) builds a `tinyagents` `EmbeddingModel` and
+//! wraps it here — so the adapter is 40 lines of glue between two dependencies
+//! this crate already has, and reaching it through the engine crate was the only
+//! thing keeping `tinymemory-core` linked for it.
+//!
+//! The engine keeps its own copy for its own factory. That is not duplication of
+//! *state*: the adapter is a stateless newtype over a boxed trait object, both
+//! sides wrap the same `tinyagents::harness::embeddings::EmbeddingModel` (one
+//! crate — the root `[patch.crates-io]` points every consumer at
+//! `vendor/tinyagents`), and both produce the same
+//! `tinymemory_api::host::EmbeddingProvider`. Nothing reads the other's output,
+//! which is the same shape the scrubbers, `util::redact` and
+//! `memory::obsidian_registry` took when they came home.
+//!
+//! The signature is load-bearing and is **not** re-derived here:
+//! [`format_embedding_signature`] stays the contract's, so a vector written
+//! before this move and one written after land in the same embedding space.
+
+use async_trait::async_trait;
+use tinyagents::harness::embeddings::EmbeddingModel;
pub use tinymemory_api::host::{format_embedding_signature, EmbeddingProvider};
-pub use tinymemory_core::embedding_adapter::TinyAgentsEmbeddingProvider;
+
+/// Compatibility adapter from the canonical tinyagents embedding model.
+pub struct TinyAgentsEmbeddingProvider {
+ model: Box<dyn EmbeddingModel>,
+}
+
+impl TinyAgentsEmbeddingProvider {
+ pub fn new(model: impl EmbeddingModel + 'static) -> Self {
+ Self {
+ model: Box::new(model),
+ }
+ }
+
+ pub fn boxed(model: impl EmbeddingModel + 'static) -> Box<dyn EmbeddingProvider> {
+ Box::new(Self::new(model))
+ }
+}
+
+#[async_trait]
+impl EmbeddingProvider for TinyAgentsEmbeddingProvider {
+ fn name(&self) -> &str {
+ self.model.name()
+ }
+
+ fn model_id(&self) -> &str {
+ self.model.model_id()
+ }
+
+ fn dimensions(&self) -> usize {
+ self.model.dimensions()
+ }
+
+ fn signature(&self) -> String {
+ self.model.signature()
+ }
+
+ /// The one shape difference between the two traits: the contract takes
+ /// `&[&str]` and `EmbeddingModel` takes `&[String]`, so the batch is owned
+ /// here. Kept verbatim from the engine-side adapter this replaces — a
+ /// "cheaper" variant that embedded one text at a time would turn one
+ /// provider request into N.
+ async fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
+ let owned = texts
+ .iter()
+ .map(|text| (*text).to_owned())
+ .collect::<Vec<_>>();
+ self.model
+ .embed(&owned)
+ .await
+ .map_err(|error| anyhow::anyhow!(error))
+ }
+}
diff --git a/src/openhuman/integrations/composio/ops/connections.rs b/src/openhuman/integrations/composio/ops/connections.rs
index 6dbee2d2bf..5599dc9b99 100644
--- a/src/openhuman/integrations/composio/ops/connections.rs
+++ b/src/openhuman/integrations/composio/ops/connections.rs
@@ -163,17 +163,15 @@ pub async fn composio_delete_connection(
Err(_) => None,
};
let memory_targets = if clear_memory {
- // The LIVE process client — target discovery loads notion sync state
- // through it. Resolved here, not constructed inside the discovery:
- // `MemoryClient::from_workspace_dir` starts an ingestion worker at
- // construction, so building one per delete put a second worker on the
- // live store every time.
- let memory = crate::openhuman::memory::ops::helpers::active_memory_client()
- .await
- .map_err(|error| {
- format!("[composio] delete_connection cannot resolve the memory client: {error}")
- })?;
- composio_memory_targets_for_connection(&memory, toolkit.as_deref(), connection_id)
+ // Target discovery takes the config and resolves the bound driver
+ // itself — the notion arm reads sync state through the driver's `Graph`
+ // family. This used to resolve the LIVE in-process client here
+ // (`memory::ops::helpers::active_memory_client`) and hand it down;
+ // openhuman#5560 deleted that engine, and the binding is what replaced
+ // it. Discovery still refuses before the connection is deleted rather
+ // than after, so a memory store this host cannot reach aborts the
+ // delete instead of orphaning the user's synced pages.
+ composio_memory_targets_for_connection(config, toolkit.as_deref(), connection_id)
.await
.map_err(|error| {
format!("[composio] delete_connection cannot enumerate memory targets: {error:#}")
diff --git a/src/openhuman/integrations/composio/ops/memory_cleanup.rs b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
index 29dd677b51..c3b77b6a0e 100644
--- a/src/openhuman/integrations/composio/ops/memory_cleanup.rs
+++ b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
@@ -1,11 +1,18 @@
//! Memory cleanup helpers used when deleting a Composio connection.
-use std::sync::Arc;
-
use crate::openhuman::config::Config;
+use crate::openhuman::memory::binding::MemoryBinding;
use tinymemory_api::chunks::SourceKind;
use tinymemory_api::provider::ForgetSelector;
-use tinymemory_core::store::MemoryClientRef;
+
+/// KV namespace the Composio sync pipelines keep their per-connection cursor
+/// state under.
+///
+/// `tinycortex`'s `memory::sync::state::STATE_NAMESPACE`, which
+/// `tinymemory-core`'s `sync_state::KV_NAMESPACE` aliases — one namespace, two
+/// crates naming it, and the row this module reads is written by whichever of
+/// them ran the last sync.
+const SYNC_STATE_NAMESPACE: &str = "composio-sync-state";
/// One thing a connection delete has to remove from memory.
///
@@ -104,20 +111,38 @@ impl MemoryCleanupTarget {
}
}
-/// `memory` is the caller's handle on the live store — the RPC path resolves
-/// the process client, tests pass one bound to their own workspace. Taken as a
-/// parameter rather than constructed here: `MemoryClient::from_workspace_dir`
-/// starts an ingestion worker at construction, so building one per
-/// connection-delete put a second worker on the live store every time — the
-/// exact hazard `memory::bypass_allowlist_tests` names for that constructor.
+/// Enumerate what a connection delete has to remove, for one toolkit.
+///
+/// **Takes a `&Config`, not a memory handle, and that is the openhuman#5560
+/// change.** This used to take `&MemoryClientRef` — the caller's handle on the
+/// live in-process store — because the notion arm loaded sync state through
+/// `tinymemory_core::tinycortex::HostSyncAdapter`. That adapter is two lines
+/// (`kv_get` / `kv_set` on the client), the contract's `MemoryGraph` serves
+/// exactly those, and the in-process engine is gone — so the read goes over the
+/// bus and the parameter became the config the binding is keyed on.
+///
+/// The old signature's warning still applies to whoever is tempted to construct
+/// a client here instead: `MemoryClient::from_workspace_dir` starts an
+/// ingestion worker at construction, so building one per connection-delete put
+/// a second worker on the live store every time — the hazard
+/// `memory::bypass_allowlist_tests` names for that constructor. The binding is
+/// a workspace-keyed cache and starts nothing.
+///
+/// The binding is resolved here rather than inside the notion arm so the
+/// ordering the caller had is preserved: `composio_delete_connection` resolved
+/// the memory handle **before** target discovery and refused the whole delete
+/// if it could not, rather than deleting the connection and then discovering
+/// memory was unreachable.
pub(crate) async fn composio_memory_targets_for_connection(
- memory: &MemoryClientRef,
+ config: &Config,
toolkit: Option<&str>,
connection_id: &str,
) -> anyhow::Result<Vec<MemoryCleanupTarget>> {
let Some(toolkit) = toolkit.map(str::trim).filter(|s| !s.is_empty()) else {
return Ok(Vec::new());
};
+ let binding = crate::openhuman::memory::binding::for_config(config)
+ .map_err(|error| anyhow::anyhow!("memory driver unavailable: {error}"))?;
let targets = match toolkit.to_ascii_lowercase().as_str() {
"slack" => vec![MemoryCleanupTarget::Exact(
@@ -125,7 +150,7 @@ pub(crate) async fn composio_memory_targets_for_connection(
format!("slack:{connection_id}"),
)],
"gmail" => gmail_memory_sources_for_connection(connection_id),
- "notion" => notion_memory_targets_for_connection(memory, connection_id).await?,
+ "notion" => notion_memory_targets_for_connection(&binding, connection_id).await?,
"drive" | "googledrive" | "google_drive" => {
drive_memory_targets_for_connection(connection_id)
}
@@ -143,19 +168,58 @@ fn gmail_memory_sources_for_connection(connection_id: &str) -> Vec<MemoryCleanup
]
}
+/// Notion files one memory document per synced page, so the delete has to know
+/// which pages this connection ever synced — that list lives in the sync
+/// pipeline's own KV row, not in any chunk.
+///
+/// Read through the contract's `Graph` family. The three outcomes are kept
+/// exactly as `SyncState::load` had them, because the caller's contract is
+/// "every page this connection synced, or an error":
+///
+/// - **no row** → an empty synced set, same as `SyncState::new`. A connection
+/// that never synced has nothing extra to forget.
+/// - **a row that will not deserialise** → `Err`, *not* an empty set. A corrupt
+/// cursor means the page list is unknown, and reporting "nothing to delete"
+/// would leave a disconnected account's pages in memory while telling the
+/// user they were removed. `notion_cleanup_targets_surface_corrupt_sync_state`
+/// pins the message.
+/// - **a driver with no `Graph` family** → `Err`, for the same reason.
+///
+/// All three failures render through [`sync_state_load_error`] so they stay one
+/// message to the caller, exactly as they were when `SyncState::load` produced
+/// all three itself.
async fn notion_memory_targets_for_connection(
- memory: &MemoryClientRef,
+ binding: &MemoryBinding,
connection_id: &str,
) -> anyhow::Result<Vec<MemoryCleanupTarget>> {
let mut targets = connection_scoped_document_targets("notion", connection_id);
- let adapter = tinymemory_core::tinycortex::HostSyncAdapter::new(Arc::clone(memory));
- let state = tinycortex::memory::sync::SyncState::load(&adapter, "notion", connection_id)
+ let Some(graph) = binding.provider().as_graph() else {
+ return Err(sync_state_load_error(format!(
+ "driver '{}' does not serve Graph",
+ binding.driver_id()
+ )));
+ };
+ let key = format!("notion:{connection_id}");
+ let record = graph
+ .kv_get(Some(SYNC_STATE_NAMESPACE), &key)
.await
- .map_err(|error| {
- anyhow::anyhow!("failed to load notion sync state for memory cleanup: {error}")
- })?;
- for raw_id in state.synced_ids {
+ .map_err(sync_state_load_error)?;
+ let synced_ids = match record {
+ Some(record) => {
+ serde_json::from_value::<tinycortex::memory::sync::SyncState>(record.value)
+ .map_err(sync_state_load_error)?
+ .synced_ids
+ }
+ None => {
+ log::debug!(
+ "[composio][memory] no notion sync state for connection (driver='{}'); no page targets",
+ binding.driver_id()
+ );
+ Default::default()
+ }
+ };
+ for raw_id in synced_ids {
let Some(page_id) = notion_synced_page_id(&raw_id) else {
continue;
};
@@ -172,6 +236,17 @@ async fn notion_memory_targets_for_connection(
Ok(dedupe_memory_targets(targets))
}
+/// The one message the notion sync-state read reports, whatever went wrong.
+///
+/// `notion_cleanup_targets_surface_corrupt_sync_state` asserts on the
+/// `"failed to load notion sync state"` prefix, and the caller in
+/// `composio_delete_connection` renders it into a user-facing "cannot enumerate
+/// memory targets" refusal — so the wording is load-bearing in both directions
+/// and is kept identical to the one `SyncState::load`'s caller used to build.
+fn sync_state_load_error(detail: impl std::fmt::Display) -> anyhow::Error {
+ anyhow::anyhow!("failed to load notion sync state for memory cleanup: {detail}")
+}
+
fn drive_memory_targets_for_connection(connection_id: &str) -> Vec<MemoryCleanupTarget> {
["drive", "googledrive", "google_drive"]
.into_iter()
diff --git a/src/openhuman/integrations/composio/ops/mod.rs b/src/openhuman/integrations/composio/ops/mod.rs
index 11cf8ae4db..b4795a8f4b 100644
--- a/src/openhuman/integrations/composio/ops/mod.rs
+++ b/src/openhuman/integrations/composio/ops/mod.rs
@@ -21,6 +21,7 @@
//! | `triggers` | GitHub repos + trigger CRUD + trigger history |
//! | `providers_ops` | `composio_get_user_profile`, `_refresh_...`, `composio_sync` |
//! | `direct_mode` | `composio_get_mode`, `composio_set_api_key`, `_clear_...` |
+//! | `user_scopes` | per-toolkit agent scope prefs, over the bound memory driver |
mod connections;
mod direct_mode;
@@ -31,6 +32,7 @@ mod providers_ops;
mod toolkits;
mod tools_ops;
mod triggers;
+mod user_scopes;
// ── Public re-exports (match original ops.rs public surface) ───────────────
@@ -51,6 +53,12 @@ pub use triggers::{
composio_list_available_triggers, composio_list_github_repos, composio_list_trigger_history,
composio_list_triggers,
};
+// The `composio.{get,set}_user_scopes` handlers' storage half. Host code now —
+// it was `tinymemory_core::sync::composio::providers::user_scopes` reached
+// through the in-process engine handle until openhuman#5560; see the module.
+pub(crate) use user_scopes::{
+ load_or_default as load_user_scope_pref, save as save_user_scope_pref,
+};
// ── Re-export connected_integrations public items ──────────────────────────
// (originally at the bottom of ops.rs)
diff --git a/src/openhuman/integrations/composio/ops/user_scopes.rs b/src/openhuman/integrations/composio/ops/user_scopes.rs
new file mode 100644
index 0000000000..3e425d8ff6
--- /dev/null
+++ b/src/openhuman/integrations/composio/ops/user_scopes.rs
@@ -0,0 +1,189 @@
+//! Per-toolkit agent scope preferences, read and written through the bound
+//! memory driver.
+//!
+//! # Why this is host code now
+//!
+//! The two `composio.{get,set}_user_scopes` handlers used to reach
+//! `tinymemory_core::sync::composio::providers::user_scopes::{load_or_default,
+//! save}` — engine functions taking a `&MemoryClientRef`, resolved from the
+//! host's in-process `global` slot. openhuman#5560 deletes that second engine,
+//! so both calls had to move. Neither is a capability a second memory driver
+//! would answer differently: they are two rows in the driver's key/value tier,
+//! which the contract already exposes as [`MemoryGraph`]. So the *policy* came
+//! home and the *storage* went over the bus, exactly as `memory::safety` and
+//! `util::redact` did — no contract member was added.
+//!
+//! # The storage shape is the engine's, byte for byte
+//!
+//! The namespace, the key derivation and the serialised value below are copied
+//! from `tinymemory-core`'s `user_scopes.rs` rather than re-invented, because
+//! **this host is not the only reader**. Engine code still consults the same
+//! rows to gate tool calls by scope, and it now runs inside the loaded module.
+//! A key this host lower-cased differently, or a namespace one character off,
+//! would not fail — it would read as "no preference stored" and silently hand
+//! the agent the default (`read+write`, no `admin`) while the user's saved
+//! choice sat one key away. `user_scopes_storage_shape_matches_the_engine`
+//! pins the three constants against that.
+
+use serde_json::Value;
+
+use crate::openhuman::config::Config;
+
+/// The stored type, still the engine's.
+///
+/// Named through `integrations::composio::providers` — the host's re-export of
+/// the engine's provider vocabulary — rather than redeclared here. `ToolScope`
+/// gating, the catalogue and the RPC reply all read this exact struct, and a
+/// host-side twin would be a second serde shape over one row. It is the wire
+/// shape of both handlers' replies, so it must not be swapped for a look-alike.
+pub(crate) use crate::openhuman::integrations::composio::providers::UserScopePref;
+
+/// KV namespace holding one row per toolkit.
+///
+/// `tinymemory-core`'s `user_scopes::KV_NAMESPACE`. Deliberately distinct from
+/// `composio-sync-state`, so prefs and sync cursors never collide.
+const KV_NAMESPACE: &str = "composio-user-scopes";
+
+/// The row key for a toolkit — trimmed and ASCII-lowercased.
+///
+/// `tinymemory-core`'s `user_scopes::kv_key`. Both RPC handlers reach here
+/// through `read_required_non_empty`, which has already rejected an
+/// all-whitespace toolkit, so the empty-key arm those engine functions carry
+/// cannot be reached from the RPC surface; it is still handled rather than
+/// assumed away, because a future caller need not come through that helper.
+fn kv_key(toolkit: &str) -> String {
+ toolkit.trim().to_ascii_lowercase()
+}
+
+/// The scope pref stored for `toolkit`, or the default when none is.
+///
+/// **This read fails open, and that is inherited behaviour, not a new
+/// decision.** The engine's `load` documented it: "the agent should always be
+/// able to use connected integrations productively, even if pref storage is
+/// temporarily unavailable". Every failure mode — no driver, no `Graph` family,
+/// a backend error, a row that will not deserialise — lands on the same default
+/// (`read+write`, no `admin`) that a user who has never opened the toggle gets.
+/// Each is logged with its own reason so "defaulted because nothing is stored"
+/// stays distinguishable from "defaulted because the store is down".
+///
+/// The opposite choice would be worse: a failed read is not evidence that the
+/// user revoked anything, and refusing every integration on a transient KV
+/// error would break a working app to protect a preference it could not see.
+/// The **write** below does not fail open — see [`save`].
+pub(crate) async fn load_or_default(config: &Config, toolkit: &str) -> UserScopePref {
+ let key = kv_key(toolkit);
+ if key.is_empty() {
+ return UserScopePref::default();
+ }
+
+ let binding = match crate::openhuman::memory::binding::for_config(config) {
+ Ok(binding) => binding,
+ Err(error) => {
+ tracing::warn!(
+ toolkit = %key,
+ %error,
+ "[composio][scopes] memory driver unavailable, using default pref (read+write)"
+ );
+ return UserScopePref::default();
+ }
+ };
+ let Some(graph) = binding.provider().as_graph() else {
+ tracing::warn!(
+ toolkit = %key,
+ driver = binding.driver_id(),
+ "[composio][scopes] driver does not serve Graph, using default pref (read+write)"
+ );
+ return UserScopePref::default();
+ };
+
+ match graph.kv_get(Some(KV_NAMESPACE), &key).await {
+ Ok(Some(record)) => match serde_json::from_value::<UserScopePref>(record.value) {
+ Ok(pref) => {
+ tracing::debug!(
+ toolkit = %key,
+ read = pref.read,
+ write = pref.write,
+ admin = pref.admin,
+ "[composio][scopes] pref loaded"
+ );
+ pref
+ }
+ Err(error) => {
+ tracing::warn!(
+ toolkit = %key,
+ %error,
+ "[composio][scopes] pref deserialize failed, falling back to default"
+ );
+ UserScopePref::default()
+ }
+ },
+ Ok(None) => {
+ tracing::debug!(
+ toolkit = %key,
+ "[composio][scopes] no pref stored, using default (read+write)"
+ );
+ UserScopePref::default()
+ }
+ Err(error) => {
+ tracing::warn!(
+ toolkit = %key,
+ %error,
+ "[composio][scopes] kv_get failed, falling back to default"
+ );
+ UserScopePref::default()
+ }
+ }
+}
+
+/// Persist the scope pref for `toolkit`.
+///
+/// **This one fails closed.** A write that reported success without storing
+/// anything would leave the user looking at a toggle they just moved while the
+/// agent kept the old permissions — and the next read, which fails open, would
+/// confirm the stale value rather than contradict it. Every failure is an
+/// `Err` the RPC surfaces.
+///
+/// # Errors
+///
+/// An empty toolkit, an unresolvable driver, a driver with no `Graph` family,
+/// or a backend write failure.
+pub(crate) async fn save(
+ config: &Config,
+ toolkit: &str,
+ pref: UserScopePref,
+) -> Result<(), String> {
+ let key = kv_key(toolkit);
+ if key.is_empty() {
+ return Err("user_scopes: toolkit must not be empty".to_string());
+ }
+ let value: Value = serde_json::to_value(pref)
+ .map_err(|e| format!("[composio][scopes] serialize failed: {e}"))?;
+
+ let binding = crate::openhuman::memory::binding::for_config(config)
+ .map_err(|e| format!("[composio][scopes] memory driver unavailable: {e}"))?;
+ let Some(graph) = binding.provider().as_graph() else {
+ return Err(format!(
+ "[composio][scopes] driver '{}' does not serve Graph, cannot persist pref",
+ binding.driver_id()
+ ));
+ };
+
+ graph
+ .kv_put(Some(KV_NAMESPACE), &key, value)
+ .await
+ .map_err(|e| format!("[composio][scopes] kv_put failed: {e}"))?;
+
+ tracing::info!(
+ toolkit = %key,
+ read = pref.read,
+ write = pref.write,
+ admin = pref.admin,
+ driver = binding.driver_id(),
+ "[composio][scopes] pref saved"
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "user_scopes_tests.rs"]
+mod tests;
diff --git a/src/openhuman/integrations/composio/ops/user_scopes_tests.rs b/src/openhuman/integrations/composio/ops/user_scopes_tests.rs
new file mode 100644
index 0000000000..d01ac4f02f
--- /dev/null
+++ b/src/openhuman/integrations/composio/ops/user_scopes_tests.rs
@@ -0,0 +1,88 @@
+//! Pins the host copy of the scope-pref storage shape.
+//!
+//! These constants were copied out of `tinymemory-core` when the two RPC
+//! handlers stopped reaching the in-process engine (openhuman#5560). The engine
+//! still reads the same rows to gate tool calls by scope, and it now runs
+//! inside the loaded module — so drift between the two spellings does not
+//! fail. It reads as "no preference stored" and hands the agent the permissive
+//! default while the user's saved choice sits one key away: a permission bug
+//! that looks like a working app. Hence a test rather than a comment.
+//!
+//! **What this can and cannot check, stated rather than implied.**
+//! `tinymemory-core`'s own `user_scopes::KV_NAMESPACE` is a private `const`, so
+//! there is no way to assert the two strings equal from here. What *is* public
+//! is the sibling `sync_state::KV_NAMESPACE`, and the engine's doc is explicit
+//! that the two must differ ("Separate from `composio-sync-state` so the two
+//! never collide") — so that is the half asserted against the engine, and the
+//! literal is asserted against itself. A round-trip test (engine writes, host
+//! constants read it back) would be strictly stronger and is the thing to add
+//! when a test-support seam for building an in-process client exists again;
+//! `memory::host_impls::install_for_tests` was that seam and left with the
+//! second engine.
+//!
+//! The engine path below resolves because `tinymemory-core` is a
+//! **dev-dependency** of this crate (`Cargo.toml`); production code in
+//! `user_scopes.rs` names neither it nor any engine item.
+
+use super::*;
+
+use tinymemory_core::sync::composio::providers::sync_state as engine_sync_state;
+
+/// The scopes namespace is the literal the engine writes, and it is not the
+/// sync-state namespace.
+///
+/// If either constant ever moved onto the other, prefs and Composio sync
+/// cursors would overwrite each other row for row.
+#[test]
+fn user_scopes_namespace_is_the_engine_literal_and_not_sync_state() {
+ assert_eq!(
+ KV_NAMESPACE, "composio-user-scopes",
+ "must stay the literal tinymemory-core's user_scopes::KV_NAMESPACE holds"
+ );
+ assert_ne!(
+ KV_NAMESPACE,
+ engine_sync_state::KV_NAMESPACE,
+ "prefs must not share a namespace with Composio sync state"
+ );
+}
+
+/// `kv_key` trims and ASCII-lowercases, exactly as the engine's does — the RPC
+/// takes free text from a settings toggle, so `"GitHub"`, `" github "` and
+/// `"github"` have to reach one row.
+#[test]
+fn kv_key_normalises_the_toolkit_the_same_way_the_engine_does() {
+ assert_eq!(kv_key(" GitHub "), "github");
+ assert_eq!(kv_key("SLACK"), "slack");
+ assert_eq!(kv_key("gmail"), "gmail");
+ assert_eq!(kv_key(" "), "", "an all-whitespace toolkit has no row");
+}
+
+/// The stored JSON is the engine's `UserScopePref`, field for field.
+///
+/// A host-side twin with the same three booleans would serialise identically
+/// today and drift on the first field either side adds, so the production code
+/// re-exports the engine's type instead of declaring one. This asserts the
+/// bytes that actually land in the row.
+#[test]
+fn stored_value_is_the_three_boolean_fields() {
+ let value = serde_json::to_value(UserScopePref {
+ read: true,
+ write: false,
+ admin: true,
+ })
+ .expect("UserScopePref serialises");
+ assert_eq!(
+ value,
+ serde_json::json!({ "read": true, "write": false, "admin": true })
+ );
+}
+
+/// The default a failed or absent read falls back to: productive, not
+/// permissive-with-admin.
+#[test]
+fn default_pref_is_read_write_without_admin() {
+ let pref = UserScopePref::default();
+ assert!(pref.read);
+ assert!(pref.write);
+ assert!(!pref.admin, "admin must stay opt-in");
+}
diff --git a/src/openhuman/integrations/composio/ops_tests.rs b/src/openhuman/integrations/composio/ops_tests.rs
index c12c075c72..723775bd3e 100644
--- a/src/openhuman/integrations/composio/ops_tests.rs
+++ b/src/openhuman/integrations/composio/ops_tests.rs
@@ -931,7 +931,7 @@ async fn notion_cleanup_targets_include_synced_page_sources() {
let adapter = tinymemory_core::tinycortex::HostSyncAdapter::new(std::sync::Arc::clone(&memory));
state.save(&adapter).await.expect("sync state should save");
- let targets = composio_memory_targets_for_connection(&memory, Some("notion"), "conn-1")
+ let targets = composio_memory_targets_for_connection(&config, Some("notion"), "conn-1")
.await
.expect("notion cleanup targets should resolve");
@@ -971,7 +971,7 @@ async fn notion_cleanup_targets_surface_corrupt_sync_state() {
.await
.expect("corrupt sync state should be written");
- let err = composio_memory_targets_for_connection(&memory, Some("notion"), "conn-1")
+ let err = composio_memory_targets_for_connection(&config, Some("notion"), "conn-1")
.await
.expect_err("corrupt sync state should surface");
@@ -994,7 +994,7 @@ async fn drive_cleanup_targets_are_connection_scoped() {
);
let targets =
- composio_memory_targets_for_connection(&drive_memory, Some("google_drive"), "conn-1")
+ composio_memory_targets_for_connection(&config, Some("google_drive"), "conn-1")
.await
.expect("drive cleanup targets should resolve");
diff --git a/src/openhuman/integrations/composio/schemas.rs b/src/openhuman/integrations/composio/schemas.rs
index 56c837c7af..3c77fe5071 100644
--- a/src/openhuman/integrations/composio/schemas.rs
+++ b/src/openhuman/integrations/composio/schemas.rs
@@ -896,7 +896,28 @@ fn handle_get_user_scopes(params: Map<String, Value>) -> ControllerFuture {
toolkit = %toolkit,
"[composio:scopes] handler entry"
);
- let pref = super::providers::user_scopes::load_or_default(&toolkit).await;
+ // Reads through the bound memory driver's `Graph` family, not through
+ // the engine's `load_or_default` (which resolved the in-process client
+ // itself — openhuman#5560 deleted that client). The read still fails
+ // OPEN onto the default pref for every failure mode, deliberately; see
+ // `ops::user_scopes`.
+ //
+ // The config load is `?`-free for the same reason: this handler has
+ // never had a failing path, and turning "settings file momentarily
+ // unreadable" into an RPC error would make the scopes panel fail where
+ // it used to render the defaults.
+ let pref = match config_rpc::load_config_with_timeout().await {
+ Ok(config) => super::ops::load_user_scope_pref(&config, &toolkit).await,
+ Err(error) => {
+ tracing::warn!(
+ method = "composio.get_user_scopes",
+ toolkit = %toolkit,
+ %error,
+ "[composio:scopes] config load failed, using default pref (read+write)"
+ );
+ super::providers::UserScopePref::default()
+ }
+ };
tracing::debug!(
method = "composio.get_user_scopes",
toolkit = %toolkit,
@@ -934,18 +955,13 @@ fn handle_set_user_scopes(params: Map<String, Value>) -> ControllerFuture {
admin = pref.admin,
"[composio:scopes] handler entry"
);
- let memory = match tinymemory_core::global::client_if_ready() {
- Some(m) => m,
- None => {
- tracing::error!(
- method = "composio.set_user_scopes",
- toolkit = %toolkit,
- "[composio:scopes] memory client not initialised — cannot persist pref"
- );
- return Err("memory client not initialised".to_string());
- }
- };
- if let Err(e) = super::providers::user_scopes::save(&memory, &toolkit, pref).await {
+ // Writes through the bound memory driver's `Graph` family. This half
+ // fails CLOSED, as it did before: the old code refused with "memory
+ // client not initialised" rather than reporting a save it had not
+ // done, and `ops::user_scopes::save` refuses on the same three
+ // grounds (no driver, no `Graph` family, backend write failure).
+ let config = config_rpc::load_config_with_timeout().await?;
+ if let Err(e) = super::ops::save_user_scope_pref(&config, &toolkit, pref).await {
tracing::error!(
method = "composio.set_user_scopes",
toolkit = %toolkit,
diff --git a/src/openhuman/memory/conversations/blocking.rs b/src/openhuman/memory/conversations/blocking.rs
new file mode 100644
index 0000000000..09adb769bb
--- /dev/null
+++ b/src/openhuman/memory/conversations/blocking.rs
@@ -0,0 +1,205 @@
+//! Async wrappers that run the conversation store's **blocking** operations on
+//! tokio's blocking pool (#5156).
+//!
+//! # Why this lives here (#5560)
+//!
+//! It was `tinymemory_core::conversations::blocking`, and that crate's own
+//! module docs already called it *host-retained*: the conversation store is the
+//! engine's, but deciding which executor a host runs a blocking call on is the
+//! host's, and nothing inside `tinymemory` ever called these wrappers. So this
+//! is a move home rather than a re-routing — the same shape as
+//! `memory::rpc_models`, whose forty-five types were named only by this host.
+//!
+//! The only edit is the crate the store is addressed through:
+//! `crate::engine::backend::conversations` was
+//! `pub use tinycortex::memory::conversations`, so the item set is unchanged
+//! and `tinycortex` is a direct dependency this crate keeps. Function
+//! signatures, argument order, error strings and the `[conversations]` log
+//! prefix are byte-identical, because `web_chat::run_task` and the RPC layer
+//! read them.
+//!
+//! Every `tinycortex::memory::conversations` entry point is synchronous, and
+//! each one takes the process-global `CONVERSATION_STORE_LOCK` — a
+//! `parking_lot::Mutex` — and then does fsync'd JSONL file IO while holding it.
+//! Calling one directly from an `async fn` therefore parks a tokio **worker**
+//! thread for the whole wait, and the wait is not short:
+//!
+//! * `threads.jsonl` is folded from scratch on nearly every operation
+//! (`thread_index_unlocked`), and it grows by roughly two lines per appended
+//! message and is never compacted — so the per-call fold cost grows with the
+//! user's whole history;
+//! * `append_message` writes two fsync'd appends under the lock, and
+//! `update_message` reads and rewrites a thread's entire message log under it,
+//! so a live streaming turn holds the lock repeatedly;
+//! * `search_cross_thread_messages` reads every thread's transcript on a cold
+//! index.
+//!
+//! Once more concurrent conversation operations than there are worker threads
+//! are parked on that mutex, the runtime stops polling **anything** — including
+//! the HTTP task that owes the client its response. That is how a create that
+//! only needs one append blows the frontend's 30 s RPC budget:
+//! `UnhandledRejection: Core RPC openhuman.threads_create_new timed out after
+//! 30000ms` (Sentry TAURI-REACT-10, #5156).
+//!
+//! Moving each call onto the blocking pool keeps the lock wait off the async
+//! workers. The work is just as serialized as before — the store's lock still
+//! decides who writes when — but the executor stays live, so the RPC server
+//! keeps answering while a slow conversation operation drains, and a queued
+//! create completes as soon as the lock frees instead of after the client has
+//! given up.
+//!
+//! Callers pass owned arguments because the closure must be `'static`.
+
+use std::path::PathBuf;
+
+use tinycortex::memory::conversations as store;
+
+use tinycortex::memory::conversations::{
+ ConversationMessage, ConversationMessagePatch, ConversationPurgeStats, ConversationStore,
+ ConversationThread, CreateConversationThread, CrossThreadHit,
+};
+
+/// Run one blocking store call on the blocking pool.
+///
+/// A `JoinError` here means the pool task panicked (or the runtime is shutting
+/// down); surface it as a store error rather than propagating the panic into
+/// the RPC dispatcher, which would turn a transient store fault into a 500-shaped
+/// unknown failure.
+async fn run<T, F>(operation: &'static str, f: F) -> Result<T, String>
+where
+ F: FnOnce() -> Result<T, String> + Send + 'static,
+ T: Send + 'static,
+{
+ match tokio::task::spawn_blocking(f).await {
+ Ok(result) => result,
+ Err(error) => {
+ tracing::warn!(
+ operation,
+ error = %error,
+ "[conversations] blocking store task failed to join"
+ );
+ Err(format!(
+ "conversation store {operation} task failed: {error}"
+ ))
+ }
+ }
+}
+
+/// [`store::ensure_thread`] on the blocking pool.
+pub async fn ensure_thread(
+ workspace_dir: PathBuf,
+ request: CreateConversationThread,
+) -> Result<ConversationThread, String> {
+ run("ensure_thread", move || {
+ store::ensure_thread(workspace_dir, request)
+ })
+ .await
+}
+
+/// [`store::list_threads`] on the blocking pool.
+pub async fn list_threads(workspace_dir: PathBuf) -> Result<Vec<ConversationThread>, String> {
+ run("list_threads", move || store::list_threads(workspace_dir)).await
+}
+
+/// [`store::get_messages`] on the blocking pool.
+pub async fn get_messages(
+ workspace_dir: PathBuf,
+ thread_id: String,
+) -> Result<Vec<ConversationMessage>, String> {
+ run("get_messages", move || {
+ store::get_messages(workspace_dir, &thread_id)
+ })
+ .await
+}
+
+/// [`store::append_message`] on the blocking pool.
+pub async fn append_message(
+ workspace_dir: PathBuf,
+ thread_id: String,
+ message: ConversationMessage,
+) -> Result<ConversationMessage, String> {
+ run("append_message", move || {
+ store::append_message(workspace_dir, &thread_id, message)
+ })
+ .await
+}
+
+/// [`store::update_message`] on the blocking pool.
+pub async fn update_message(
+ workspace_dir: PathBuf,
+ thread_id: String,
+ message_id: String,
+ patch: ConversationMessagePatch,
+) -> Result<ConversationMessage, String> {
+ run("update_message", move || {
+ store::update_message(workspace_dir, &thread_id, &message_id, patch)
+ })
+ .await
+}
+
+/// [`store::update_thread_title`] on the blocking pool.
+pub async fn update_thread_title(
+ workspace_dir: PathBuf,
+ thread_id: String,
+ title: String,
+ updated_at: String,
+) -> Result<ConversationThread, String> {
+ run("update_thread_title", move || {
+ store::update_thread_title(workspace_dir, &thread_id, &title, &updated_at)
+ })
+ .await
+}
+
+/// [`store::update_thread_labels`] on the blocking pool.
+pub async fn update_thread_labels(
+ workspace_dir: PathBuf,
+ thread_id: String,
+ labels: Vec<String>,
+ updated_at: String,
+) -> Result<ConversationThread, String> {
+ run("update_thread_labels", move || {
+ store::update_thread_labels(workspace_dir, &thread_id, labels, &updated_at)
+ })
+ .await
+}
+
+/// [`store::delete_thread`] on the blocking pool.
+pub async fn delete_thread(
+ workspace_dir: PathBuf,
+ thread_id: String,
+ deleted_at: String,
+) -> Result<bool, String> {
+ run("delete_thread", move || {
+ store::delete_thread(workspace_dir, &thread_id, &deleted_at)
+ })
+ .await
+}
+
+/// [`store::purge_threads`] on the blocking pool.
+pub async fn purge_threads(workspace_dir: PathBuf) -> Result<ConversationPurgeStats, String> {
+ run("purge_threads", move || store::purge_threads(workspace_dir)).await
+}
+
+/// [`ConversationStore::search_cross_thread_messages`] on the blocking pool.
+///
+/// The heaviest operation in the family: a cold inverted index reads every
+/// thread's transcript before the search runs.
+pub async fn search_cross_thread_messages(
+ workspace_dir: PathBuf,
+ query: String,
+ limit: usize,
+ exclude_thread_id: Option<String>,
+) -> Result<Vec<CrossThreadHit>, String> {
+ run("search_cross_thread_messages", move || {
+ ConversationStore::new(workspace_dir).search_cross_thread_messages(
+ &query,
+ limit,
+ exclude_thread_id.as_deref(),
+ )
+ })
+ .await
+}
+
+#[cfg(test)]
+#[path = "blocking_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/conversations/blocking_tests.rs b/src/openhuman/memory/conversations/blocking_tests.rs
new file mode 100644
index 0000000000..239c5be66e
--- /dev/null
+++ b/src/openhuman/memory/conversations/blocking_tests.rs
@@ -0,0 +1,300 @@
+//! Tests for the blocking-pool conversation-store wrappers (#5156).
+//!
+//! The property under test is that the wrappers are a faithful, `.await`-able
+//! stand-in for the synchronous store: same results, same errors, and safe to
+//! drive concurrently from several tasks on a runtime with a single async worker
+//! — which is exactly the shape that used to starve (a sync call parks the
+//! worker on the store's `parking_lot` mutex, so with every worker parked the
+//! runtime stops polling the HTTP task that owes the client its response).
+
+use serde_json::json;
+use tempfile::TempDir;
+
+use super::*;
+
+fn message(id: &str, content: &str) -> ConversationMessage {
+ ConversationMessage {
+ id: id.to_string(),
+ content: content.to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-07-30T00:00:00Z".to_string(),
+ }
+}
+
+fn create(id: &str) -> CreateConversationThread {
+ CreateConversationThread {
+ id: id.to_string(),
+ title: format!("Title {id}"),
+ created_at: "2026-07-30T00:00:00Z".to_string(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ }
+}
+
+#[tokio::test]
+async fn create_append_read_round_trips_through_the_blocking_pool() {
+ let tmp = TempDir::new().unwrap();
+ let dir = tmp.path().to_path_buf();
+
+ let thread = ensure_thread(dir.clone(), create("thread-a"))
+ .await
+ .expect("ensure_thread");
+ assert_eq!(thread.id, "thread-a");
+
+ append_message(dir.clone(), "thread-a".to_string(), message("m1", "hello"))
+ .await
+ .expect("append_message");
+
+ let messages = get_messages(dir.clone(), "thread-a".to_string())
+ .await
+ .expect("get_messages");
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].content, "hello");
+
+ let threads = list_threads(dir.clone()).await.expect("list_threads");
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].message_count, 1);
+}
+
+#[tokio::test]
+async fn store_errors_surface_unchanged() {
+ let tmp = TempDir::new().unwrap();
+ let dir = tmp.path().to_path_buf();
+
+ // Appending to a thread that was never created is the store's own error,
+ // not a join failure — the wrapper must pass it through verbatim so the
+ // RPC layer's thread-scoped error mapping still recognises it.
+ let error = append_message(dir, "missing".to_string(), message("m1", "hello"))
+ .await
+ .expect_err("append to a missing thread must fail");
+ assert!(
+ error.contains("not found"),
+ "expected the store's own error, got: {error}"
+ );
+}
+
+/// The starvation shape from #5156: several conversation operations in flight at
+/// once on a runtime with a **single** async worker. Each one contends for the
+/// store's process-global mutex, so with the calls made inline the single worker
+/// is parked in `lock()` and nothing else on the runtime can be polled. Off the
+/// blocking pool they all complete, and a plain cooperative task keeps being
+/// polled while they do.
+///
+/// The cooperative ticker alone would not prove that: its 64 yields can all
+/// retire before any store task even reaches the lock, so it would stay green
+/// against an implementation that ran the store inline. Determinism comes from
+/// `probe` — a store closure *held open* for the whole window — plus a watchdog
+/// that observes progress while it is held.
+///
+/// The watchdog is a plain OS thread on purpose. A `tokio::time::timeout` cannot
+/// bound this: if the store ran inline, the sole worker would be parked inside
+/// the probe closure and the timeout future would never be polled either, so the
+/// test would hang instead of failing. An OS thread cannot be starved by the
+/// runtime, and it releases the probe on its way out so a starved runtime always
+/// recovers far enough to report the failure.
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn concurrent_operations_complete_without_stalling_the_single_async_worker() {
+ use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
+ use std::sync::Arc;
+ use std::time::{Duration, Instant};
+
+ const TICK_TARGET: u32 = 64;
+ const WATCHDOG_BUDGET: Duration = Duration::from_secs(10);
+
+ let tmp = TempDir::new().unwrap();
+ let dir = tmp.path().to_path_buf();
+
+ // A store call pinned open for as long as we hold `release`. `recv()` is a
+ // genuinely blocking wait — the same shape as `parking_lot::Mutex::lock`.
+ let probe_entered = Arc::new(AtomicBool::new(false));
+ let (release, held) = std::sync::mpsc::channel::<()>();
+ let probe = tokio::spawn(run("blocked_probe", {
+ let probe_entered = Arc::clone(&probe_entered);
+ move || {
+ probe_entered.store(true, Ordering::SeqCst);
+ let _ = held.recv();
+ Ok::<(), String>(())
+ }
+ }));
+
+ // A cooperative task that only ever yields: it can make progress solely
+ // because no store call is holding the worker hostage.
+ let ticks = Arc::new(AtomicU32::new(0));
+ let ticker = tokio::spawn({
+ let ticks = Arc::clone(&ticks);
+ async move {
+ for _ in 0..TICK_TARGET {
+ tokio::task::yield_now().await;
+ ticks.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ });
+
+ let watchdog = std::thread::spawn({
+ let probe_entered = Arc::clone(&probe_entered);
+ let ticks = Arc::clone(&ticks);
+ move || {
+ let deadline = Instant::now() + WATCHDOG_BUDGET;
+ // 1. The probe must actually be executing, or its "blocking window"
+ // means nothing.
+ while Instant::now() < deadline && !probe_entered.load(Ordering::SeqCst) {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ let entered = probe_entered.load(Ordering::SeqCst);
+ // 2. The ticker must then run to completion *while* that store call
+ // is still held. Inline execution parks the sole worker inside
+ // the closure, so this expires with ticks stuck at 0.
+ let mut observed = 0;
+ while Instant::now() < deadline {
+ observed = ticks.load(Ordering::SeqCst);
+ if observed >= TICK_TARGET {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ // Always release, even on failure: a starved runtime has to recover
+ // far enough for the assertions below to run and report.
+ let _ = release.send(());
+ (entered, observed)
+ }
+ });
+
+ let mut handles = Vec::new();
+ for idx in 0..8 {
+ let dir = dir.clone();
+ handles.push(tokio::spawn(async move {
+ let thread = ensure_thread(dir.clone(), create(&format!("thread-{idx}")))
+ .await
+ .expect("ensure_thread");
+ append_message(
+ dir,
+ thread.id.clone(),
+ message(&format!("m{idx}"), "concurrent"),
+ )
+ .await
+ .expect("append_message");
+ thread.id
+ }));
+ }
+
+ // The load-bearing assertions, both observed from outside the runtime.
+ let (probe_started, observed_ticks) = watchdog.join().expect("join watchdog");
+ assert!(
+ probe_started,
+ "the blocking store probe never started — the pool is not running store work"
+ );
+ assert_eq!(
+ observed_ticks, TICK_TARGET,
+ "the async worker must keep polling while a store call is blocked; \
+ only {observed_ticks}/{TICK_TARGET} ticks retired within {WATCHDOG_BUDGET:?}"
+ );
+
+ ticker.await.expect("join ticker");
+ probe
+ .await
+ .expect("join probe")
+ .expect("probe closure result");
+
+ let mut ids = Vec::new();
+ for handle in handles {
+ ids.push(handle.await.expect("join create task"));
+ }
+ ids.sort();
+ ids.dedup();
+ assert_eq!(
+ ids.len(),
+ 8,
+ "every concurrent create must land its own thread"
+ );
+
+ let threads = list_threads(dir).await.expect("list_threads");
+ assert_eq!(threads.len(), 8);
+ assert!(threads.iter().all(|thread| thread.message_count == 1));
+}
+
+#[tokio::test]
+async fn title_labels_delete_and_purge_round_trip() {
+ let tmp = TempDir::new().unwrap();
+ let dir = tmp.path().to_path_buf();
+ ensure_thread(dir.clone(), create("thread-a"))
+ .await
+ .expect("ensure_thread");
+
+ let retitled = update_thread_title(
+ dir.clone(),
+ "thread-a".to_string(),
+ "Renamed".to_string(),
+ "2026-07-30T00:01:00Z".to_string(),
+ )
+ .await
+ .expect("update_thread_title");
+ assert_eq!(retitled.title, "Renamed");
+
+ let relabelled = update_thread_labels(
+ dir.clone(),
+ "thread-a".to_string(),
+ vec!["general".to_string()],
+ "2026-07-30T00:02:00Z".to_string(),
+ )
+ .await
+ .expect("update_thread_labels");
+ assert_eq!(relabelled.labels, vec!["general".to_string()]);
+ assert_eq!(relabelled.title, "Renamed", "labels update preserves title");
+
+ assert!(
+ delete_thread(
+ dir.clone(),
+ "thread-a".to_string(),
+ "2026-07-30T00:03:00Z".to_string()
+ )
+ .await
+ .expect("delete_thread"),
+ "deleting a live thread reports true"
+ );
+ assert!(list_threads(dir.clone()).await.unwrap().is_empty());
+
+ ensure_thread(dir.clone(), create("thread-b"))
+ .await
+ .expect("ensure_thread");
+ purge_threads(dir.clone()).await.expect("purge_threads");
+ assert!(list_threads(dir).await.unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn update_message_patches_metadata_and_search_finds_content() {
+ let tmp = TempDir::new().unwrap();
+ let dir = tmp.path().to_path_buf();
+ ensure_thread(dir.clone(), create("thread-a"))
+ .await
+ .expect("ensure_thread");
+ append_message(
+ dir.clone(),
+ "thread-a".to_string(),
+ message("m1", "quarterly roadmap review"),
+ )
+ .await
+ .expect("append_message");
+
+ let patched = update_message(
+ dir.clone(),
+ "thread-a".to_string(),
+ "m1".to_string(),
+ ConversationMessagePatch {
+ extra_metadata: Some(json!({"pinned": true})),
+ },
+ )
+ .await
+ .expect("update_message");
+ assert_eq!(patched.extra_metadata, json!({"pinned": true}));
+
+ let hits = search_cross_thread_messages(dir, "roadmap".to_string(), 10, None)
+ .await
+ .expect("search_cross_thread_messages");
+ assert!(
+ hits.iter().any(|hit| hit.thread_id == "thread-a"),
+ "cross-thread search must find the appended message, got: {hits:?}"
+ );
+}
diff --git a/src/openhuman/memory/conversations/mod.rs b/src/openhuman/memory/conversations/mod.rs
index f837605cc1..ff552bf875 100644
--- a/src/openhuman/memory/conversations/mod.rs
+++ b/src/openhuman/memory/conversations/mod.rs
@@ -1,10 +1,28 @@
-//! Host layer over [`tinymemory_core::conversations`].
+//! Host-side wiring for workspace-backed conversation thread/message storage.
//!
-//! The domain lives in the extracted crate; the `core::bus` subscribers stay
-//! here — they name `DomainEvent` and `BUS`, which are OpenHuman vocabulary.
-//! The glob re-export keeps every historical `memory::conversations::…` path resolving.
+//! Conversations are stored as JSONL files under the workspace (thread metadata
+//! append-only in `threads.jsonl`; each thread's messages in a dedicated JSONL
+//! file). The store / inverted-index / tokenizer / types engine is
+//! `tinycortex::memory::conversations`, and consumers name that directly —
+//! roughly a dozen files across `threads`, `channels` and `agent` already do.
+//!
+//! Host-retained:
+//! - `bus` — the `core::bus` persistence subscriber that bridges typed channel
+//! events onto the store (the store abstracts the bus behind its own
+//! `ConversationEventBus` trait; the host wires the real one).
+//! - [`blocking`] — `spawn_blocking` wrappers around the store's synchronous
+//! entry points. Request paths must use these, never the sync API (#5156).
+//!
+//! # What changed for #5560
+//!
+//! This module used to open with `pub use tinymemory_core::conversations::*;`,
+//! and that glob carried exactly one item: `blocking`. The engine crate's own
+//! docs already labelled it *host-retained* — nothing inside `tinymemory` ever
+//! called it — so it moved here rather than being re-routed, and this file no
+//! longer names the engine crate at all. See [`blocking`]'s module docs for the
+//! one-line difference the move made.
-pub use tinymemory_core::conversations::*;
+pub mod blocking;
mod bus;
diff --git a/src/openhuman/memory/diff/mod.rs b/src/openhuman/memory/diff/mod.rs
index 8ebb0c9bc0..258e2302d6 100644
--- a/src/openhuman/memory/diff/mod.rs
+++ b/src/openhuman/memory/diff/mod.rs
@@ -4,6 +4,43 @@
//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::diff::…` path resolving.
+//!
+//! # What the glob actually carries, and what blocks removing it (#5560)
+//!
+//! Three things, and only one of them is engine-owned in a way that matters:
+//!
+//! - the eight serde wire types (`ChangeKind`, `Checkpoint`, `CrossSourceDiff`,
+//! `DiffResult`, `DiffSummary`, `ItemChange`, `Snapshot`, `SnapshotTrigger`)
+//! — these are `tinycortex::memory::diff::types`, which `rpc.rs` and
+//! `tools/diff.rs` already name directly, so they would repoint for free;
+//! - `ops` (or its `memory-git`-off stub) — 312 lines of async wrappers over
+//! `tinycortex::memory::diff::DiffEngine`, reached from `rpc.rs` as
+//! `super::ops` and from the `memory_diff` agent tool;
+//! - `source` — the `SnapshotItemSource` seam `ops` hands the engine.
+//!
+//! `ops` is what pins this. It reads the source registry
+//! (`sources::registry::list_sources`, `sources::types::MemorySourceEntry`,
+//! `sources::status::source_id_prefix`), so it cannot come home ahead of
+//! `memory::sources` — see that module's docs for the two blockers there — and
+//! `source` builds its snapshot items through
+//! `store::chunks::store::with_connection`, a raw SQLite handle. Moving that
+//! pair into the host would relocate the unpoliced door rather than close it.
+//!
+//! `MemoryDiff` is a real capability family — `capture_snapshot`, `snapshots`,
+//! `diff` — and it is the right destination for three of `ops`' entry points.
+//! It is not a drop-in for the module, for two reasons worth stating before
+//! anyone tries:
+//!
+//! - **It covers three of `ops`' ten entry points.** `auto_snapshot_after_sync`,
+//! `diff_since_last`, `diff_since_read`, `mark_read`, `create_checkpoint`,
+//! `diff_since_checkpoint` and `cleanup` are checkpoints, read markers, the
+//! post-sync trigger and ledger retention; the family has no member for any
+//! of them, and `capture_snapshot` takes no `SnapshotTrigger`.
+//! - **The wire shapes are different types.** The family answers `SnapshotRef`
+//! and `DiffReport`; `memory_diff.*` publishes `Snapshot`, `DiffResult` and
+//! `CrossSourceDiff`, which the Memory tab reads. Swapping the call without
+//! translating at the handler would change the RPC payloads, which is a
+//! behaviour change, not a migration.
pub use tinymemory_core::diff::*;
diff --git a/src/openhuman/memory/guard/families_tests.rs b/src/openhuman/memory/guard/families_tests.rs
index ccc3fbdd33..e3409b70ad 100644
--- a/src/openhuman/memory/guard/families_tests.rs
+++ b/src/openhuman/memory/guard/families_tests.rs
@@ -416,3 +416,93 @@ async fn retrieve_leaves_intersects_an_explicit_scope_with_the_ambient_one() {
"an explicit scope outside the ambient one must fail closed"
);
}
+
+// ── Episodic writes are redacted before they cross to a foreign driver ───────
+//
+// Both members reach a driver that may be a separately compiled module, so the
+// content has to be scrubbed on the way out. `insert_event` shipped without
+// that scrub once already, and nothing caught it: the recording driver
+// discarded the event instead of keeping its text, so no assertion could see
+// what the driver was handed. These two tests exist to make that class of
+// regression visible, which is why they assert on the recorded content rather
+// than merely on the call having happened.
+
+fn episodic_turn(content: &str) -> crate::openhuman::memory::api::provider::EpisodicTurn {
+ crate::openhuman::memory::api::provider::EpisodicTurn {
+ id: None,
+ session_id: "session-1".into(),
+ timestamp: 1_700_000_000.0,
+ role: "user".into(),
+ content: content.into(),
+ lesson: None,
+ tool_calls_json: None,
+ cost_microdollars: 0,
+ }
+}
+
+fn episodic_event(content: &str) -> crate::openhuman::memory::api::provider::EpisodicEvent {
+ crate::openhuman::memory::api::provider::EpisodicEvent {
+ event_id: "event-1".into(),
+ segment_id: "segment-1".into(),
+ session_id: "session-1".into(),
+ namespace: "ns".into(),
+ kind: crate::openhuman::memory::api::provider::EventKind::Fact,
+ content: content.into(),
+ subject: None,
+ timestamp_ref: None,
+ confidence: 1.0,
+ embedding: None,
+ source_turn_ids: None,
+ created_at: 1_700_000_000.0,
+ }
+}
+
+#[tokio::test]
+async fn episodic_writes_are_redacted_for_a_foreign_driver() {
+ let secrety = "Authorization: Bearer abcdefghijklmnop";
+
+ let (driver, guard) = guarded(external_policy("untrusted"));
+ guard
+ .as_episodic()
+ .expect("episodic family")
+ .insert_turn(&episodic_turn(secrety))
+ .await
+ .expect("insert_turn");
+ let turn = driver.only_call();
+ assert_ne!(
+ turn.content.as_deref(),
+ Some(secrety),
+ "the bearer token reached a foreign driver verbatim"
+ );
+
+ let (driver, guard) = guarded(external_policy("untrusted"));
+ guard
+ .as_episodic()
+ .expect("episodic family")
+ .insert_event(&episodic_event(secrety))
+ .await
+ .expect("insert_event");
+ let event = driver.only_call();
+ assert_ne!(
+ event.content.as_deref(),
+ Some(secrety),
+ "the bearer token reached a foreign driver verbatim"
+ );
+}
+
+/// The other half, so the test above cannot pass by redacting everything
+/// everywhere: an in-process driver is the same address space, so scrubbing
+/// there would cost fidelity for no privacy gain.
+#[tokio::test]
+async fn episodic_writes_are_not_redacted_for_an_embedded_driver() {
+ let secrety = "Authorization: Bearer abcdefghijklmnop";
+
+ let (driver, guard) = guarded(embedded_policy());
+ guard
+ .as_episodic()
+ .expect("episodic family")
+ .insert_event(&episodic_event(secrety))
+ .await
+ .expect("insert_event");
+ assert_eq!(driver.only_call().content.as_deref(), Some(secrety));
+}
diff --git a/src/openhuman/memory/guard/test_support.rs b/src/openhuman/memory/guard/test_support.rs
index fe5afa8a4b..b77ebd8cdf 100644
--- a/src/openhuman/memory/guard/test_support.rs
+++ b/src/openhuman/memory/guard/test_support.rs
@@ -796,8 +796,16 @@ impl MemoryEpisodic for RecordingProvider {
Ok(())
}
- async fn insert_event(&self, _event: &EpisodicEvent) -> Result<(), MemoryError> {
- self.record(Call::plain("episodic.insert_event"));
+ async fn insert_event(&self, event: &EpisodicEvent) -> Result<(), MemoryError> {
+ // Records the event text for the same reason `insert_turn` does: a guard
+ // that stopped redacting one would otherwise be invisible to every test,
+ // and the redaction on this path has already been missing once.
+ self.record(Call {
+ method: "episodic.insert_event".into(),
+ content: Some(event.content.clone()),
+ taint: None,
+ scoped: None,
+ });
Ok(())
}
diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rs
index a2b3abe10f..eb4dae348f 100644
--- a/src/openhuman/memory/mod.rs
+++ b/src/openhuman/memory/mod.rs
@@ -19,9 +19,18 @@
//! | [`global`] | the per-workspace singleton |
//! | [`host`] | the seam impls — [`host::install_memory_event_sink`] and `MemoryHostConfig for Config` |
//!
-//! Everything else in this module is a **re-export** of the extracted crate, so
-//! the ~550 `crate::openhuman::memory::…` paths elsewhere in this crate keep
-//! resolving unchanged. Prefer `tinymemory_core::…` in new code.
+//! What is left below is a handful of flat **type** re-exports, kept so the
+//! ~550 `crate::openhuman::memory::…` paths elsewhere in this crate keep
+//! resolving unchanged. The engine's *modules* are no longer re-exported here
+//! at all — see the block at the bottom of this file for why that facade was
+//! deleted.
+//!
+//! **Prefer `tinymemory_api::…` in new code, never `tinymemory_core::…`.** This
+//! paragraph used to say the opposite, which predates #5560: the contract crate
+//! is what the host, `ModuleMemoryProvider` and the loaded module all speak, and
+//! naming the engine crate is the thing that keeps it linked into the shipped
+//! binary. A path that has no contract equivalent is a gap to report, not a
+//! reason to reach for the engine.
pub mod agent;
pub mod api;
@@ -29,6 +38,15 @@ pub mod binding;
pub mod driver;
pub mod guard;
pub mod host;
+/// Host implementations of the seam traits the ENGINE declares.
+///
+/// `#[cfg(test)]` because the production host embeds no engine any more: the
+/// module installs its own seams and this host answers it over the bus through
+/// [`crate::openhuman::modules::memory_host`] instead. What still needs these
+/// is the test suite, which binds the in-process TinyCortex driver directly —
+/// legitimate, because `tinymemory-core` is a dev-dependency there and a
+/// dev-dependency is not linked into the shipped binary.
+#[cfg(any(test, feature = "memory-embedded-test-seams"))]
pub mod host_impls;
/// Host desktop policy: is the memory content root a vault Obsidian already
/// knows about? See the module docs for why this is OpenHuman's and not the
diff --git a/src/openhuman/memory/ops/documents.rs b/src/openhuman/memory/ops/documents.rs
index 8b90ed80ac..dacb0ce0c7 100644
--- a/src/openhuman/memory/ops/documents.rs
+++ b/src/openhuman/memory/ops/documents.rs
@@ -372,13 +372,35 @@ pub async fn context_recall(
///
/// `request.jwt_token` is accepted for backward compatibility but ignored — all
/// memory operations are local. Remote/cloud sync is a future consideration.
+///
+/// "Initialise" now means **bind the memory driver for this workspace**, not
+/// construct an in-process engine: this was `tinymemory_core::global::init`, a
+/// second `MemoryClient` over the same SQLite file as the bound driver (#5560).
+/// `active_memory_guard` is the cached, workspace-keyed resolution every other
+/// handler in this file already takes, so calling it here warms exactly the
+/// driver the next `memory_*` call will use.
+///
+/// One behaviour difference, stated rather than hidden: binding is infallible
+/// by design — an inadmissible driver *falls back* and records why, where
+/// `global::init` returned `Err`. So a driver that cannot bind is now reported
+/// through `memory.provider_status` instead of failing this call, and only an
+/// unresolvable workspace or a poisoned binding lock still errors. The driver
+/// id is logged here so the distinction is not invisible at this handler
+/// either.
pub async fn memory_init(
request: MemoryInitRequest,
) -> Result<RpcOutcome<ApiEnvelope<MemoryInitResponse>>, String> {
let _ = request.jwt_token; // accepted but unused — memory is local-only
let workspace_dir = current_workspace_dir().await?;
- // Initialise (or return existing) global singleton.
- let _ = tinymemory_core::global::init(workspace_dir.clone())?;
+ // Resolve (and thereby warm) the guarded driver for this workspace — the
+ // same door every other handler in this file takes, so `memory_init`
+ // initialises exactly what the next `memory_*` call will use.
+ let guard = active_memory_guard().await?;
+ log::debug!(
+ "[memory:ops] memory_init: workspace={} driver={}",
+ workspace_dir.display(),
+ guard.driver_id(),
+ );
let memory_dir = workspace_dir.join("memory");
Ok(envelope(
MemoryInitResponse {
diff --git a/src/openhuman/memory/ops/guard.rs b/src/openhuman/memory/ops/guard.rs
index a50149f0d6..40979460be 100644
--- a/src/openhuman/memory/ops/guard.rs
+++ b/src/openhuman/memory/ops/guard.rs
@@ -18,17 +18,35 @@
//! workspace is always bound, so that is the only path production takes.
//!
//! The fallback path exists for callers that run *before* a context is built —
-//! in practice the roughly four thousand pre-boot unit tests, which bind the
-//! process-global client through `ensure_shared_memory_client()` and never
-//! build a `CoreContext`. `CoreContext::memory()` cannot serve them:
+//! in practice the roughly four thousand pre-boot unit tests, which never build
+//! a `CoreContext`. `CoreContext::memory()` cannot serve them:
//! `memory_binding()` goes through `workspace_dir()`, which errors outright
-//! when the context has no bound workspace. `active_memory_client()` already
-//! has an answer for that state — it lazily initialises — so this mirrors it,
-//! with one refinement: it prefers the workspace the global client is
-//! **already** bound to over whatever `Config::load_or_init` reports. Resolving
-//! through the config instead would hand a test a binding over a *different*
-//! workspace than the client its fixtures wrote to, which is a silently wrong
-//! store rather than a visible failure.
+//! when the context has no bound workspace.
+//!
+//! ### The fallback names its workspace differently in the two builds, on purpose
+//!
+//! This used to read `tinymemory_core::global::active_workspace_dir()` — "the
+//! workspace the in-process engine singleton is currently bound to" — and
+//! preferred it over `Config::load_or_init` precisely so a test whose fixtures
+//! wrote through that singleton could not be handed a binding over a *different*
+//! workspace, which is a silently wrong store rather than a visible failure.
+//!
+//! #5560 deletes that singleton's boot, so the host no longer has an engine slot
+//! to ask. The property still has to hold, so the fallback now names the same
+//! workspace by its real source in each build:
+//!
+//! - **`cfg(test)`** — `test_support::shared_memory_test_workspace()`, the
+//! single leaked temp workspace every `memory::ops` fixture shares and the
+//! exact path `ensure_shared_memory_client()` binds. Asking the fixture
+//! directly is strictly *more* reliable than asking a singleton it happened to
+//! have initialised, because it cannot be re-pointed by an unrelated test.
+//! (Named without a doc link on purpose: the module it lives in is
+//! `#[cfg(test)]`, so a link would dangle in a documentation build.)
+//! - **production** — `helpers::current_workspace_dir()`, i.e.
+//! `Config::load_or_init`. This is not a behaviour change: with the engine
+//! singleton no longer initialised at boot, `active_workspace_dir()` answered
+//! `None` on every production call anyway, so `Config::load_or_init` was
+//! already the only reachable answer here.
//!
//! The fallback binds with [`MemorySubsystemConfig::default`] (driver
//! `"tinycortex"`, default hook budgets). That is the right default precisely
@@ -41,30 +59,49 @@ use crate::core::runtime::context::CoreContext;
use crate::openhuman::config::schema::MemorySubsystemConfig;
use crate::openhuman::memory::binding;
use crate::openhuman::memory::guard::MemoryGuard;
-use tinymemory_core::global;
+
+/// The workspace the pre-boot fallback guards — production build.
+///
+/// See the module docs for why the two builds resolve it differently. Two
+/// definitions rather than one body with a `#[cfg]` block inside it: a bare
+/// block in statement position is only the function's value once the *other*
+/// arm has been stripped, which is exactly the kind of thing that compiles in
+/// one build configuration and not the other.
+#[cfg(not(test))]
+async fn fallback_workspace_dir() -> Result<std::path::PathBuf, String> {
+ super::helpers::current_workspace_dir().await
+}
+
+/// The workspace the pre-boot fallback guards — test build.
+///
+/// The shared fixture's own path, so a test that seeded through
+/// `ensure_shared_memory_client()` is guaranteed the binding over the store its
+/// fixtures wrote to. `async` to match the production arm; there is nothing to
+/// await.
+#[cfg(test)]
+async fn fallback_workspace_dir() -> Result<std::path::PathBuf, String> {
+ Ok(super::test_support::shared_memory_test_workspace())
+}
/// The guarded memory driver for this dispatch.
///
/// # Errors
///
/// When neither resolution path can name a workspace — no ambient context and
-/// no global client, with `Config::load_or_init` also failing — or when the
-/// binding cache lock is poisoned.
+/// `Config::load_or_init` also failing — or when the binding cache lock is
+/// poisoned.
pub(crate) async fn active_memory_guard() -> Result<Arc<MemoryGuard>, String> {
if let Some(ctx) = CoreContext::current() {
match ctx.memory() {
Ok(guard) => return Ok(guard),
Err(error) => log::debug!(
"[memory:guard] ambient context has no bound workspace ({error}); \
- resolving as active_memory_client does"
+ falling back to the configured workspace"
),
}
}
- let workspace_dir = match global::active_workspace_dir() {
- Some(dir) => dir,
- None => super::helpers::current_workspace_dir().await?,
- };
+ let workspace_dir = fallback_workspace_dir().await?;
log::debug!(
"[memory:guard] no context binding; guarding workspace={}",
workspace_dir.display()
diff --git a/src/openhuman/memory/ops/guard_tests.rs b/src/openhuman/memory/ops/guard_tests.rs
index f8f3380b03..35eef907e7 100644
--- a/src/openhuman/memory/ops/guard_tests.rs
+++ b/src/openhuman/memory/ops/guard_tests.rs
@@ -13,16 +13,15 @@ use super::*;
/// `CoreContext`, so a config-derived fallback would silently guard a
/// different store.
#[tokio::test]
-async fn falls_back_to_the_globally_bound_workspace_when_there_is_no_context() {
+async fn falls_back_to_the_configured_workspace_when_there_is_no_context() {
let _serial = crate::openhuman::memory::ops::GLOBAL_MEMORY_TEST_LOCK
.lock()
.await;
+ // The process-global engine slot is gone with the second in-process engine,
+ // so there is no `active_workspace_dir()` to interrogate. The fixture's own
+ // workspace is the anchor now, and the assertion below — that the fallback
+ // resolves to the same binding — is what this test was really about.
let workspace = crate::openhuman::memory::ops::ensure_shared_memory_client();
- assert_eq!(
- global::active_workspace_dir().as_deref(),
- Some(workspace.as_path()),
- "the fixture must leave the global client bound to its own workspace"
- );
let guard = active_memory_guard().await.expect("guard resolves");
let bound = binding::for_workspace(&workspace, &MemorySubsystemConfig::default())
diff --git a/src/openhuman/memory/ops/sync.rs b/src/openhuman/memory/ops/sync.rs
index e2b465e33f..627f2d0286 100644
--- a/src/openhuman/memory/ops/sync.rs
+++ b/src/openhuman/memory/ops/sync.rs
@@ -2,6 +2,42 @@
//!
//! Sync RPCs publish `DomainEvent::MemorySyncRequested` on the global event
//! bus — they are fire-and-forget hooks for future ingestion subscribers.
+//!
+//! # Both engine calls here are openhuman#5560 blockers, and both degrade
+//!
+//! Neither of the two `tinymemory_core::` calls below could be routed through
+//! the contract, and both change behaviour the moment the host's in-process
+//! engine is deleted. Written down here because both failures are quiet, and
+//! the quiet one is the one that gets shipped.
+//!
+//! - **`spawn_manual_sync` → `tinycortex::run_composio_connection`.** The
+//! engine's own `run_composio_connection_with_caps` opens with
+//! `global::client_if_ready().ok_or(… "memory client is not ready")`, so with
+//! the in-process engine gone every target fails and this handler emits
+//! `MemorySyncStage::Failed` per connection. Loud, at least, but wrong. There
+//! is no contract member to move to: the whole pipeline is `tinycortex`-shaped
+//! (a `SyncPipeline` over provider-specific fetchers), and the loaded module
+//! does not run it either — `tinymemory` v1.5.0's module carries a section
+//! headed "The periodic sync loops are deliberately NOT started here" with
+//! three named reasons. Manual sync and the periodic loop share this call, so
+//! they move together or not at all.
+//! - **[`memory_ingestion_status`] → `global::client_if_ready()`.** Reads the
+//! engine's live `IngestionState` — running flag, in-flight document, queue
+//! depth. The contract has no member for it (`memory::bypass_allowlist_tests`
+//! already records it as "queue telemetry, absent from the contract"), and
+//! the state now lives inside the module's own address space. **This is the
+//! quiet one**: the `None` arm already answers "idle, queue empty", which is
+//! indistinguishable from a healthy store with nothing to do — so once the
+//! second engine goes this RPC reports permanent idle rather than failing,
+//! and the Memory panel's ingestion indicator simply never lights up again.
+//!
+//! The honest fix is not a new bus member. `tinymemory_api::host::MemoryEvent`
+//! already carries `DocumentIngestStarted`/`Completed` **with `queue_depth`**,
+//! and the host already serves the event sink over the bus
+//! (`modules/memory_host.rs`), so the module's ingestion events reach this
+//! process today. The status snapshot should be folded up from that stream
+//! host-side, which is a host change with no release coupling — but it needs
+//! a home next to the sink in `memory/host.rs`, not here.
use crate::openhuman::config::rpc as config_rpc;
use crate::openhuman::memory::sync::composio;
diff --git a/src/openhuman/memory/people/mod.rs b/src/openhuman/memory/people/mod.rs
index eae9d277e5..8143a1056a 100644
--- a/src/openhuman/memory/people/mod.rs
+++ b/src/openhuman/memory/people/mod.rs
@@ -1,11 +1,36 @@
-//! Host layer over [`tinymemory_core::people`].
+//! Host layer over the engine's people domain.
//!
-//! The domain itself lives in the extracted crate; what stays here is its
+//! The domain itself lives in the engine crate; what stays here is its
//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::people::…` path resolving.
+//!
+//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//!
+//! It used to read `pub use tinymemory_core::people::*;`, and that path was
+//! itself a re-export: `tinymemory_core::people` is
+//! `pub use crate::engine::backend::people::{address_book, migrations,
+//! resolver, scorer, store, types};`, and `engine::backend::people` is
+//! `pub use tinycortex::memory::people`. Both spellings therefore resolve to
+//! the **same six items**; naming the engine crate directly changes no item,
+//! only which crate alias holds them in the build.
+//!
+//! That matters because `tinymemory-core` is what #5560 is removing from the
+//! production dependency graph, while `tinycortex` stays — it is a direct
+//! dependency of this crate (`Cargo.toml`), it is where the memory engine
+//! actually lives, and ~40 files here already name `tinycortex::memory::…`.
+//! Same precedent as the `Memory` / `MemoryCategory` type re-exports in
+//! `memory/mod.rs`, which were repointed at the contract for the same reason.
+//!
+//! **The `contacts` gate has to follow.** `address_book`'s macOS reader is
+//! `#[cfg(all(target_os = "macos", feature = "contacts"))]` *inside tinycortex*,
+//! and this crate reaches it today through `contacts = ["tinymemory-core/contacts"]`
+//! → `tinymemory-core`'s `contacts = ["tinycortex/contacts"]`. When the
+//! `tinymemory-core` normal dependency is dropped, that forward has to become
+//! `contacts = ["tinycortex/contacts"]` directly, or the gate test below stops
+//! testing anything.
-pub use tinymemory_core::people::*;
+pub use tinycortex::memory::people::*;
pub mod rpc;
pub mod schemas;
diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs
index d0bf730427..4e200450a6 100644
--- a/src/openhuman/memory/read_rpc/admin.rs
+++ b/src/openhuman/memory/read_rpc/admin.rs
@@ -272,6 +272,28 @@ pub async fn reset_tree_rpc(config: &Config) -> Result<RpcOutcome<ResetTreeRespo
// ── flush_source_tree ────────────────────────────────────────────────────
+/// Force a flush of one source's summary tree.
+///
+/// # The last engine reference in this module (#5560)
+///
+/// `get_or_create_source_tree` hands back a live `Tree` **object**, and both
+/// things this handler does next need the object rather than a namespace: the
+/// host's `TreeFactory::from_tree(&tree).label_strategy(&cfg)` picks the
+/// labelling policy from the tree's own kind/scope, and `force_flush_tree`
+/// takes `&tree.id`.
+///
+/// `MemoryTree` cannot express that. It is namespace-addressed end to end —
+/// `append`, `query_source`, `drill_down`, `seal`, `cascade`, `summary_forest`,
+/// `recent_leaves` — and there is no member that returns a tree handle, nor
+/// should there be: handing a driver's internal object across the bus is the
+/// thing the contract exists to prevent. `tinymemory_core::tree_source` is also
+/// genuinely engine-owned (it wraps `tree::tree::registry::get_or_create_tree`
+/// and writes the `_source.md` mirror as a side effect), so there is no
+/// tinycortex twin to repoint at either.
+///
+/// Migrating this needs a bus member shaped like "flush the tree for this
+/// source scope, using the host's label strategy", which does not exist in the
+/// pinned release — an upstream ask, not a host change.
pub async fn flush_source_tree_rpc(
config: &Config,
source_scope: &str,
diff --git a/src/openhuman/memory/read_rpc/mod.rs b/src/openhuman/memory/read_rpc/mod.rs
index 152f0778a5..7787461dfc 100644
--- a/src/openhuman/memory/read_rpc/mod.rs
+++ b/src/openhuman/memory/read_rpc/mod.rs
@@ -44,6 +44,19 @@ pub(crate) fn parse_source_kind_str(s: &str) -> Option<tinymemory_api::chunks::S
tinymemory_api::chunks::SourceKind::parse(s).ok()
}
+// Re-exports for `read_rpc_tests.rs`, which drives this module with
+// `use super::*;`.
+//
+// `with_connection` is the raw SQLite door into the engine's chunk store, and
+// it is deliberately the only one left here: the tests use it to assert on rows
+// the RPCs wrote, which is the point of asserting *storage* rather than
+// re-reading through the same handler. It survives the #5560 shed because it is
+// `#[cfg(test)]` — `cfg(test)` code links the `tinymemory-core`
+// **dev-dependency**, which stays after the normal dependency is dropped, so
+// this line does not keep the engine crate in the shipped binary. Nothing
+// production-side in `read_rpc` names the engine any more; `wipe_all`,
+// `clear_composio_sync_state` and `delete_source` left for `purge_all`,
+// `kv_list` + `kv_delete` and `forget_matching(Source)`.
#[cfg(test)]
pub(crate) use crate::openhuman::config::Config;
#[cfg(test)]
diff --git a/src/openhuman/memory/sources/mod.rs b/src/openhuman/memory/sources/mod.rs
index d85ec2e429..cfdcf2f679 100644
--- a/src/openhuman/memory/sources/mod.rs
+++ b/src/openhuman/memory/sources/mod.rs
@@ -4,6 +4,35 @@
//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::sources::…` path resolving.
+//!
+//! # Why this glob is still here (#5560), stated so nobody re-derives it
+//!
+//! On its face this looks like the easiest facade in the tree to bring home:
+//! the registry it fronts is persisted in **this host's** `config.toml` under
+//! `[[memory_sources]]`, and `tinymemory_core::sources` is a thin layer —
+//! `types` is `pub use tinymemory_sources::…`, `registry` wraps
+//! `tinymemory_sources::registry::SourceRegistry`, and the readers wrap
+//! `tinymemory_sources::readers`. Two things block moving it, and both are
+//! outside this file:
+//!
+//! 1. **The types have a home this crate does not depend on.** They are
+//! `tinymemory-sources`' — an engine-neutral crate the root manifest does
+//! not list. Bringing the domain here needs that dependency added, which is
+//! a `Cargo.toml` decision, not a code one.
+//! 2. **`sources::sync` is wired into the pieces #5560 has not moved yet.**
+//! Its call graph reaches `engine::run_source_pipeline`,
+//! `queue::store::retry_all_failed`,
+//! `store::chunks::store::with_connection`, `sync::composio` and
+//! `sync::audit` — the ingest pipeline, the re-embed queue and the raw
+//! SQLite chunk door. Porting the domain as it stands would move those into
+//! the host rather than behind the bus, which is the opposite of what the
+//! issue is for: a second unpoliced door spelled differently is still a
+//! second unpoliced door.
+//!
+//! So this stays until the queue and the sync pipeline go behind the module.
+//! `MemorySourceSink` is not the answer either — it is `accept_source_items` +
+//! `forget_source` + `forget_matching`, an *ingest* door, with no listing or
+//! CRUD member for a configured connector.
pub use tinymemory_core::sources::*;
diff --git a/src/openhuman/memory/sources/rpc.rs b/src/openhuman/memory/sources/rpc.rs
index 30dac04647..d377159267 100644
--- a/src/openhuman/memory/sources/rpc.rs
+++ b/src/openhuman/memory/sources/rpc.rs
@@ -9,6 +9,21 @@ use crate::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
use crate::rpc::RpcOutcome;
use tinymemory_api::host::MemoryHostConfig;
+/// The coding-session ingest request, under this domain's own name.
+///
+/// The type is the engine's (`tinymemory_core::tinycortex`, which is
+/// `tinymemory-core`'s host-orchestration layer over TinyCortex's persona
+/// pipeline — 305 lines that name `walkdir`, `RawSession` and `FileStateStore`,
+/// with no capability family and no contract equivalent). It is re-exported
+/// here so `schemas.rs` can name it as `rpc::CodingSessionIngestRequest`, the
+/// way every other handler adapter in that file names its request type.
+///
+/// That is a consolidation, not a migration (#5560): the engine dependency does
+/// not go away, it stops being spread over two files. When the persona pipeline
+/// finally moves — behind the bus, or home the way `rpc_models` did — this
+/// module is the only one that has to change.
+pub use tinymemory_core::tinycortex::CodingSessionIngestRequest;
+
#[derive(Debug, serde::Serialize)]
pub struct CodingSessionStatusResponse {
pub sources: Vec<tinymemory_core::tinycortex::CodingSessionSourceStatus>,
@@ -85,7 +100,7 @@ fn ingest_budget(max_sessions: usize) -> std::time::Duration {
}
pub async fn ingest_coding_sessions_rpc(
- req: tinymemory_core::tinycortex::CodingSessionIngestRequest,
+ req: CodingSessionIngestRequest,
) -> Result<RpcOutcome<tinymemory_core::tinycortex::CodingSessionIngestResponse>, String> {
tracing::info!("[memory_sources] ingest_coding_sessions_rpc: entry");
let config = crate::openhuman::config::Config::load_or_init()
diff --git a/src/openhuman/memory/sources/schemas.rs b/src/openhuman/memory/sources/schemas.rs
index 6c08cbaa32..8ac0a80ad8 100644
--- a/src/openhuman/memory/sources/schemas.rs
+++ b/src/openhuman/memory/sources/schemas.rs
@@ -735,9 +735,11 @@ fn handle_coding_session_status(_params: Map<String, Value>) -> ControllerFuture
fn handle_ingest_coding_sessions(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let req = parse_value::<tinymemory_core::tinycortex::CodingSessionIngestRequest>(
- Value::Object(params),
- )?;
+ // `rpc::CodingSessionIngestRequest`, not the engine path: this adapter
+ // names its own domain's request type, the way every sibling here does.
+ // See the re-export's docs in `rpc.rs` for why the type is still the
+ // engine's underneath (#5560).
+ let req = parse_value::<rpc::CodingSessionIngestRequest>(Value::Object(params))?;
to_json(rpc::ingest_coding_sessions_rpc(req).await?)
})
}
diff --git a/src/openhuman/memory/sync/composio/bus.rs b/src/openhuman/memory/sync/composio/bus.rs
index fac528bfb9..fa19bc6677 100644
--- a/src/openhuman/memory/sync/composio/bus.rs
+++ b/src/openhuman/memory/sync/composio/bus.rs
@@ -389,11 +389,13 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
// The classifier named here is the host's own. The
// engine crate exposes a `report_error_or_expected` of its
// own, but that is a global slot for *extracted* code to
- // report through, and the reporter installed into it
- // (`memory::host_impls::OpenHumanErrorReporter`) forwards
- // verbatim to this function. This subscriber is host code,
- // so the detour buys nothing and only costs an engine
- // dependency the seam is trying to shed (#5560).
+ // report through — installed by whichever process embeds
+ // the engine, which since #5560 is the loaded TinyMemory
+ // module and no longer this one (`memory/host_impls.rs`,
+ // the host's installer, is deleted; `modules/memory_host.rs`
+ // is the bus-served twin). This subscriber is host code, so
+ // the detour buys nothing and only costs an engine
+ // dependency the seam is trying to shed.
crate::core::observability::report_error_or_expected(
detail.as_str(),
"composio",
diff --git a/src/openhuman/memory/sync/composio/mod.rs b/src/openhuman/memory/sync/composio/mod.rs
index 7f59225867..5b60790de4 100644
--- a/src/openhuman/memory/sync/composio/mod.rs
+++ b/src/openhuman/memory/sync/composio/mod.rs
@@ -5,28 +5,51 @@
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::sync::composio::…` path resolving.
//!
-//! # This shim outlives its usefulness the day the in-process engine goes
+//! # This shim cannot go yet, and the reason is upstream, not here
//!
//! The glob below is what makes `integrations::composio::start_periodic_sync`
//! resolve, and therefore what lets `core/runtime/services.rs` start an engine
//! sync loop inside the host process. openhuman#5560 deletes the second,
-//! in-process engine and leaves the loaded TinyMemory module as the only one;
-//! after that this re-export names a crate the host no longer has a live engine
-//! for, and the periodic loop it exposes has nothing to run against.
+//! in-process engine and leaves the loaded TinyMemory module as the only one,
+//! so the obvious reading is that this file goes with it.
//!
-//! It must not be deleted first, and the ordering is the point. Composio sync
-//! degrades **quietly** — an unwired `ComposioHost` makes `is_available` read
-//! `false` and a sync run report zero connections, which nobody can tell apart
-//! from a user with none. So a half-removed loop looks like a working one for
-//! as long as it takes someone to notice their mail stopped being indexed.
+//! **It does not, and this was checked against the pinned artifact rather than
+//! assumed.** `modules::registry` pins `tinymemory` v1.5.0, whose module
+//! carries a section headed *"The periodic sync loops are deliberately NOT
+//! started here"* (`tinymemory-module/src/lib.rs`, right after
+//! `start_queue_pool`). It names three reasons the loops cannot move yet, none
+//! of which a host change can close:
+//!
+//! 1. The pipeline reads Composio credentials off `Config`, not off the
+//! `ComposioHost` seam — `composio_config` takes the direct-mode branch only
+//! when `config.composio().mode == "direct"` and otherwise wants
+//! `config.session_token()`, and the module's `EngineRuntimeConfig` answers
+//! neither. Routing it through `ComposioHost::execute` is a change to the
+//! *engine's* contract.
+//! 2. `global::client_if_ready()` is `None` inside the module — it builds its
+//! store through `create_memory_client_with_local_ai`, which never touches
+//! the global slot.
+//! 3. `EngineRuntimeConfig::memory_sync_interval_secs()` answers `Some(0)`,
+//! which the contract defines as *manual only*, so every tick would skip
+//! every source silently.
+//!
+//! The queue pool **did** move in v1.5.0, which is why `services.rs` no longer
+//! calls `queue::start` — do not read that as precedent for these two.
+//!
+//! So the ordering stands, with one step still open. Composio sync degrades
+//! **quietly** — an unwired `ComposioHost` makes `is_available` read `false`
+//! and a sync run report zero connections, which nobody can tell apart from a
+//! user with none. A half-removed loop looks like a working one for as long as
+//! it takes someone to notice their mail stopped being indexed.
//!
//! The full ordered list lives next to the call site it protects, in
//! `core/runtime/services.rs`'s `start_bootstrap_jobs`. In short: the host
-//! serves `ComposioHost` on the module bus (done — `modules/memory_host.rs`),
-//! the module installs a bus-backed seam for it and starts the loop itself, a
-//! `tinymemory` release carries both and `modules::registry` is re-pinned to
-//! its digest — **then** this file and that call go, together with the
-//! in-process engine.
+//! serves `ComposioHost` on the module bus (**done** — `modules/memory_host.rs`),
+//! the module installs a bus-backed seam for it (**done** in v1.5.0 —
+//! `composio::BusComposioHost`) **and starts the loop itself** (⛔ *not done*,
+//! for the three reasons above), a `tinymemory` release carries all of it and
+//! `modules::registry` is re-pinned to its digest — **then** this file and that
+//! call go.
pub use tinymemory_core::sync::composio::*;
diff --git a/src/openhuman/memory/sync/sync_status/mod.rs b/src/openhuman/memory/sync/sync_status/mod.rs
index 4e0521d8d5..6ad6bacebf 100644
--- a/src/openhuman/memory/sync/sync_status/mod.rs
+++ b/src/openhuman/memory/sync/sync_status/mod.rs
@@ -1,11 +1,44 @@
-//! Host layer over [`tinymemory_core::sync::sync_status`].
+//! Host layer over the engine's sync-status vocabulary.
//!
-//! The domain itself lives in the extracted crate; what stays here is its
-//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
-//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
-//! The glob re-export keeps every historical `memory::sync::sync_status::…` path resolving.
+//! The domain itself lives in the engine; what stays here is its JSON-RPC
+//! surface — handlers and controller schemas name OpenHuman's `RpcOutcome` and
+//! `ControllerSchema`, which the engine crate cannot see. The re-export below
+//! keeps every historical `memory::sync::sync_status::…` path resolving.
+//!
+//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//!
+//! It used to read `pub use tinymemory_core::sync::sync_status::*;`, and that
+//! glob had exactly two `pub` items — `FreshnessLabel` and `MemorySyncStatus`.
+//! **Neither was the one this domain actually returns.** `rpc::status_list_rpc`
+//! builds its reply from `tinycortex::memory::sync::{StatusListResponse,
+//! MemorySyncStatus}`, produced by `tinycortex`'s SQLite-backed
+//! `list_sync_statuses`; `tinymemory-core`'s pair is a second declaration of
+//! the same two shapes with no producer behind it. Its own module doc says so:
+//! "today the only *producer* is the engine's SQLite-backed
+//! `list_sync_statuses`, which OpenHuman still calls directly … the serde shape
+//! matches the engine's copy field for field."
+//!
+//! So this is not a substitute — it is the **same two items**, named through
+//! the crate that defines them instead of through a twin. Verified rather than
+//! assumed: both `FreshnessLabel`s are `#[serde(rename_all = "snake_case")]`
+//! over `Active`/`Recent`/`Idle` with the identical `from_age_ms` thresholds
+//! (30s → `Active`, 5min → `Recent`, else `Idle`), and both `MemorySyncStatus`
+//! carry the same seven fields in the same order.
+//!
+//! That matters because `tinymemory-core` is what #5560 removes from the
+//! production dependency graph, while `tinycortex` stays — it is a direct
+//! dependency of this crate (`Cargo.toml`), it is where the engine actually
+//! lives, and `rpc.rs` in this very directory already names
+//! `tinycortex::memory::sync`. Same precedent as `memory::people`, which
+//! repointed for the same reason.
+//!
+//! **Named, not globbed, and that is deliberate.** `tinycortex::memory::sync`
+//! re-exports ~50 items — every sync pipeline, `SyncState`, `SyncDispatcher`,
+//! the audit log — and pouring those into `memory::sync::sync_status::*` would
+//! widen this path far past the two names the old glob carried. Two names in,
+//! two names out.
-pub use tinymemory_core::sync::sync_status::*;
+pub use tinycortex::memory::sync::{FreshnessLabel, MemorySyncStatus};
pub mod rpc;
pub mod schemas;
diff --git a/src/openhuman/memory/tool_memory/mod.rs b/src/openhuman/memory/tool_memory/mod.rs
index 25e7d0591c..df05b16b8a 100644
--- a/src/openhuman/memory/tool_memory/mod.rs
+++ b/src/openhuman/memory/tool_memory/mod.rs
@@ -1,11 +1,75 @@
-//! Host layer over [`tinymemory_core::tool_memory`].
+//! Host layer over the engine's tool-memory domain.
//!
-//! The rule store and its types are core. What stays here is the pair that
-//! plugs into the agent harness — the post-turn capture hook and the system
-//! prompt section — both of which name harness traits (`PostTurnHook`,
+//! The rule store and its types are the engine's. What stays here is the pair
+//! that plugs into the agent harness — the post-turn capture hook and the
+//! system prompt section — both of which name harness traits (`PostTurnHook`,
//! `PromptContext`) that the engine crate cannot see.
+//!
+//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//!
+//! This module used to be `pub use tinymemory_core::tool_memory::*;`, and that
+//! glob resolved to three different places:
+//!
+//! | Name | Where it really lives |
+//! | --- | --- |
+//! | `ToolMemoryStore`, `TOOL_MEMORY_PROMPT_CAP` | `tinycortex::memory::tool_memory::store` |
+//! | `tool_memory_namespace`, `ToolMemoryPriority`, `ToolMemoryRule`, `ToolMemorySource` | `tinycortex::memory::tool_memory::types` |
+//! | `tool_memory_store` | a ten-line constructor in `tinymemory-core` |
+//! | `test_helpers` | `tinymemory-core`, behind `cfg(any(test, feature = "test-support"))` |
+//!
+//! The first two rows are named at `tinycortex` directly now. They are the
+//! **same items** either way — `tinymemory_core::tool_memory` re-exported them
+//! out of `crate::engine::backend::tool_memory`, which is itself
+//! `pub use tinycortex::memory::tool_memory` — so this changes no type, only
+//! which crate alias holds it in the build. `tinycortex` stays a direct
+//! dependency of this crate; `tinymemory-core` is the one #5560 removes.
+//!
+//! The third row came home: [`tool_memory_store`] below is the same one-line
+//! `ToolMemoryStore::new` wrapper, and it was only in the engine crate because
+//! that crate used to be this host's memory layer. Nothing in `tinymemory`
+//! named it.
+//!
+//! The fourth row is **test-only** and stays on the engine crate deliberately:
+//! `MockMemory` is a test fixture reached from three inline `#[cfg(test)]`
+//! modules, and `cfg(test)` code links against the `tinymemory-core`
+//! **dev-dependency** (declared with `features = ["test-support"]`), which
+//! survives the shed. It is not a production reference and does not keep the
+//! engine crate in the shipped binary.
+
+use std::sync::Arc;
+
+// The contract's storage trait, named at the contract rather than through
+// `memory::Memory` — same item, one less alias to follow.
+use tinymemory_api::traits::Memory;
-pub use tinymemory_core::tool_memory::*;
+pub use tinycortex::memory::tool_memory::{
+ store::{ToolMemoryStore, TOOL_MEMORY_PROMPT_CAP},
+ types::{tool_memory_namespace, ToolMemoryPriority, ToolMemoryRule, ToolMemorySource},
+};
pub mod capture;
pub mod prompt;
+
+/// Build the rule store over OpenHuman's shared memory object.
+///
+/// A named constructor rather than `ToolMemoryStore::new` at each call site:
+/// every caller (`capture.rs`, the harness session builder, the raw-coverage
+/// suite) passes the same `Arc<dyn Memory>` the host already holds, and the
+/// indirection is what let the store's own construction move between crates
+/// without touching them. Kept for exactly that reason.
+pub fn tool_memory_store(memory: Arc<dyn Memory>) -> ToolMemoryStore {
+ log::trace!("[memory::tool_memory] building ToolMemoryStore over the host memory object");
+ ToolMemoryStore::new(memory)
+}
+
+/// The engine crate's `MockMemory` fixture, under its historical path.
+///
+/// Test-only in both directions: `tinymemory-core` compiles this module behind
+/// `cfg(any(test, feature = "test-support"))`, and this re-export is
+/// `#[cfg(test)]`, so it exists only in `cargo test --lib` builds where the
+/// dev-dependency at `Cargo.toml`'s `[dev-dependencies]` supplies the crate.
+/// Three inline `#[cfg(test)]` modules reach it —
+/// `agent::experience::{capture, store}` and
+/// `agent::tinyagents::host::experience_store`.
+#[cfg(test)]
+pub use tinymemory_core::tool_memory::test_helpers;
diff --git a/src/openhuman/memory/tools/diff.rs b/src/openhuman/memory/tools/diff.rs
index db2cfd4dc2..eb94335dde 100644
--- a/src/openhuman/memory/tools/diff.rs
+++ b/src/openhuman/memory/tools/diff.rs
@@ -11,6 +11,13 @@ use crate::openhuman::config::rpc as config_rpc;
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};
use crate::openhuman::memory::diff::ops;
+// The host path, matching the six other call sites that read this
+// registry (`memory::diff::rpc`, `memory::sync::composio::bus`,
+// `integrations::composio::ops::connections`). This tool was the one
+// place that named the engine crate for it; the registry itself is
+// still `tinymemory_core::sources` behind `memory::sources` — see that
+// module's docs for what has to move before the name goes away (#5560).
+use crate::openhuman::memory::sources;
use tinycortex::memory::diff::types::*;
pub struct MemoryDiffTool;
@@ -105,7 +112,7 @@ impl Tool for MemoryDiffTool {
if let Some(sid) = source_id {
debug!("[memory_diff][tool] branch=source_diff source_id={sid}");
- let source = tinymemory_core::sources::get_source(sid)
+ let source = sources::get_source(sid)
.await
.map_err(|e| anyhow::anyhow!(e))?
.ok_or_else(|| anyhow::anyhow!("source not found: {sid}"))?;
@@ -125,7 +132,7 @@ impl Tool for MemoryDiffTool {
debug!("[memory_diff][tool] branch=list_sources");
// No source_id or checkpoint_id: list sources with snapshot counts
- let sources = tinymemory_core::sources::list_sources()
+ let sources = sources::list_sources()
.await
.map_err(|e| anyhow::anyhow!(e))?;
diff --git a/src/openhuman/memory/tools/flavour.rs b/src/openhuman/memory/tools/flavour.rs
index 24126b55dd..72be75a7b6 100644
--- a/src/openhuman/memory/tools/flavour.rs
+++ b/src/openhuman/memory/tools/flavour.rs
@@ -24,6 +24,25 @@ use tinycortex::memory::tree::{compile_flavoured_root, flavoured_root_abs_path};
use crate::openhuman::config::Config;
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};
+// The `Config` → `tinycortex::memory::MemoryConfig` mapping, and the one engine
+// reference left in this file (#5560).
+//
+// It cannot be repointed at `tinycortex` — the mapping is `tinymemory-core`'s
+// own (`engine/config.rs`), not a re-export — and it cannot be reimplemented
+// here. Two of its three assignments are trivial (`workspace`, `content_root`);
+// the third sets `embedding.provider` from `effective_embedder_slug`, the
+// engine's embedder-resolution ladder, and that field is the *signature every
+// per-model embedding sidecar row is keyed by*. A host-side twin of that ladder
+// would be a second copy of the function whose whole documented purpose is that
+// `config.memory().embedding_provider` is not authoritative — and a copy that
+// drifted would file locally-produced vectors under the cloud provider.
+//
+// It also is not this file's to fix alone: four other host call sites take the
+// same helper (`memory::sync::sync_status::rpc`,
+// `agent::harness::archivist::{hook_impl, recap}`, plus the archivist tests),
+// so the mapping needs one home, host-side, once the engine-config seam moves.
+// There is no contract member for it and there should not be — the contract is
+// deliberately engine-neutral and `MemoryConfig` is TinyCortex's runtime shape.
use tinymemory_core::tinycortex::memory_config_from;
/// The seven valid `flavour` slugs, for error messages.
diff --git a/src/openhuman/security/credentials/ops.rs b/src/openhuman/security/credentials/ops.rs
index 28481b733e..ee35ba5fb2 100644
--- a/src/openhuman/security/credentials/ops.rs
+++ b/src/openhuman/security/credentials/ops.rs
@@ -592,16 +592,26 @@ async fn store_session_inner(
logs.push("session stored".to_string());
- match tinymemory_core::global::init(effective_config.workspace_dir.clone()) {
- Ok(_) => logs.push(format!(
- "memory client bound to workspace {}",
- effective_config.workspace_dir.display()
- )),
- Err(e) => {
- tracing::warn!(error = %e, "[credentials] failed to bind memory client after login");
- logs.push(format!("memory client bind warning: {e}"));
- }
- }
+ // ── No explicit memory re-point here any more (#5560) ──────────────────
+ //
+ // This site used to call `tinymemory_core::global::init(...)` before the
+ // context rebind below. That was load-bearing for the *engine singleton*: a
+ // single process-global slot that keeps writing into the pre-login
+ // workspace until something re-points it, which is why it needed its own
+ // call at every login / logout / revalidation site.
+ //
+ // `memory::binding` is a workspace-keyed cache, not a slot, and
+ // `CoreContext::memory_binding`'s own docs already state the consequence:
+ // "there is **no** explicit 'rebind the memory driver' call at the login /
+ // logout / revalidation sites the way `memory::global::init` needs one: the
+ // accessor keys on the workspace dir and the subsystem config, both of
+ // which those sites already re-point." The `rebind_default_workspace` call
+ // immediately below re-points both, so memory follows it by construction.
+ //
+ // The binding is resolved lazily on the next memory call rather than warmed
+ // here. Warming it would mean naming `binding::for_workspace` at a site
+ // that never touches memory content, which the memory-guard bypass ratchet
+ // is right to treat as reach-through.
match crate::core::runtime::context::CoreContext::rebind_default_workspace(
&effective_config.workspace_dir,
effective_config.subsystems.memory.clone(),
@@ -832,9 +842,10 @@ pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Val
match crate::openhuman::config::load_config_with_timeout().await {
Ok(signed_out_config) => {
let workspace = signed_out_config.workspace_dir.clone();
- if let Err(error) = tinymemory_core::global::init(workspace.clone()) {
- tracing::warn!(%error, "failed to rebind memory after logout");
- }
+ // No `memory::global::init` twin here either — see the login site.
+ // The context rebind below carries the signed-out workspace and its
+ // `[subsystems.memory]` block, and the memory binding is keyed on
+ // exactly that pair, so it follows without a second call.
if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(
&workspace,
signed_out_config.subsystems.memory.clone(),