Skip to content

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

Route the remaining engine-handle, tree and archivist paths through the contract

Shanu7a42783789fa
diff --git a/src/bin/library_profile/scenarios/cold_phases.rs b/src/bin/library_profile/scenarios/cold_phases.rs
index c643980efe..b582e71c73 100644
--- a/src/bin/library_profile/scenarios/cold_phases.rs
+++ b/src/bin/library_profile/scenarios/cold_phases.rs
@@ -1,6 +1,20 @@
//! `cold-phases`: sequential per-phase checkpoints of the cold bootstrap, all
//! inside one measured region. Each phase is sampled right after it completes
//! so the JSON `checkpoints` series attributes the cold-start cost per phase.
+//!
+//! # Why this still names the engine crate (#5560)
+//!
+//! Phase (e) exists to time **opening the SQLite memory store**, and
+//! `MemoryClient` is the thing that opens it. `memory::binding::for_config`
+//! would resolve the null driver in this binary — no module is loaded — so the
+//! checkpoint would report the cost of binding a driver that opens nothing, and
+//! the cold-start series would silently lose its heaviest I/O phase rather than
+//! gain a migration. `MemoryClient` is also `tinymemory-core`'s own type, not a
+//! re-export of a TinyCortex one, so there is no path swap available either.
+//!
+//! Same conclusion as the sibling `memory_ingest` scenario: this is a
+//! **feature-gate** case, not a migration. See that module's note for what the
+//! manifest needs (`tinymemory-core` optional, enabled by `rss-bench`).
use std::time::Duration;
diff --git a/src/bin/library_profile/scenarios/memory_ingest.rs b/src/bin/library_profile/scenarios/memory_ingest.rs
index 18e66f7948..252afe9c34 100644
--- a/src/bin/library_profile/scenarios/memory_ingest.rs
+++ b/src/bin/library_profile/scenarios/memory_ingest.rs
@@ -1,5 +1,25 @@
//! `memory-ingest`: canonicalise and ingest 100 chat messages, then drain the
//! real extraction/admission/tree queue.
+//!
+//! # Why this still names the engine crate (#5560)
+//!
+//! It is measuring the in-process engine on purpose, and routing it through
+//! `memory::binding` would not be a migration — it would be a different
+//! measurement. `MemoryIngest::ingest_chat` on the contract hands items to
+//! whatever driver the workspace bound, which in this binary is the **null**
+//! driver (no module is loaded), so the number would be the cost of doing
+//! nothing. And `queue::drain_until_idle` has no contract member at all: the
+//! queue is not a capability family, and the point of this scenario is that the
+//! extraction/admission/tree jobs actually run before the timer stops.
+//!
+//! So the honest fix here is a **feature gate, not a migration** — this binary
+//! carries `required-features = ["rss-bench"]` and is local/dev only, and
+//! `rss-bench` is deliberately absent from `scripts/ci/product-features.txt`,
+//! so nothing here is in the shipped product graph. What it needs from the
+//! manifest is for `tinymemory-core` to become `optional = true` with
+//! `rss-bench` enabling it; a bin target cannot use dev-dependencies, so
+//! demoting the crate to dev-only without that would break this build with the
+//! gate on, in a configuration no CI lane compiles.
use anyhow::Result;
use chrono::{TimeZone, Utc};
diff --git a/src/openhuman/agent/experience/ops.rs b/src/openhuman/agent/experience/ops.rs
index 8b344278b1..0a53d24810 100644
--- a/src/openhuman/agent/experience/ops.rs
+++ b/src/openhuman/agent/experience/ops.rs
@@ -1,3 +1,7 @@
+//! JSON-RPC handlers for the agent-experience store, and the adapter that lets
+//! it read and write through the **bound memory driver** instead of an
+//! in-process engine handle (openhuman#5560).
+
use serde::{Deserialize, Serialize};
use crate::openhuman::agent::experience::store::{
@@ -5,10 +9,229 @@ use crate::openhuman::agent::experience::store::{
};
use crate::openhuman::agent::experience::types::{AgentExperience, ExperienceHit};
use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::health::MemoryHealth;
+// `MemoryCore` and `MemoryRecall` are deliberately NOT imported: their methods
+// are reached on a `dyn MemoryProvider` receiver, where supertrait methods are
+// inherent object candidates rather than in-scope-trait candidates — so an
+// import of either would be flagged unused and fail `clippy -D warnings`.
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use crate::openhuman::memory::api::recall::OwnedRecallOpts;
+use crate::openhuman::memory::api::types::{
+ MemoryCategory, MemoryEntry, MemoryTaint, NamespaceSummary, RecallOpts,
+};
+use crate::openhuman::memory::Memory;
use crate::rpc::RpcOutcome;
+use async_trait::async_trait;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
+/// The [`Memory`] view of a bound memory driver.
+///
+/// # Why this exists
+///
+/// [`AgentExperienceStore`] is built on `Arc<dyn Memory>` — the storage trait
+/// `tinymemory-api` exports — and the driver contract has no door that hands one
+/// out. Before #5560 the host closed that gap with the in-process engine's own
+/// `MemoryClient::memory_handle()`, which meant every experience read and write
+/// went through a **second** engine over the same SQLite file as the loaded
+/// TinyMemory module. This adapter closes it the other way round: `Memory`'s
+/// methods are a subset of what `MemoryCore` and `MemoryRecall` already
+/// promise, so the whole trait can be served from the bound driver with nothing
+/// added to the contract.
+///
+/// # It wraps the driver, not the guard, and that is deliberate
+///
+/// [`MemoryGuard`](crate::openhuman::memory::guard::MemoryGuard) truncates
+/// `store` content at `capture_max_chars`, which
+/// `MemoryHooksConfig::default()` sets to **500**. An `AgentExperience` is
+/// stored as base64 of its serialized JSON — precisely so the free-text
+/// scrubber cannot rewrite a Luhn-valid millisecond timestamp and corrupt the
+/// payload (#5209) — and truncated base64 does not decode, so the record would
+/// silently vanish on read. That is the same class of bug #5209 fixed, so the
+/// pre-#5560 behaviour is preserved exactly: no policy layer between this store
+/// and the driver. The store runs the full scrubber over its own free-text
+/// fields before serialization (`store::redact_experience`), which is what
+/// keeps that safe rather than merely unguarded.
+///
+/// # Home
+///
+/// This belongs in `src/openhuman/memory/`, next to `binding`, not under
+/// `agent::experience` — it is contract-to-trait plumbing, not an
+/// agent-experience concept. It sits here because both of its callers do
+/// (`open_store_in_subdir` below, and the session builder's
+/// `shared_experience_memory`).
+pub struct DriverMemory {
+ provider: Arc<dyn MemoryProvider>,
+}
+
+impl DriverMemory {
+ /// Wrap an already-resolved driver.
+ pub fn new(provider: Arc<dyn MemoryProvider>) -> Self {
+ Self { provider }
+ }
+
+ /// The driver bound for `config`'s workspace and shared `memory` subtree.
+ ///
+ /// # Errors
+ ///
+ /// Only binding-cache lock poisoning: an inadmissible driver falls back to
+ /// the null driver loudly rather than failing here (kernel.md §3.7).
+ pub fn for_config(config: &Config) -> Result<Arc<dyn Memory>, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ log::debug!(
+ "[agent-experience] bound shared memory subtree driver='{}'",
+ binding.driver_id()
+ );
+ let memory: Arc<dyn Memory> = Arc::new(Self::new(binding.provider().clone()));
+ Ok(memory)
+ }
+
+ /// The driver bound for one memory subtree of `config`'s workspace.
+ ///
+ /// `"memory"` is the shared tree; `"memory-<id>"` is a profile that opted
+ /// into dedicated memory. Each subtree is its own binding and therefore its
+ /// own store, which is what makes `dedicatedMemory` isolation hold.
+ ///
+ /// # Errors
+ ///
+ /// As [`Self::for_config`].
+ pub fn for_subtree(config: &Config, memory_subdir: &str) -> Result<Arc<dyn Memory>, String> {
+ let binding = crate::openhuman::memory::binding::for_subtree(
+ &config.workspace_dir,
+ memory_subdir,
+ &config.subsystems.memory,
+ )?;
+ log::debug!(
+ "[agent-experience] bound memory subtree '{memory_subdir}' driver='{}'",
+ binding.driver_id()
+ );
+ let memory: Arc<dyn Memory> = Arc::new(Self::new(binding.provider().clone()));
+ Ok(memory)
+ }
+}
+
+#[async_trait]
+impl Memory for DriverMemory {
+ /// The **driver's** id, not a synthetic name: this string reaches logs and
+ /// status output, which should name whatever actually stores the bytes.
+ fn name(&self) -> &str {
+ self.provider.driver_id()
+ }
+
+ async fn store(
+ &self,
+ namespace: &str,
+ key: &str,
+ content: &str,
+ category: MemoryCategory,
+ session_id: Option<&str>,
+ ) -> anyhow::Result<()> {
+ Ok(self
+ .provider
+ .store(
+ namespace,
+ key,
+ content,
+ category,
+ session_id,
+ MemoryTaint::Internal,
+ )
+ .await?)
+ }
+
+ /// Overridden rather than inherited. The trait's default *bails* for any
+ /// taint other than `Internal`, so inheriting it would turn a sync path's
+ /// `ExternalSync` write into an error against a driver that records taint
+ /// perfectly well.
+ async fn store_with_taint(
+ &self,
+ namespace: &str,
+ key: &str,
+ content: &str,
+ category: MemoryCategory,
+ session_id: Option<&str>,
+ taint: MemoryTaint,
+ ) -> anyhow::Result<()> {
+ Ok(self
+ .provider
+ .store(namespace, key, content, category, session_id, taint)
+ .await?)
+ }
+
+ /// `scope` is passed explicitly, never left to ambient state.
+ ///
+ /// The per-turn source allowlist is a `tokio::task_local` and task-locals
+ /// do not cross the bus — a module reads an unset one as *unrestricted*, so
+ /// a call that relied on the driver picking it up would fail open. Rendering
+ /// it host-side with `source_scope::as_bus_scope()` is the rule the whole
+ /// memory seam follows.
+ async fn recall(
+ &self,
+ query: &str,
+ limit: usize,
+ opts: RecallOpts<'_>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ let owned: OwnedRecallOpts = opts.into();
+ let scope = crate::openhuman::memory::source_scope::as_bus_scope();
+ Ok(self
+ .provider
+ .recall(query, limit, &owned, scope.as_ref())
+ .await?)
+ }
+
+ // `recall_relevant_by_vector` is deliberately left on the trait's default.
+ // The contract has no vector-threshold recall member, and the trait
+ // defines the default as the documented opt-out for a backend that cannot
+ // answer it ("keyword-only / mock backends opt out"), not as a swallowed
+ // failure. The consumer that cares — situational preferences
+ // (`memory::preferences`, Lane B) — already treats an empty answer as "no
+ // block to inject" rather than as a broken turn, and it is reached through
+ // the session's own memory handle, not through this adapter.
+
+ async fn get(&self, namespace: &str, key: &str) -> anyhow::Result<Option<MemoryEntry>> {
+ Ok(self.provider.get(namespace, key).await?)
+ }
+
+ async fn list(
+ &self,
+ namespace: Option<&str>,
+ category: Option<&MemoryCategory>,
+ session_id: Option<&str>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ Ok(self.provider.list(namespace, category, session_id).await?)
+ }
+
+ async fn forget(&self, namespace: &str, key: &str) -> anyhow::Result<bool> {
+ Ok(self.provider.forget(namespace, key).await?)
+ }
+
+ async fn namespace_summaries(&self) -> anyhow::Result<Vec<NamespaceSummary>> {
+ Ok(self.provider.namespaces().await?)
+ }
+
+ /// Summed from the per-namespace counts the driver already reports, rather
+ /// than from `list(None, None, None).len()`: the two answer the same
+ /// question and only one of them pulls every entry's content across the bus
+ /// to do it.
+ async fn count(&self) -> anyhow::Result<usize> {
+ let summaries = self.provider.namespaces().await?;
+ Ok(summaries.iter().map(|summary| summary.count).sum())
+ }
+
+ /// `Degraded` counts as healthy here because the trait asks whether the
+ /// backend is "reachable and able to serve requests" — a degraded driver
+ /// is both. Only `Down` is false.
+ async fn health_check(&self) -> bool {
+ !matches!(self.provider.health().await, MemoryHealth::Down { .. })
+ }
+
+ /// The typed answer, so callers get the driver's own reason string instead
+ /// of falling back to the boolean above.
+ async fn health_probe(&self) -> Option<MemoryHealth> {
+ Some(self.provider.health().await)
+ }
+}
+
#[derive(Debug, Deserialize)]
pub struct CaptureParams {
pub experience: AgentExperience,
@@ -72,52 +295,48 @@ fn profile_memory_subdir(
))
}
+/// The experience store for `profile_id`'s memory subtree.
+///
+/// Both arms used to resolve the in-process engine — `global::client_if_ready()`
+/// with a `global::init` fallback for the shared tree, a freshly constructed
+/// `UnifiedMemory` for a dedicated one. Neither exists any more (#5560): both
+/// arms now go through [`DriverMemory::for_subtree`], with `"memory"` naming the
+/// shared tree. That is the same workspace-and-subtree binding key the session
+/// builder already resolves for the archivist, so the two cannot end up on
+/// different stores for one profile.
async fn open_store(profile_id: Option<&str>) -> Result<AgentExperienceStore, String> {
let profile_id = profile_id.map(str::trim).filter(|id| !id.is_empty());
- if profile_id.is_none() {
- let client = match tinymemory_core::global::client_if_ready() {
- Some(client) => client,
- None => {
- let config = Config::load_or_init()
- .await
- .map_err(|e| format!("load config: {e}"))?;
- tinymemory_core::global::init(config.workspace_dir)?
- }
- };
- return Ok(AgentExperienceStore::new(client.memory_handle()));
- }
-
let config = Config::load_or_init()
.await
.map_err(|e| format!("load config: {e}"))?;
+ if profile_id.is_none() {
+ return open_store_in_subdir(&config, "memory").await;
+ }
+
let memory_subdir = profile_memory_subdir(&config.workspace_dir, profile_id)?;
open_store_in_subdir(&config, &memory_subdir).await
}
+/// The experience store over one named memory subtree of `config`'s workspace.
+///
+/// # The embedder moved with the store, and that is the intended delta
+///
+/// The dedicated-subtree arm used to build its own `UnifiedMemory` with a
+/// config-scoped embedding provider, so that the experience store's managed
+/// embedder read the signed-in user's session rather than the keyless
+/// `default_state_dir()` scope (#5501). The bound driver embeds with the
+/// embedder the module policy publishes — which is that same user-scoped one,
+/// resolved once at boot instead of per store — so #5501's fix survives the
+/// move. What is gone is this call site's ability to choose a *different*
+/// embedder from the rest of the subsystem, which was never the point.
async fn open_store_in_subdir(
config: &Config,
memory_subdir: &str,
) -> Result<AgentExperienceStore, String> {
- if memory_subdir != "memory" {
- let memory = tinymemory_core::store::UnifiedMemory::new_with_memory_dir(
- &config.workspace_dir,
- memory_subdir,
- // Config-scoped so the experience store's managed embedder reads the
- // signed-in user's session, not the keyless `default_state_dir()`
- // scope (#5501).
- crate::openhuman::inference::embeddings::default_embedding_provider_with_config(config),
- config.memory.sqlite_open_timeout_secs,
- )
- .map_err(|e| format!("open agent experience store '{memory_subdir}': {e:#}"))?;
- return Ok(AgentExperienceStore::new(Arc::new(memory)));
- }
-
- let client = match tinymemory_core::global::client_if_ready() {
- Some(client) => client,
- None => tinymemory_core::global::init(config.workspace_dir.clone())?,
- };
- Ok(AgentExperienceStore::new(client.memory_handle()))
+ let memory = DriverMemory::for_subtree(config, memory_subdir)
+ .map_err(|e| format!("open agent experience store '{memory_subdir}': {e}"))?;
+ Ok(AgentExperienceStore::new(memory))
}
fn query_memory_subdirs(
@@ -263,4 +482,112 @@ mod tests {
vec!["memory".to_string(), "memory-alice".to_string()]
);
}
+
+ /// A config on a disposable workspace with the in-process TinyCortex driver
+ /// bound to it.
+ ///
+ /// A test workspace with nothing installed resolves to the **null** driver,
+ /// which serves nothing and discards writes — so a round-trip through
+ /// [`DriverMemory`] would fail in a way that looks like a bug in the
+ /// adapter. TinyCortex is the engine the loadable module wraps, so binding
+ /// it exercises the same store production reaches over the bus, and unlike
+ /// the module it is not a process singleton.
+ fn bound_config() -> (tempfile::TempDir, Config) {
+ let tmp = tempfile::TempDir::new().expect("tempdir");
+ let mut config = Config::default();
+ config.workspace_dir = tmp.path().to_path_buf();
+ config.config_path = tmp.path().join("config.toml");
+ // Keep the round-trip hermetic: `"none"` routes to the inert embedder
+ // rather than a live embedding service.
+ config.embeddings_provider = Some("none".into());
+ config.memory_tree.embedding_endpoint = None;
+ config.memory_tree.embedding_model = None;
+ config.memory_tree.embedding_strict = false;
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
+ (tmp, config)
+ }
+
+ /// The adapter is a real `Memory` over the bound driver, not a shape that
+ /// merely compiles: what `store` writes, `get` and `list` read back.
+ #[tokio::test]
+ async fn driver_memory_round_trips_through_the_bound_driver() {
+ let (_tmp, config) = bound_config();
+ let memory = DriverMemory::for_subtree(&config, "memory").expect("bind driver");
+
+ // `name()` is the *driver's* id, so this doubles as the fixture's own
+ // canary: a workspace with no binding installed resolves to the null
+ // driver, which accepts writes and returns nothing — the round-trip
+ // below would then fail for the wrong reason.
+ assert_ne!(
+ memory.name(),
+ tinymemory_api::null::NULL_DRIVER_ID,
+ "the adapter must be over the bound driver, not the null fallback"
+ );
+
+ memory
+ .store(
+ "ops_adapter_ns",
+ "k1",
+ "adapter round trip",
+ MemoryCategory::Custom("ops_adapter_ns".into()),
+ None,
+ )
+ .await
+ .expect("store");
+
+ let fetched = memory.get("ops_adapter_ns", "k1").await.expect("get");
+ assert_eq!(
+ fetched.map(|entry| entry.content).as_deref(),
+ Some("adapter round trip")
+ );
+
+ let listed = memory
+ .list(Some("ops_adapter_ns"), None, None)
+ .await
+ .expect("list");
+ assert!(listed.iter().any(|entry| entry.key == "k1"));
+
+ assert!(memory.health_check().await, "a bound driver is reachable");
+ }
+
+ /// The experience store opened for a profile-less caller and the one opened
+ /// for the `"memory"` subtree are the same store — the shared-tree arm has
+ /// no special case any more.
+ #[tokio::test]
+ async fn experience_store_round_trips_over_the_bound_driver() {
+ let (_tmp, config) = bound_config();
+ let store = open_store_in_subdir(&config, "memory")
+ .await
+ .expect("open store");
+
+ let experience = AgentExperience {
+ id: "exp_adapter".into(),
+ created_at_ms: 1,
+ updated_at_ms: 1,
+ source: crate::openhuman::agent::experience::types::ExperienceSource::ToolLoop,
+ agent_id: None,
+ entrypoint: None,
+ profile_id: None,
+ task_fingerprint: "fp-adapter".into(),
+ task_summary: "route the experience store onto the contract".into(),
+ tools_used: Vec::new(),
+ tool_sequence: Vec::new(),
+ outcome: crate::openhuman::agent::experience::types::ExperienceOutcome::Success,
+ error_class: None,
+ lesson: "the bound driver is the store".into(),
+ reuse_hint: "open it through the binding".into(),
+ avoid_hint: None,
+ confidence: 0.9,
+ tags: Vec::new(),
+ payload_hash: None,
+ dismissed: false,
+ };
+
+ store.put(experience).await.expect("put");
+ let listed = store.list().await.expect("list");
+ assert!(
+ listed.iter().any(|item| item.id == "exp_adapter"),
+ "a record written through the bound driver must read back"
+ );
+ }
}
diff --git a/src/openhuman/agent/experience/store.rs b/src/openhuman/agent/experience/store.rs
index a4db82b58b..b629326c97 100644
--- a/src/openhuman/agent/experience/store.rs
+++ b/src/openhuman/agent/experience/store.rs
@@ -440,419 +440,5 @@ fn normalize(input: &str) -> String {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::agent::experience::types::{
- AgentExperience, ExperienceOutcome, ExperienceSource,
- };
- use crate::openhuman::memory::tool_memory::test_helpers::MockMemory;
- use std::sync::Arc;
-
- fn sample_experience(
- id: &str,
- task_summary: &str,
- tools: Vec<&str>,
- tags: Vec<&str>,
- confidence: f32,
- ) -> AgentExperience {
- let sequence = tools.iter().map(|tool| (*tool).to_string()).collect();
- AgentExperience {
- id: id.to_string(),
- created_at_ms: 1,
- updated_at_ms: 1,
- source: ExperienceSource::ToolLoop,
- agent_id: Some("orchestrator".into()),
- entrypoint: Some("chat".into()),
- profile_id: None,
- task_fingerprint: format!("fp-{id}"),
- task_summary: task_summary.to_string(),
- tools_used: tools.iter().map(|tool| (*tool).to_string()).collect(),
- tool_sequence: sequence,
- outcome: ExperienceOutcome::Success,
- error_class: None,
- lesson: format!("lesson for {task_summary}"),
- reuse_hint: format!("reuse for {task_summary}"),
- avoid_hint: None,
- confidence,
- tags: tags.iter().map(|tag| (*tag).to_string()).collect(),
- payload_hash: None,
- dismissed: false,
- }
- }
-
- fn fresh_store() -> (AgentExperienceStore, Arc<MockMemory>) {
- let memory = Arc::new(MockMemory::default());
- (AgentExperienceStore::new(memory.clone()), memory)
- }
-
- #[tokio::test]
- async fn put_list_and_dismiss_round_trip() {
- let (store, memory) = fresh_store();
- store
- .put(sample_experience(
- "exp_success",
- "search repository docs",
- vec!["grep", "file_read"],
- vec!["docs"],
- 0.8,
- ))
- .await
- .unwrap();
-
- assert!(memory.entries.lock().contains_key(&(
- AGENT_EXPERIENCE_NAMESPACE.into(),
- "experience/exp_success".into()
- )));
-
- let listed = store.list().await.unwrap();
- assert_eq!(listed.len(), 1);
- assert_eq!(listed[0].id, "exp_success");
-
- let dismissed = store.dismiss("exp_success").await.unwrap();
- assert!(dismissed);
- let listed = store.list().await.unwrap();
- assert_eq!(listed.len(), 1);
- assert!(listed[0].dismissed);
- }
-
- /// Regression for #5209. `Memory::store` runs document content through the
- /// free-text secret/PII sanitizer, whose credit-card (Luhn-gated) pattern
- /// matches any 13–19-digit run. A serialized experience carries bare 13-digit
- /// millisecond timestamps, so a Luhn-valid timestamp used to be rewritten to
- /// a `[REDACTED_PII_*]` token — corrupting the JSON so the record silently
- /// vanished on read (~10% of writes, whichever `now_ms()` happened to be
- /// Luhn-valid). Exercised over the *real* `UnifiedMemory` because `MockMemory`
- /// does not sanitize. `1785148840502` is a Luhn-valid 13-digit ms timestamp;
- /// `put` preserves a positive `created_at_ms`, so the corruption is forced
- /// deterministically rather than depending on the wall clock.
- #[tokio::test]
- async fn experience_survives_content_sanitizer_with_luhn_valid_timestamp() {
- use crate::openhuman::inference::embeddings::NoopEmbedding;
- use crate::openhuman::memory::Memory;
- use tinymemory_core::store::UnifiedMemory;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let memory: Arc<dyn Memory> =
- Arc::new(UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).unwrap());
- let store = AgentExperienceStore::new(memory);
-
- let mut experience = sample_experience(
- "exp_luhn",
- "Deploy the Rust service safely",
- vec![],
- vec![],
- 0.9,
- );
- // Luhn-valid 13-digit ms timestamp; preserved by `put` (positive value),
- // so the vulnerable numeric field is present on every run.
- experience.created_at_ms = 1_785_148_840_502;
- experience.lesson = "Legacy shared deployment guidance".into();
-
- store.put(experience).await.unwrap();
-
- let listed = store.list().await.unwrap();
- assert_eq!(
- listed.len(),
- 1,
- "experience must survive the memory content sanitizer round-trip"
- );
- assert_eq!(listed[0].lesson, "Legacy shared deployment guidance");
- assert_eq!(listed[0].created_at_ms, 1_785_148_840_502);
- }
-
- /// Security regression for PR #5211 review (P1). Base64-encoding the payload
- /// makes the memory layer's store-time content scrubber a no-op over the
- /// stored bytes, so the store must run the full scrubber over free-text
- /// fields itself before serialization ([`redact_experience`]). A secret in a
- /// captured free-text field must be redacted in the recalled record (so it
- /// is neither stored nor returned reversibly), while the numeric timestamp
- /// survives intact. Exercised over the real `UnifiedMemory` (the store path
- /// that base64 now shields).
- #[tokio::test]
- async fn secrets_in_free_text_are_redacted_before_storage() {
- use crate::openhuman::inference::embeddings::NoopEmbedding;
- use crate::openhuman::memory::Memory;
- use tinymemory_core::store::UnifiedMemory;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let memory: Arc<dyn Memory> =
- Arc::new(UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).unwrap());
- let store = AgentExperienceStore::new(memory);
-
- let mut experience =
- sample_experience("exp_secret", "deploy the service", vec![], vec![], 0.9);
- // Luhn-valid 13-digit ms timestamp; must survive intact (the #5209 fix).
- experience.created_at_ms = 1_785_148_840_502;
- experience.lesson =
- "provider token sk_live_12345678901234567890 then dial +15551234567".into();
- experience.reuse_hint =
- "-----BEGIN PRIVATE KEY-----\nMIIabc123\n-----END PRIVATE KEY-----".into();
- experience.error_class = Some("phone leaked: +15551234567".into());
-
- store.put(experience).await.unwrap();
-
- let listed = store.list().await.unwrap();
- assert_eq!(listed.len(), 1, "record must still parse and round-trip");
- let recalled = &listed[0];
-
- // (a) secrets are redacted in the recalled free-text fields.
- assert!(
- !recalled.lesson.contains("sk_live_12345678901234567890"),
- "Stripe key must be redacted, got: {}",
- recalled.lesson
- );
- assert!(
- !recalled.lesson.contains("+15551234567"),
- "phone number must be redacted, got: {}",
- recalled.lesson
- );
- assert!(
- !recalled.reuse_hint.contains("PRIVATE KEY"),
- "private-key block must be redacted, got: {}",
- recalled.reuse_hint
- );
- assert!(
- recalled
- .error_class
- .as_deref()
- .is_none_or(|e| !e.contains("+15551234567")),
- "phone in error_class must be redacted, got: {:?}",
- recalled.error_class
- );
- assert!(
- recalled.lesson.contains("REDACTED") && recalled.reuse_hint.contains("REDACTED"),
- "expected redaction markers in scrubbed fields"
- );
-
- // (b) the numeric timestamp survives intact and the record parses.
- assert_eq!(recalled.created_at_ms, 1_785_148_840_502);
- }
-
- #[tokio::test]
- async fn generated_ids_partition_identical_experiences_by_profile() {
- let (store, _) = fresh_store();
- let mut alice = sample_experience("", "same task", vec!["grep"], vec!["docs"], 0.8);
- alice.profile_id = Some("alice".into());
- let mut bob = alice.clone();
- bob.profile_id = Some("bob".into());
-
- let alice = store.put(alice).await.unwrap();
- let bob = store.put(bob).await.unwrap();
-
- assert_ne!(alice.id, bob.id);
- let listed = store.list().await.unwrap();
- assert_eq!(listed.len(), 2);
- assert!(listed
- .iter()
- .any(|item| item.profile_id.as_deref() == Some("alice")));
- assert!(listed
- .iter()
- .any(|item| item.profile_id.as_deref() == Some("bob")));
- }
-
- #[tokio::test]
- async fn retrieve_ranks_tool_and_query_matches() {
- let (store, _) = fresh_store();
- store
- .put(sample_experience(
- "exp_docs",
- "search repository docs",
- vec!["grep", "file_read"],
- vec!["docs"],
- 0.6,
- ))
- .await
- .unwrap();
- store
- .put(sample_experience(
- "exp_email",
- "send a careful email",
- vec!["email"],
- vec!["mail"],
- 1.0,
- ))
- .await
- .unwrap();
-
- let hits = store
- .retrieve(ExperienceQuery {
- query: "search docs with grep".into(),
- tools: vec!["grep".into()],
- tags: vec!["docs".into()],
- agent_id: Some("orchestrator".into()),
- entrypoint: Some("chat".into()),
- profile_id: None,
- max_hits: 2,
- })
- .await
- .unwrap();
-
- assert_eq!(hits.len(), 2);
- assert_eq!(hits[0].experience.id, "exp_docs");
- assert!(hits[0].score > hits[1].score);
- assert!(hits[0].match_reasons.contains(&"tool_overlap".into()));
- assert!(hits[0].match_reasons.contains(&"query_overlap".into()));
- }
-
- #[test]
- fn experience_matches_profile_partition_rules() {
- // Profile-less query sees everything.
- assert!(experience_matches_profile(None, None));
- assert!(experience_matches_profile(Some("p"), None));
- // Profiled query: own + legacy in, sibling out.
- assert!(experience_matches_profile(Some("p"), Some("p")));
- assert!(experience_matches_profile(None, Some("p")));
- assert!(!experience_matches_profile(Some("q"), Some("p")));
- }
-
- async fn seed_partitioned(store: &AgentExperienceStore) {
- let mut own = sample_experience("exp_p", "task p", vec!["grep"], vec!["docs"], 0.8);
- own.profile_id = Some("p".into());
- store.put(own).await.unwrap();
-
- let mut sibling = sample_experience("exp_q", "task q", vec!["grep"], vec!["docs"], 0.8);
- sibling.profile_id = Some("q".into());
- store.put(sibling).await.unwrap();
-
- // Unstamped legacy record.
- store
- .put(sample_experience(
- "exp_legacy",
- "task legacy",
- vec!["grep"],
- vec!["docs"],
- 0.8,
- ))
- .await
- .unwrap();
- }
-
- #[tokio::test]
- async fn retrieve_partitions_by_profile() {
- let (store, _) = fresh_store();
- seed_partitioned(&store).await;
-
- // Profile P: sees P + legacy, never Q.
- let hits = store
- .retrieve(ExperienceQuery {
- query: "task".into(),
- tools: vec!["grep".into()],
- tags: vec!["docs".into()],
- profile_id: Some("p".into()),
- max_hits: 10,
- ..Default::default()
- })
- .await
- .unwrap();
- let ids: BTreeSet<_> = hits.iter().map(|h| h.experience.id.clone()).collect();
- assert!(ids.contains("exp_p"), "profile P must see its own record");
- assert!(
- ids.contains("exp_legacy"),
- "profile P must see legacy records"
- );
- assert!(!ids.contains("exp_q"), "profile P must not see sibling Q");
-
- // Profile-less: sees everything.
- let all = store
- .retrieve(ExperienceQuery {
- query: "task".into(),
- tools: vec!["grep".into()],
- tags: vec!["docs".into()],
- profile_id: None,
- max_hits: 10,
- ..Default::default()
- })
- .await
- .unwrap();
- let all_ids: BTreeSet<_> = all.iter().map(|h| h.experience.id.clone()).collect();
- assert!(all_ids.contains("exp_p"));
- assert!(all_ids.contains("exp_q"));
- assert!(all_ids.contains("exp_legacy"));
- }
-
- #[tokio::test]
- async fn dismiss_for_profile_rejects_sibling_record() {
- let (store, _) = fresh_store();
- seed_partitioned(&store).await;
-
- assert!(!store.dismiss_for_profile("exp_q", Some("p")).await.unwrap());
- assert!(store
- .list()
- .await
- .unwrap()
- .iter()
- .find(|experience| experience.id == "exp_q")
- .is_some_and(|experience| !experience.dismissed));
-
- assert!(store
- .dismiss_for_profile("exp_legacy", Some("p"))
- .await
- .unwrap());
- assert!(store.dismiss_for_profile("exp_p", Some("p")).await.unwrap());
- }
-
- #[tokio::test]
- async fn list_for_profile_partitions() {
- let (store, _) = fresh_store();
- seed_partitioned(&store).await;
-
- let p_ids: BTreeSet<_> = store
- .list_for_profile(Some("p"))
- .await
- .unwrap()
- .into_iter()
- .map(|e| e.id)
- .collect();
- assert_eq!(
- p_ids,
- BTreeSet::from(["exp_legacy".to_string(), "exp_p".to_string()])
- );
-
- let all_ids: BTreeSet<_> = store
- .list_for_profile(None)
- .await
- .unwrap()
- .into_iter()
- .map(|e| e.id)
- .collect();
- assert_eq!(
- all_ids,
- BTreeSet::from([
- "exp_legacy".to_string(),
- "exp_p".to_string(),
- "exp_q".to_string()
- ])
- );
- }
-
- #[tokio::test]
- async fn retrieve_ignores_dismissed_records() {
- let (store, _) = fresh_store();
- store
- .put(sample_experience(
- "exp_dismissed",
- "search repository docs",
- vec!["grep", "file_read"],
- vec!["docs"],
- 0.8,
- ))
- .await
- .unwrap();
- store.dismiss("exp_dismissed").await.unwrap();
-
- let hits = store
- .retrieve(ExperienceQuery {
- query: "search repository docs".into(),
- tools: vec!["grep".into()],
- tags: vec!["docs".into()],
- agent_id: None,
- entrypoint: None,
- profile_id: None,
- max_hits: 5,
- })
- .await
- .unwrap();
-
- assert!(hits.is_empty());
- }
-}
+#[path = "store_tests.rs"]
+mod tests;
diff --git a/src/openhuman/agent/experience/store_tests.rs b/src/openhuman/agent/experience/store_tests.rs
new file mode 100644
index 0000000000..bfdb2aa7ec
--- /dev/null
+++ b/src/openhuman/agent/experience/store_tests.rs
@@ -0,0 +1,424 @@
+//! Unit tests for [`AgentExperienceStore`](super::AgentExperienceStore).
+//!
+//! A sibling `*_tests.rs` rather than an inline `#[cfg(test)] mod tests`, for
+//! two reasons that point the same way. It keeps `store.rs` near the ~500-line
+//! guideline, and it is the path both memory ratchets skip
+//! (`direct_engine_refs_tests::is_test_path`), which is what lets the two
+//! sanitizer regressions below keep constructing a real `UnifiedMemory`. That
+//! reference is legitimate: `tinymemory-core` is a dev-dependency after #5560,
+//! and a dev-dependency is not linked into the shipped binary — but in
+//! `store.rs` it read as an unmigrated production call site and cost an
+//! allowlist entry that documented the opposite of the truth.
+
+use super::*;
+use crate::openhuman::agent::experience::types::{
+ AgentExperience, ExperienceOutcome, ExperienceSource,
+};
+use crate::openhuman::memory::tool_memory::test_helpers::MockMemory;
+use std::sync::Arc;
+
+fn sample_experience(
+ id: &str,
+ task_summary: &str,
+ tools: Vec<&str>,
+ tags: Vec<&str>,
+ confidence: f32,
+) -> AgentExperience {
+ let sequence = tools.iter().map(|tool| (*tool).to_string()).collect();
+ AgentExperience {
+ id: id.to_string(),
+ created_at_ms: 1,
+ updated_at_ms: 1,
+ source: ExperienceSource::ToolLoop,
+ agent_id: Some("orchestrator".into()),
+ entrypoint: Some("chat".into()),
+ profile_id: None,
+ task_fingerprint: format!("fp-{id}"),
+ task_summary: task_summary.to_string(),
+ tools_used: tools.iter().map(|tool| (*tool).to_string()).collect(),
+ tool_sequence: sequence,
+ outcome: ExperienceOutcome::Success,
+ error_class: None,
+ lesson: format!("lesson for {task_summary}"),
+ reuse_hint: format!("reuse for {task_summary}"),
+ avoid_hint: None,
+ confidence,
+ tags: tags.iter().map(|tag| (*tag).to_string()).collect(),
+ payload_hash: None,
+ dismissed: false,
+ }
+}
+
+fn fresh_store() -> (AgentExperienceStore, Arc<MockMemory>) {
+ let memory = Arc::new(MockMemory::default());
+ (AgentExperienceStore::new(memory.clone()), memory)
+}
+
+#[tokio::test]
+async fn put_list_and_dismiss_round_trip() {
+ let (store, memory) = fresh_store();
+ store
+ .put(sample_experience(
+ "exp_success",
+ "search repository docs",
+ vec!["grep", "file_read"],
+ vec!["docs"],
+ 0.8,
+ ))
+ .await
+ .unwrap();
+
+ assert!(memory.entries.lock().contains_key(&(
+ AGENT_EXPERIENCE_NAMESPACE.into(),
+ "experience/exp_success".into()
+ )));
+
+ let listed = store.list().await.unwrap();
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].id, "exp_success");
+
+ let dismissed = store.dismiss("exp_success").await.unwrap();
+ assert!(dismissed);
+ let listed = store.list().await.unwrap();
+ assert_eq!(listed.len(), 1);
+ assert!(listed[0].dismissed);
+}
+
+/// Regression for #5209. `Memory::store` runs document content through the
+/// free-text secret/PII sanitizer, whose credit-card (Luhn-gated) pattern
+/// matches any 13–19-digit run. A serialized experience carries bare 13-digit
+/// millisecond timestamps, so a Luhn-valid timestamp used to be rewritten to
+/// a `[REDACTED_PII_*]` token — corrupting the JSON so the record silently
+/// vanished on read (~10% of writes, whichever `now_ms()` happened to be
+/// Luhn-valid). Exercised over the *real* `UnifiedMemory` because `MockMemory`
+/// does not sanitize. `1785148840502` is a Luhn-valid 13-digit ms timestamp;
+/// `put` preserves a positive `created_at_ms`, so the corruption is forced
+/// deterministically rather than depending on the wall clock.
+#[tokio::test]
+async fn experience_survives_content_sanitizer_with_luhn_valid_timestamp() {
+ use crate::openhuman::inference::embeddings::NoopEmbedding;
+ use crate::openhuman::memory::Memory;
+ use tinymemory_core::store::UnifiedMemory;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let memory: Arc<dyn Memory> =
+ Arc::new(UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).unwrap());
+ let store = AgentExperienceStore::new(memory);
+
+ let mut experience = sample_experience(
+ "exp_luhn",
+ "Deploy the Rust service safely",
+ vec![],
+ vec![],
+ 0.9,
+ );
+ // Luhn-valid 13-digit ms timestamp; preserved by `put` (positive value),
+ // so the vulnerable numeric field is present on every run.
+ experience.created_at_ms = 1_785_148_840_502;
+ experience.lesson = "Legacy shared deployment guidance".into();
+
+ store.put(experience).await.unwrap();
+
+ let listed = store.list().await.unwrap();
+ assert_eq!(
+ listed.len(),
+ 1,
+ "experience must survive the memory content sanitizer round-trip"
+ );
+ assert_eq!(listed[0].lesson, "Legacy shared deployment guidance");
+ assert_eq!(listed[0].created_at_ms, 1_785_148_840_502);
+}
+
+/// Security regression for PR #5211 review (P1). Base64-encoding the payload
+/// makes the memory layer's store-time content scrubber a no-op over the
+/// stored bytes, so the store must run the full scrubber over free-text
+/// fields itself before serialization ([`redact_experience`]). A secret in a
+/// captured free-text field must be redacted in the recalled record (so it
+/// is neither stored nor returned reversibly), while the numeric timestamp
+/// survives intact. Exercised over the real `UnifiedMemory` (the store path
+/// that base64 now shields).
+#[tokio::test]
+async fn secrets_in_free_text_are_redacted_before_storage() {
+ use crate::openhuman::inference::embeddings::NoopEmbedding;
+ use crate::openhuman::memory::Memory;
+ use tinymemory_core::store::UnifiedMemory;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let memory: Arc<dyn Memory> =
+ Arc::new(UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).unwrap());
+ let store = AgentExperienceStore::new(memory);
+
+ let mut experience = sample_experience("exp_secret", "deploy the service", vec![], vec![], 0.9);
+ // Luhn-valid 13-digit ms timestamp; must survive intact (the #5209 fix).
+ experience.created_at_ms = 1_785_148_840_502;
+ experience.lesson = "provider token sk_live_12345678901234567890 then dial +15551234567".into();
+ experience.reuse_hint =
+ "-----BEGIN PRIVATE KEY-----\nMIIabc123\n-----END PRIVATE KEY-----".into();
+ experience.error_class = Some("phone leaked: +15551234567".into());
+
+ store.put(experience).await.unwrap();
+
+ let listed = store.list().await.unwrap();
+ assert_eq!(listed.len(), 1, "record must still parse and round-trip");
+ let recalled = &listed[0];
+
+ // (a) secrets are redacted in the recalled free-text fields.
+ assert!(
+ !recalled.lesson.contains("sk_live_12345678901234567890"),
+ "Stripe key must be redacted, got: {}",
+ recalled.lesson
+ );
+ assert!(
+ !recalled.lesson.contains("+15551234567"),
+ "phone number must be redacted, got: {}",
+ recalled.lesson
+ );
+ assert!(
+ !recalled.reuse_hint.contains("PRIVATE KEY"),
+ "private-key block must be redacted, got: {}",
+ recalled.reuse_hint
+ );
+ assert!(
+ recalled
+ .error_class
+ .as_deref()
+ .is_none_or(|e| !e.contains("+15551234567")),
+ "phone in error_class must be redacted, got: {:?}",
+ recalled.error_class
+ );
+ assert!(
+ recalled.lesson.contains("REDACTED") && recalled.reuse_hint.contains("REDACTED"),
+ "expected redaction markers in scrubbed fields"
+ );
+
+ // (b) the numeric timestamp survives intact and the record parses.
+ assert_eq!(recalled.created_at_ms, 1_785_148_840_502);
+}
+
+#[tokio::test]
+async fn generated_ids_partition_identical_experiences_by_profile() {
+ let (store, _) = fresh_store();
+ let mut alice = sample_experience("", "same task", vec!["grep"], vec!["docs"], 0.8);
+ alice.profile_id = Some("alice".into());
+ let mut bob = alice.clone();
+ bob.profile_id = Some("bob".into());
+
+ let alice = store.put(alice).await.unwrap();
+ let bob = store.put(bob).await.unwrap();
+
+ assert_ne!(alice.id, bob.id);
+ let listed = store.list().await.unwrap();
+ assert_eq!(listed.len(), 2);
+ assert!(listed
+ .iter()
+ .any(|item| item.profile_id.as_deref() == Some("alice")));
+ assert!(listed
+ .iter()
+ .any(|item| item.profile_id.as_deref() == Some("bob")));
+}
+
+#[tokio::test]
+async fn retrieve_ranks_tool_and_query_matches() {
+ let (store, _) = fresh_store();
+ store
+ .put(sample_experience(
+ "exp_docs",
+ "search repository docs",
+ vec!["grep", "file_read"],
+ vec!["docs"],
+ 0.6,
+ ))
+ .await
+ .unwrap();
+ store
+ .put(sample_experience(
+ "exp_email",
+ "send a careful email",
+ vec!["email"],
+ vec!["mail"],
+ 1.0,
+ ))
+ .await
+ .unwrap();
+
+ let hits = store
+ .retrieve(ExperienceQuery {
+ query: "search docs with grep".into(),
+ tools: vec!["grep".into()],
+ tags: vec!["docs".into()],
+ agent_id: Some("orchestrator".into()),
+ entrypoint: Some("chat".into()),
+ profile_id: None,
+ max_hits: 2,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(hits.len(), 2);
+ assert_eq!(hits[0].experience.id, "exp_docs");
+ assert!(hits[0].score > hits[1].score);
+ assert!(hits[0].match_reasons.contains(&"tool_overlap".into()));
+ assert!(hits[0].match_reasons.contains(&"query_overlap".into()));
+}
+
+#[test]
+fn experience_matches_profile_partition_rules() {
+ // Profile-less query sees everything.
+ assert!(experience_matches_profile(None, None));
+ assert!(experience_matches_profile(Some("p"), None));
+ // Profiled query: own + legacy in, sibling out.
+ assert!(experience_matches_profile(Some("p"), Some("p")));
+ assert!(experience_matches_profile(None, Some("p")));
+ assert!(!experience_matches_profile(Some("q"), Some("p")));
+}
+
+async fn seed_partitioned(store: &AgentExperienceStore) {
+ let mut own = sample_experience("exp_p", "task p", vec!["grep"], vec!["docs"], 0.8);
+ own.profile_id = Some("p".into());
+ store.put(own).await.unwrap();
+
+ let mut sibling = sample_experience("exp_q", "task q", vec!["grep"], vec!["docs"], 0.8);
+ sibling.profile_id = Some("q".into());
+ store.put(sibling).await.unwrap();
+
+ // Unstamped legacy record.
+ store
+ .put(sample_experience(
+ "exp_legacy",
+ "task legacy",
+ vec!["grep"],
+ vec!["docs"],
+ 0.8,
+ ))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn retrieve_partitions_by_profile() {
+ let (store, _) = fresh_store();
+ seed_partitioned(&store).await;
+
+ // Profile P: sees P + legacy, never Q.
+ let hits = store
+ .retrieve(ExperienceQuery {
+ query: "task".into(),
+ tools: vec!["grep".into()],
+ tags: vec!["docs".into()],
+ profile_id: Some("p".into()),
+ max_hits: 10,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ let ids: BTreeSet<_> = hits.iter().map(|h| h.experience.id.clone()).collect();
+ assert!(ids.contains("exp_p"), "profile P must see its own record");
+ assert!(
+ ids.contains("exp_legacy"),
+ "profile P must see legacy records"
+ );
+ assert!(!ids.contains("exp_q"), "profile P must not see sibling Q");
+
+ // Profile-less: sees everything.
+ let all = store
+ .retrieve(ExperienceQuery {
+ query: "task".into(),
+ tools: vec!["grep".into()],
+ tags: vec!["docs".into()],
+ profile_id: None,
+ max_hits: 10,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ let all_ids: BTreeSet<_> = all.iter().map(|h| h.experience.id.clone()).collect();
+ assert!(all_ids.contains("exp_p"));
+ assert!(all_ids.contains("exp_q"));
+ assert!(all_ids.contains("exp_legacy"));
+}
+
+#[tokio::test]
+async fn dismiss_for_profile_rejects_sibling_record() {
+ let (store, _) = fresh_store();
+ seed_partitioned(&store).await;
+
+ assert!(!store.dismiss_for_profile("exp_q", Some("p")).await.unwrap());
+ assert!(store
+ .list()
+ .await
+ .unwrap()
+ .iter()
+ .find(|experience| experience.id == "exp_q")
+ .is_some_and(|experience| !experience.dismissed));
+
+ assert!(store
+ .dismiss_for_profile("exp_legacy", Some("p"))
+ .await
+ .unwrap());
+ assert!(store.dismiss_for_profile("exp_p", Some("p")).await.unwrap());
+}
+
+#[tokio::test]
+async fn list_for_profile_partitions() {
+ let (store, _) = fresh_store();
+ seed_partitioned(&store).await;
+
+ let p_ids: BTreeSet<_> = store
+ .list_for_profile(Some("p"))
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|e| e.id)
+ .collect();
+ assert_eq!(
+ p_ids,
+ BTreeSet::from(["exp_legacy".to_string(), "exp_p".to_string()])
+ );
+
+ let all_ids: BTreeSet<_> = store
+ .list_for_profile(None)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|e| e.id)
+ .collect();
+ assert_eq!(
+ all_ids,
+ BTreeSet::from([
+ "exp_legacy".to_string(),
+ "exp_p".to_string(),
+ "exp_q".to_string()
+ ])
+ );
+}
+
+#[tokio::test]
+async fn retrieve_ignores_dismissed_records() {
+ let (store, _) = fresh_store();
+ store
+ .put(sample_experience(
+ "exp_dismissed",
+ "search repository docs",
+ vec!["grep", "file_read"],
+ vec!["docs"],
+ 0.8,
+ ))
+ .await
+ .unwrap();
+ store.dismiss("exp_dismissed").await.unwrap();
+
+ let hits = store
+ .retrieve(ExperienceQuery {
+ query: "search repository docs".into(),
+ tools: vec!["grep".into()],
+ tags: vec!["docs".into()],
+ agent_id: None,
+ entrypoint: None,
+ profile_id: None,
+ max_hits: 5,
+ })
+ .await
+ .unwrap();
+
+ assert!(hits.is_empty());
+}
diff --git a/src/openhuman/agent/harness/archivist/hook_impl.rs b/src/openhuman/agent/harness/archivist/hook_impl.rs
index 4320dc78ea..5ea389143b 100644
--- a/src/openhuman/agent/harness/archivist/hook_impl.rs
+++ b/src/openhuman/agent/harness/archivist/hook_impl.rs
@@ -82,8 +82,23 @@ impl PostTurnHook for ArchivistHook {
// segment ops can store it alongside the FTS5 episodic id.
let mut current_seq: Option<u32> = None;
if let Some(cfg) = self.config.as_ref() {
- let engine_config =
- tinymemory_core::tinycortex::memory_config_from(cfg, cfg.workspace_dir.clone());
+ // The archivist store addresses `MemoryConfig::workspace` and
+ // nothing else: `tinycortex::memory::archivist::store` computes its
+ // own content root as `<workspace>/memory_tree/content` (a private
+ // `content_root(config)` in that module) and never reads
+ // `config.content_root` or `config.embedding`.
+ //
+ // This used to build the config through
+ // `tinymemory_core::tinycortex::memory_config_from`, which is the
+ // engine crate's `Config` → `MemoryConfig` mapping. That mapping
+ // sets two further fields — the content-root override and the
+ // embedding signature — and neither reaches `record_turn` or
+ // `session_entries`, so constructing the workspace-rooted config
+ // directly is the same value where it is read. Naming it here also
+ // drops the last `tinymemory_core::` reference in this file (#5560);
+ // `tinycortex` stays a direct dependency of this crate and is where
+ // the archivist store itself lives, two lines below.
+ let engine_config = tinycortex::memory::MemoryConfig::new(cfg.workspace_dir.clone());
let ts_ms = (timestamp * 1000.0) as i64;
let user_turn = tinycortex::memory::archivist::types::ArchivedTurn {
session_id: session_id.to_string(),
diff --git a/src/openhuman/agent/harness/archivist/lifecycle.rs b/src/openhuman/agent/harness/archivist/lifecycle.rs
index 80932423cb..2854c43e23 100644
--- a/src/openhuman/agent/harness/archivist/lifecycle.rs
+++ b/src/openhuman/agent/harness/archivist/lifecycle.rs
@@ -12,7 +12,15 @@ use crate::openhuman::memory::api::provider::{
use crate::openhuman::memory::tree::score::embed::{build_embedder_from_config, Embedder};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
-use tinymemory_core::chat::ChatProvider;
+
+/// The inference role the segment recap runs as.
+///
+/// Named here rather than inlined because it is the one string that has to
+/// match what the memory summariser asks for — `tinymemory_core::chat::
+/// build_chat_runtime` routes `"summarization"`, and the probe in
+/// [`ArchivistHook::with_config`] is only meaningful if it asks the same
+/// question of the same role.
+const RECAP_INFERENCE_ROLE: &str = "summarization";
impl ArchivistHook {
/// Create an Archivist hook over the workspace's bound memory driver.
@@ -25,36 +33,73 @@ impl ArchivistHook {
enabled,
boundary_config: BoundaryConfig::default(),
config: None,
+ summariser_available: false,
+ #[cfg(test)]
chat_provider: None,
embedder: None,
}
}
/// Attach runtime config so the archivist can gate the tree-ingest path
- /// and build its LLM chat provider + embedder from config.
+ /// and record whether an LLM summariser and an embedder are available.
///
/// When `config.learning.chat_to_tree_enabled` is `true`, each closed
/// segment's raw prose turns are ingested into the memory tree as
/// `source_id="conversations:agent"` (one batch per segment, not per turn).
- /// The chat provider is built via `build_chat_provider(config, Summarise)`;
- /// the embedder via `build_embedder_from_config(config)`. Both are
- /// soft-fallback: if construction fails, the fields stay `None` and the
- /// archivist falls back to heuristic summary / no embedding.
+ /// Both the summariser probe and the embedder are soft-fallback: if
+ /// construction fails, the archivist falls back to the heuristic summary /
+ /// no embedding rather than failing the turn.
+ ///
+ /// # Why the summariser is probed and not held
+ ///
+ /// This used to call `tinymemory_core::chat::build_chat_provider(&config)`
+ /// and store the `Arc<dyn ChatProvider>` it returned. Nothing ever called
+ /// that handle: the summariser the archivist drives is
+ /// `memory::tree::summarise::summarise`, which builds
+ /// its own provider from the same `Config` on every call. So the stored
+ /// value was only ever read as `is_some()`, and what it actually asserted
+ /// was "a chat model for the summarise role can be constructed".
+ ///
+ /// That question is the host's to answer, and this asks it directly.
+ /// `build_chat_provider` wraps `tinymemory_core::chat_host::
+ /// create_chat_model_with_model_id`, which is a process-global seam whose
+ /// only implementation is `OpenHumanChatHost` in `memory/host_impls.rs`,
+ /// and that forwards verbatim to the call below — same role, same config,
+ /// same temperature. The predicate is therefore unchanged; what changed is
+ /// that the archivist no longer names the memory engine to evaluate it
+ /// (#5560), and no longer builds a model it will not use.
+ ///
+ /// One deliberate difference, stated rather than hidden: under `cfg(test)`
+ /// the engine's builder short-circuits on its chat task-local, so a stubbed
+ /// test would have reported "available" without a real provider. No test
+ /// takes this path — every archivist test constructs the hook through
+ /// `new`, `disabled` or `new_with_stubs*` — and the tests that do need a
+ /// deterministic LLM install the task-local around the call itself, which
+ /// is where it has to be anyway for `summarise` to see it.
pub fn with_config(mut self, config: Config) -> Self {
- // Build the LLM chat provider for segment recap.
- let chat_provider: Option<Arc<dyn ChatProvider>> =
- match tinymemory_core::chat::build_chat_provider(&config) {
- Ok(p) => {
- tracing::debug!("[archivist] segment recap provider={} registered", p.name());
- Some(p)
- }
- Err(e) => {
- tracing::warn!(
- "[archivist] failed to build chat provider for recap (will use fallback): {e}"
- );
- None
- }
- };
+ // Probe the summariser: can this host build a chat model for the recap
+ // role right now? The model is dropped immediately — see above.
+ let probe = crate::openhuman::inference::provider::create_chat_model_with_model_id(
+ RECAP_INFERENCE_ROLE,
+ &config,
+ config.default_temperature,
+ );
+ let summariser_available = match probe {
+ Ok((_model, model_id)) => {
+ tracing::debug!(
+ "[archivist] segment recap summariser ready role={RECAP_INFERENCE_ROLE} \
+ model={model_id}"
+ );
+ true
+ }
+ Err(e) => {
+ tracing::warn!(
+ "[archivist] no chat model for role={RECAP_INFERENCE_ROLE} \
+ (segment recap falls back to the heuristic summary): {e}"
+ );
+ false
+ }
+ };
// Build the embedder for segment recap vectors.
let embedder: Option<Arc<dyn Embedder>> = match build_embedder_from_config(&config) {
@@ -70,7 +115,7 @@ impl ArchivistHook {
}
};
- self.chat_provider = chat_provider;
+ self.summariser_available = summariser_available;
self.embedder = embedder;
self.config = Some(config);
self
@@ -83,6 +128,8 @@ impl ArchivistHook {
enabled: false,
boundary_config: BoundaryConfig::default(),
config: None,
+ summariser_available: false,
+ #[cfg(test)]
chat_provider: None,
embedder: None,
}
diff --git a/src/openhuman/agent/harness/archivist/recap.rs b/src/openhuman/agent/harness/archivist/recap.rs
index 116b26b9fa..cce597804e 100644
--- a/src/openhuman/agent/harness/archivist/recap.rs
+++ b/src/openhuman/agent/harness/archivist/recap.rs
@@ -5,7 +5,11 @@ use crate::openhuman::memory::api::provider::{ConversationSegment, EpisodicTurn}
use crate::openhuman::memory::tree::summarise::{summarise, SummaryContext, SummaryInput};
#[cfg(test)]
use std::sync::Arc;
-use tinymemory_core::store::trees::types::TreeKind;
+// `SummaryContext::tree_kind` is TinyCortex's own enum, and
+// `tinymemory_core::store::trees::types::TreeKind` was a re-export of exactly
+// this item. Naming the owning crate changes no type — only which crate alias
+// holds it (#5560).
+use tinycortex::memory::tree::store::TreeKind;
/// An episodic entry paired with the stable identity exposed by its backing
/// store. The md archivist uses a per-session sequence while the legacy FTS5
@@ -65,8 +69,13 @@ impl ArchivistHook {
/// the sub-millisecond timestamps used when a segment is opened.
pub(super) async fn read_session_entries(&self, session_id: &str) -> Vec<SessionEntry> {
if let Some(cfg) = self.config.as_ref() {
- let engine_config =
- tinymemory_core::tinycortex::memory_config_from(cfg, cfg.workspace_dir.clone());
+ // Workspace-rooted and nothing else, for the same reason as the
+ // write side in `hook_impl.rs`: `session_entries` resolves its
+ // directory through the archivist store's own private
+ // `<workspace>/memory_tree/content` root and reads neither
+ // `content_root` nor `embedding`. See that call site for why this
+ // replaced `tinymemory_core::tinycortex::memory_config_from`.
+ let engine_config = tinycortex::memory::MemoryConfig::new(cfg.workspace_dir.clone());
match tinycortex::memory::archivist::store::session_entries(&engine_config, session_id)
{
Ok(turns) => {
@@ -119,9 +128,9 @@ impl ArchivistHook {
/// (`rolling_segment_recap`).
///
/// Builds a prose corpus from `entries`, calls the `LlmSummariser` when a
- /// `chat_provider` is configured, and falls back to the heuristic
- /// `segments::fallback_summary` on any failure or when no provider is
- /// wired in. Always returns a non-empty string.
+ /// summariser is available for this workspace, and falls back to the
+ /// heuristic `segments::fallback_summary` on any failure or when none is.
+ /// Always returns a non-empty string.
///
/// Invariants:
/// - NEVER mutates DB state (no `segment_set_summary`, no embedding).
@@ -189,12 +198,20 @@ impl ArchivistHook {
let first = entries.first().map(|e| e.content.as_str()).unwrap_or("");
let last = entries.last().map(|e| e.content.as_str()).unwrap_or(first);
- if self.chat_provider.is_some() {
+ // Was `self.chat_provider.is_some()`. Same predicate — the archivist
+ // never called that handle, it only asked whether one could be built —
+ // recorded as the boolean it always was. See `lifecycle::with_config`.
+ if self.summariser_available {
if let Some(ref config) = self.config {
tracing::debug!(
"[archivist] summarize_entries: LLM recap segment={segment_id} entries={}",
entries.len()
);
+ // Test-only: `summarise` builds its own chat provider, and
+ // `build_chat_runtime` consults this task-local before building
+ // one. Scoping the call is what keeps the recap tests off the
+ // network. Production has no such override and never names the
+ // engine's chat module (#5560).
#[cfg(test)]
let summary_result = if let Some(provider) = self.chat_provider.as_ref() {
tinymemory_core::chat::test_override::with_provider(
@@ -238,7 +255,7 @@ impl ArchivistHook {
}
} else {
tracing::debug!(
- "[archivist] summarize_entries: no chat provider — \
+ "[archivist] summarize_entries: no summariser available — \
heuristic fallback segment={segment_id}"
);
}
diff --git a/src/openhuman/agent/harness/archivist/test_constructors.rs b/src/openhuman/agent/harness/archivist/test_constructors.rs
index e3e9925a87..01141c0d91 100644
--- a/src/openhuman/agent/harness/archivist/test_constructors.rs
+++ b/src/openhuman/agent/harness/archivist/test_constructors.rs
@@ -1,5 +1,12 @@
//! Test-only constructors for `ArchivistHook` that inject stub providers
//! directly, bypassing `with_config`'s provider-build logic.
+//!
+//! This module is `#[cfg(test)]` at its declaration in `archivist/mod.rs`, so
+//! the engine-crate import below is not linked by a production build — the
+//! engine is a dev-dependency for exactly this kind of fixture (#5560). The
+//! `ChatProvider` it injects is an override for the memory summariser's own
+//! chat task-local, not a handle the archivist calls; see
+//! `types::ArchivistHook::chat_provider`.
use super::boundary::BoundaryConfig;
use super::types::ArchivistHook;
@@ -26,6 +33,9 @@ impl ArchivistHook {
enabled: true,
boundary_config: BoundaryConfig::default(),
config: Some(Config::default()),
+ // Injecting a stub is the assertion that the LLM path runs, so the
+ // availability flag `with_config` would have probed is set here.
+ summariser_available: true,
chat_provider: Some(chat_provider),
embedder: Some(embedder),
}
@@ -48,6 +58,7 @@ impl ArchivistHook {
enabled: true,
boundary_config: BoundaryConfig::default(),
config: Some(config),
+ summariser_available: true,
chat_provider: Some(chat_provider),
embedder: Some(embedder),
}
diff --git a/src/openhuman/agent/harness/archivist/tree_ingest.rs b/src/openhuman/agent/harness/archivist/tree_ingest.rs
index dc9a372e8b..162fb62340 100644
--- a/src/openhuman/agent/harness/archivist/tree_ingest.rs
+++ b/src/openhuman/agent/harness/archivist/tree_ingest.rs
@@ -142,6 +142,15 @@ impl ArchivistHook {
// here any more — the driver owns chunking and extraction.
let _ = config;
+ // Test-only. The ingest above is a contract call, but the driver behind
+ // it runs an extraction LLM of its own, built from `Config` rather than
+ // handed in — so a test that did not scope this task-local would reach
+ // the managed backend over the network, and the ingest swallows its own
+ // failures (below), which surfaces as zero tree chunks rather than as a
+ // network error. `tinymemory_core::chat::build_chat_runtime` consults
+ // the override before building anything, which is what makes these
+ // deterministic. Production has no override and never names the engine's
+ // chat module (#5560); the engine is a dev-dependency for this fixture.
#[cfg(test)]
let ingest_result = if let Some(provider) = self.chat_provider.as_ref() {
tinymemory_core::chat::test_override::with_provider(
diff --git a/src/openhuman/agent/harness/archivist/types.rs b/src/openhuman/agent/harness/archivist/types.rs
index f62b8faaac..0a695b0956 100644
--- a/src/openhuman/agent/harness/archivist/types.rs
+++ b/src/openhuman/agent/harness/archivist/types.rs
@@ -5,6 +5,9 @@ use crate::openhuman::config::Config;
use crate::openhuman::memory::api::provider::MemoryProvider;
use crate::openhuman::memory::tree::score::embed::Embedder;
use std::sync::Arc;
+// Test-only. See [`ArchivistHook::chat_provider`] for why the engine's chat
+// trait is still named here and why it is not named in a production build.
+#[cfg(test)]
use tinymemory_core::chat::ChatProvider;
/// Post-turn hook that indexes conversation turns and manages segments.
@@ -27,8 +30,38 @@ pub struct ArchivistHook {
/// When `None`, the tree-ingest path is skipped. Set via
/// [`ArchivistHook::with_config`] on the production path.
pub(super) config: Option<Config>,
- /// Optional LLM provider for segment recap. When `None`, the
- /// fallback heuristic summary is used instead.
+ /// Whether an LLM summariser can be built for this workspace. `false`
+ /// means the heuristic bookend summary is used instead.
+ ///
+ /// This was `chat_provider.is_some()` — the archivist built a chat provider
+ /// in [`ArchivistHook::with_config`], stored it, and then never called it.
+ /// It could not: the summariser it drives is
+ /// `memory::tree::summarise::summarise`, which builds
+ /// its **own** provider from the same `Config`. The stored handle was a
+ /// probe result wearing the shape of a dependency, so it is recorded as
+ /// what it always was — a yes/no — and the probe now runs against the
+ /// host's own inference factory rather than the memory engine's wrapper
+ /// around it (#5560). See `with_config` for why those two answer alike.
+ pub(super) summariser_available: bool,
+ /// Test-only deterministic chat provider, installed into the engine's chat
+ /// task-local for the duration of a summarise or ingest call.
+ ///
+ /// **This is an override, not a dependency**, which is why it is
+ /// `#[cfg(test)]` and why nothing in a production build names
+ /// `tinymemory_core::chat`. `summarise` and the driver's `ingest_chat` both
+ /// construct their own provider; `tinymemory_core::chat::build_chat_runtime`
+ /// consults a task-local before building one, and scoping a call through it
+ /// is the only way to keep these tests off the network.
+ ///
+ /// It cannot be re-pointed at the host's own chat seam
+ /// (`modules::memory_host`'s `ChatHost` bus interface): that seam is served
+ /// to a **loaded module**, and a module cannot be loaded by these tests at
+ /// all — `dlopen` is a process singleton, so a second module-loading test in
+ /// one process hangs rather than fails. The driver under test is the
+ /// in-process `TinycortexProvider`, which reaches its LLM through
+ /// `tinymemory-core`, so the engine's task-local is the seam that exists.
+ /// The engine stays a dev-dependency for exactly this kind of fixture.
+ #[cfg(test)]
pub(super) chat_provider: Option<Arc<dyn ChatProvider>>,
/// Optional embedder for segment recap vectors. When `None`, embedding
/// is skipped (segment is still summarised).
diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs
index 0fd7d607f9..484005ff87 100644
--- a/src/openhuman/agent/harness/session/builder/factory.rs
+++ b/src/openhuman/agent/harness/session/builder/factory.rs
@@ -256,16 +256,23 @@ impl Agent {
.map_err(|e| anyhow::anyhow!("archivist memory binding: {e}"))?;
let memory: Arc<dyn Memory> = Arc::from(session_memory.memory);
// Dedicated profiles still recall unstamped experiences written by
- // pre-profile versions from the shared memory DB. Retain the global
- // shared handle explicitly on the session rather than making the hot
- // turn path reload config or reach into process-global state.
+ // pre-profile versions from the shared memory DB. Resolve that shared
+ // store once, here, and hand it to the session rather than making the
+ // hot turn path reload config.
+ //
+ // This was `global::init(workspace).memory_handle()` — booting the
+ // second, in-process engine purely to borrow its `Arc<dyn Memory>`
+ // (#5560). `DriverMemory` serves the same trait off the driver already
+ // bound for this workspace's shared `memory` subtree, so the recall
+ // reads the same rows without a second engine over the same file. Only
+ // recall goes here; writes stay on the session's own store, which is
+ // what keeps new records inside the profile subtree.
let shared_experience_memory = if memory_subdir == "memory" {
None
} else {
Some(
- tinymemory_core::global::init(config.workspace_dir.clone())
- .map_err(anyhow::Error::msg)?
- .memory_handle(),
+ crate::openhuman::agent::experience::ops::DriverMemory::for_config(config)
+ .map_err(anyhow::Error::msg)?,
)
};
diff --git a/src/openhuman/agent/harness/subagent_runner/ops/runner.rs b/src/openhuman/agent/harness/subagent_runner/ops/runner.rs
index a727149f34..92a0280fa9 100644
--- a/src/openhuman/agent/harness/subagent_runner/ops/runner.rs
+++ b/src/openhuman/agent/harness/subagent_runner/ops/runner.rs
@@ -1624,7 +1624,14 @@ mod fast_path_tests {
};
use crate::openhuman::memory::tree::retrieval::types::{NodeKind, QueryResponse, RetrievalHit};
use chrono::Utc;
- use tinymemory_core::store::trees::types::TreeKind;
+ // `RetrievalHit::tree_kind` is TinyCortex's own enum. `tinymemory_core::
+ // store::trees::types::TreeKind` was a re-export of exactly this item
+ // (`tinymemory_core::store::trees::types` → `engine::backend::tree::store`
+ // → `tinycortex::memory::tree::store`), so naming the owning crate here
+ // changes no type — only which crate alias holds it, which is what #5560
+ // is removing from the production graph. Same precedent as
+ // `memory/tools/flavour.rs`, which already imports it from this path.
+ use tinycortex::memory::tree::store::TreeKind;
fn hit(content: &str, scope: &str, score: f32) -> RetrievalHit {
RetrievalHit {
diff --git a/src/openhuman/agent/tinyagents/thread_context.rs b/src/openhuman/agent/tinyagents/thread_context.rs
index 748b06377e..398ff08993 100644
--- a/src/openhuman/agent/tinyagents/thread_context.rs
+++ b/src/openhuman/agent/tinyagents/thread_context.rs
@@ -10,5 +10,26 @@
//! runtime; `tokio::task_local!` needs one. Every existing
//! `agent::tinyagents::thread_context::…` path keeps resolving and keeps
//! naming the same task-local.
+//!
+//! # Bringing the definition home is a Phase F move, not a free one (#5560)
+//!
+//! This looks like a shim that could be replaced by a host-side
+//! `tokio::task_local!` in one commit. It cannot, while the in-process engine
+//! is still linked, and the failure would be silent.
+//!
+//! The engine reads this task-local in exactly one production place:
+//! `tinymemory_core::store::recall_policy::current_self_echo_exclusion`, which
+//! is how an in-process recall stops returning the very thread it was called
+//! from. Two `task_local!` invocations are two distinct keys, so moving the
+//! definition here would leave the engine's key permanently unset — and unset
+//! means *exclude nothing*, a permission-shaped check that fails open. Recall
+//! would start echoing the caller's own thread back at it, with no error
+//! anywhere.
+//!
+//! That read is already dead in module mode, for the reason `AGENTS.md` states:
+//! a task-local set in this process is invisible inside a separately compiled
+//! `cdylib`, so callers must pass `RecallOpts::exclude_session_id` explicitly
+//! and the host's own call sites do. So the definition comes home **with** the
+//! engine's removal, in the same commit — not before it.
pub use tinymemory_core::thread_context::{current_thread_id, with_thread_id};
diff --git a/src/openhuman/flows/memory_tools.rs b/src/openhuman/flows/memory_tools.rs
index a536c8331f..3fc027f253 100644
--- a/src/openhuman/flows/memory_tools.rs
+++ b/src/openhuman/flows/memory_tools.rs
@@ -560,6 +560,38 @@ mod tests {
MemoryCategory as EngineCategory, MemoryTaint as EngineTaint,
};
+ // ── Why `UnifiedMemory` is still here, and what replacing it costs (#5560)
+ //
+ // This whole module is `#[cfg(test)]`, so the engine is not linked into a
+ // production build from this file; the crate survives #5560 as a
+ // dev-dependency and this is the kind of fixture that keeps it. What the
+ // fixture cannot do is move to the bound driver in a one-line swap, and
+ // there are two independent reasons worth recording before someone tries.
+ //
+ // 1. **The seam is a different trait.** `test_mem` hands back
+ // `Arc<dyn memory::Memory>` (= `tinymemory_api::traits::Memory`), and
+ // `Arc<dyn MemoryProvider>` does not coerce to it: `MemoryProvider`'s
+ // supertrait is `MemoryCore`, which is a *different* trait with taint as
+ // an argument rather than a second method (see `provider/mandatory.rs`,
+ // which says so at the definition). Rebinding the fixture onto
+ // `memory::test_support::install_tinycortex_for_test` therefore rewrites
+ // every `mem.store_with_taint(..)` / `mem.get(..)` in this module, not
+ // just its two lines.
+ // 2. **The backend choice is load-bearing.** `FLOW_MEMORY_NAMESPACE_PREFIX`'s
+ // doc above turns on `UnifiedMemory::sanitize_namespace` disagreeing with
+ // `Memory::forget`'s raw `WHERE namespace = ?1`. A volatile stand-in such
+ // as `tinycortex::memory::store::InMemoryMemoryStore` implements the same
+ // `Memory` trait and would compile, but it does not reproduce that
+ // inconsistency — so it would quietly stop testing the property the
+ // prefix exists to satisfy.
+ //
+ // Every test below that touches `test_mem` is already `#[ignore]`d, and
+ // their ignore reason is the deeper problem: the tools resolve the *bound
+ // driver*, so a store seeded here is not the store they read. Making them
+ // coherent again is a fixture rewrite against the binding — a change worth
+ // making on its own, with the tests un-ignored so the result is verified,
+ // not folded into a dependency-shedding pass.
+
fn test_security() -> Arc<SecurityPolicy> {
Arc::new(SecurityPolicy::default())
}
diff --git a/src/openhuman/memory/ops/helpers.rs b/src/openhuman/memory/ops/helpers.rs
index 6c35d6e84e..589259fff9 100644
--- a/src/openhuman/memory/ops/helpers.rs
+++ b/src/openhuman/memory/ops/helpers.rs
@@ -1,5 +1,9 @@
-//! Formatting helpers, default constants, path validators, and the active
-//! memory-client lookup. Shared internals for the memory RPC handlers.
+//! Formatting helpers, default constants, path validators, and the shared
+//! workspace lookup. Shared internals for the memory RPC handlers.
+//!
+//! This module used to own `active_memory_client`, the unguarded lookup of the
+//! in-process engine's process-global handle. That handle is gone (#5560) — see
+//! the note where the function stood, further down.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
@@ -13,15 +17,14 @@ use crate::openhuman::memory::{
MemoryDocumentSummary, MemoryRetrievalChunk, MemoryRetrievalContext, MemoryRetrievalEntity,
MemoryRetrievalRelation, QueryNamespaceRequest,
};
-// Contract vocabulary named at the contract, engine handle named at the
-// engine: the three value types resolve to the same items either way
-// (tinycortex-api re-exports tinymemory-api), but a `tinymemory_core::` path
-// is a compile-time link this host is shedding (#5560), so only the handle —
-// which has no contract twin yet — still names the crate.
+// Contract vocabulary, named at the contract. Every value type here resolves
+// to the same item either way (tinycortex-api re-exports tinymemory-api), but a
+// `tinymemory_core::` path is a compile-time link this host has shed (#5560),
+// and this module no longer holds an engine handle at all — see the note where
+// `active_memory_client` used to be.
use crate::openhuman::memory::api::types::{
GraphRelationRecord, MemoryItemKind, NamespaceMemoryHit,
};
-use tinymemory_core::store::MemoryClientRef;
// ---------------------------------------------------------------------------
// Formatting helpers
@@ -378,22 +381,22 @@ pub(crate) async fn current_workspace_dir() -> Result<PathBuf, String> {
.map_err(|e| format!("load config: {e}"))
}
-/// Returns the active memory client from the process-global singleton,
-/// auto-initialising from the configured workspace if startup wiring hasn't
-/// done so yet.
-///
-/// The auto-init resolves the workspace via [`current_workspace_dir`], which
-/// goes through `Config::load_or_init` — the same path startup wiring uses.
-/// It does **not** fall back to `~/.openhuman/workspace`; that hazard is the
-/// one [`tinymemory_core::global::client`] guards against, and it
-/// remains guarded for any caller that bypasses this helper.
-pub(crate) async fn active_memory_client() -> Result<MemoryClientRef, String> {
- if let Some(client) = tinymemory_core::global::client_if_ready() {
- return Ok(client);
- }
- let workspace_dir = current_workspace_dir().await?;
- tinymemory_core::global::init(workspace_dir)
-}
+// ── `active_memory_client` is gone (#5560) ──────────────────────────────────
+//
+// It resolved the in-process engine's process-global `MemoryClient`, booting it
+// from the configured workspace when startup wiring had not. Every caller has
+// been routed onto the bound driver instead, and this host no longer boots a
+// second engine for one to be resolved from, so the function was left with no
+// callers at all — a helper whose whole body was `global::client_if_ready()`
+// then `global::init(…)`.
+//
+// The replacement is not a narrower helper here: it is
+// `super::guard::active_memory_guard` for a handler with a typed contract twin,
+// and `memory::binding::for_config(&config)` for one that needs the binding
+// itself (driver id, capabilities, a specific family). Both key on the
+// workspace dir and the `[subsystems.memory]` block, which is why the login /
+// logout / revalidation sites need no explicit re-point the way `global::init`
+// did.
// ---------------------------------------------------------------------------
// Path validators (used by file-based memory handlers)
diff --git a/src/openhuman/memory/ops/sync.rs b/src/openhuman/memory/ops/sync.rs
index 627f2d0286..44a3e901e5 100644
--- a/src/openhuman/memory/ops/sync.rs
+++ b/src/openhuman/memory/ops/sync.rs
@@ -3,12 +3,7 @@
//! 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.
+//! # One engine call is left here, and it is an openhuman#5560 blocker
//!
//! - **`spawn_manual_sync` → `tinycortex::run_composio_connection`.** The
//! engine's own `run_composio_connection_with_caps` opens with
@@ -20,26 +15,28 @@
//! 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.
+//! they move together or not at all, and the ordering that imposes lives next
+//! to the loop it protects in
+//! [`memory::sync::composio`](crate::openhuman::memory::sync::composio).
+//!
+//! # `memory_ingestion_status` was the quiet one, and it is fixed
+//!
+//! It used to read the in-process engine's live `IngestionState` through
+//! `global::client_if_ready()`, whose `None` arm answered "idle, queue empty" —
+//! indistinguishable from a healthy store with nothing to do. Once the second
+//! engine stopped booting, that arm became the *only* arm: the RPC reported
+//! permanent idle regardless of reality, and the Memory panel's ingestion
+//! indicator never lit up again. The frontend polls this every 1.5–4s
+//! (`useMemoryIngestionStatus`, `useBackgroundActivity`), so the wrong answer
+//! was on screen continuously.
//!
-//! 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.
+//! It now reads `MemoryMaintenance::queue_stats` off the bound driver, which is
+//! the contract's own queue telemetry and needs no new bus member. See
+//! `ingestion_status_for_config` for exactly which fields survived that move
+//! and which the contract does not carry.
use crate::openhuman::config::rpc as config_rpc;
+use crate::openhuman::config::Config;
use crate::openhuman::memory::sync::composio;
use crate::rpc::RpcOutcome;
use tinymemory_api::sync_events::{emit_sync_stage, MemorySyncStage, MemorySyncTrigger};
@@ -63,10 +60,19 @@ pub struct SyncAllResult {
pub requested: bool,
}
-/// Result returned by `memory_ingestion_status`. Mirrors
-/// [`crate::openhuman::memory::IngestionStatusSnapshot`] but is the public RPC
-/// shape — the indirection keeps internal renames from breaking the wire
-/// contract.
+/// Result returned by `memory_ingestion_status` — the public RPC shape, kept
+/// deliberately separate from whatever the driver answers so an internal rename
+/// cannot break the wire contract.
+///
+/// **Five fields are permanently `None` since the move onto the contract**
+/// (`current_document_id`, `current_title`, `current_namespace`,
+/// `last_document_id`, `last_success`) — see `ingestion_status_for_config`,
+/// which documents the reduction field by field. They stay on the struct because
+/// `MemoryControls`, `OverviewPanel` and `useBackgroundActivity` decode this
+/// shape and every one of them is `skip_serializing_if = "Option::is_none"`
+/// already, so an absent field is a shape the frontend has always handled.
+/// Removing them would be a wire change; leaving them is not a promise that
+/// they are filled.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct IngestionStatusResult {
pub running: bool,
@@ -241,28 +247,94 @@ async fn spawn_manual_sync(requested_connection: Option<String>) -> Result<(), S
Ok(())
}
-/// Returns the current memory-ingestion status: whether a job is running, the
-/// in-flight document, queue depth, and the most recent completion. Read-only,
+/// Returns the current memory-ingestion status: whether the driver's queue is
+/// working, how much is waiting, and when it last settled a job. Read-only,
/// safe to poll.
pub async fn memory_ingestion_status() -> Result<RpcOutcome<IngestionStatusResult>, String> {
- let snapshot = match tinymemory_core::global::client_if_ready() {
- Some(c) => c.ingestion_state().snapshot(),
- // Memory not yet initialised — report idle, no in-flight job.
- None => Default::default(),
+ let config = config_rpc::load_config_with_timeout().await?;
+ let status = ingestion_status_for_config(&config).await?;
+ Ok(RpcOutcome::new(status, vec![]))
+}
+
+/// The queue half of [`memory_ingestion_status`], against an explicit config.
+///
+/// Split out so the mapping below is testable against a bound driver without
+/// the handler's ambient `Config::load_or_init` — the same shape
+/// `read_rpc::chunks` uses for its own paged reads.
+///
+/// # What moved, and what the contract does not carry
+///
+/// This was `global::client_if_ready().ingestion_state().snapshot()` — an
+/// in-process counter owned by the engine this host no longer boots. The
+/// replacement is
+/// [`MemoryMaintenance::queue_stats`](crate::openhuman::memory::api::provider::MemoryMaintenance::queue_stats),
+/// the contract's own queue
+/// telemetry, so it works against *whichever* driver is bound rather than only
+/// against an engine living in this address space.
+///
+/// | RPC field | Source | Note |
+/// | --- | --- | --- |
+/// | `running` | `QueueStats::running > 0` | jobs a worker currently holds |
+/// | `queue_depth` | `QueueStats::ready` | jobs waiting; the running one is counted by `running`, exactly as the engine counter split them |
+/// | `last_completed_at` | `QueueStats::last_completed_ms` | when the queue last settled a job |
+///
+/// **The reduction, stated rather than hidden.** `current_document_id`,
+/// `current_title`, `current_namespace`, `last_document_id` and `last_success`
+/// have no contract equivalent and are left `None`. `QueueStats` is counts, not
+/// job identity: it can say a worker is busy, not *what* it is busy with. That
+/// is a narrower answer than the engine's snapshot gave — and a strictly better
+/// one than what shipped, because since the second engine stopped booting those
+/// fields were `None` **and** `running`/`queue_depth` were falsely zero. Nothing
+/// is substituted for them: `latest_queue_failure()` could be squinted at to
+/// synthesise a `last_success`, and it would be a different question's answer
+/// (the newest *terminal failure*, not the newest job's outcome).
+///
+/// Widening this back out is a contract member and a `tinymemory` release, not
+/// a host change.
+///
+/// # Degrade
+///
+/// A driver error propagates — reporting "idle" because the driver failed is
+/// the exact bug this replaced. A driver that does not serve `Maintenance` at
+/// all reports zeros with the driver named in the log, matching its siblings in
+/// `memory::tree::tree::rpc`: it has no queue to be behind on.
+async fn ingestion_status_for_config(config: &Config) -> Result<IngestionStatusResult, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(maintenance) = binding.provider().as_maintenance() else {
+ log::debug!(
+ "[memory.sync] ingestion_status: driver '{}' does not serve Maintenance; reporting idle",
+ binding.driver_id()
+ );
+ return Ok(IngestionStatusResult::default());
};
- Ok(RpcOutcome::new(
- IngestionStatusResult {
- running: snapshot.running,
- current_document_id: snapshot.current_document_id,
- current_title: snapshot.current_title,
- current_namespace: snapshot.current_namespace,
- queue_depth: snapshot.queue_depth,
- last_completed_at: snapshot.last_completed_at,
- last_document_id: snapshot.last_document_id,
- last_success: snapshot.last_success,
- },
- vec![],
- ))
+
+ // `None` counts every job kind. The engine counter this replaces was not
+ // narrowed to the ingest kind either — it was bumped on every submit — so
+ // narrowing here would silently shrink a number the Memory panel already
+ // displays.
+ let queue = maintenance
+ .queue_stats(None)
+ .await
+ .map_err(|e| format!("queue_stats: {e}"))?;
+
+ log::debug!(
+ "[memory.sync] ingestion_status: driver='{}' running={} ready={} eligible_now={}",
+ binding.driver_id(),
+ queue.running,
+ queue.ready,
+ queue.eligible_now
+ );
+
+ Ok(IngestionStatusResult {
+ running: queue.running > 0,
+ current_document_id: None,
+ current_title: None,
+ current_namespace: None,
+ queue_depth: usize::try_from(queue.ready).unwrap_or(usize::MAX),
+ last_completed_at: queue.last_completed_ms,
+ last_document_id: None,
+ last_success: None,
+ })
}
#[cfg(test)]
@@ -284,9 +356,27 @@ mod tests {
LOCK.get_or_init(|| std::sync::Mutex::new(()))
}
- fn ensure_memory_client() -> tinymemory_core::store::MemoryClientRef {
- crate::openhuman::memory::ops::ensure_shared_memory_client();
- tinymemory_core::global::client().expect("memory client")
+ /// A config on its own temp workspace with a driver bound that reports
+ /// `queue` verbatim.
+ ///
+ /// The ingestion-status handler reads through the contract now, and the
+ /// real driver is a compiled module a unit test cannot load — so without a
+ /// binding installed the workspace resolves to the null driver and every
+ /// count answers zero, which is exactly the failure mode this handler was
+ /// fixed for. See `binding::FixedDiagnostics`.
+ fn bind_queue(
+ queue: crate::openhuman::memory::api::provider::types::QueueStats,
+ ) -> (tempfile::TempDir, Config) {
+ let tmp = tempfile::TempDir::new().expect("tempdir");
+ let mut config = Config::default();
+ config.workspace_dir = tmp.path().to_path_buf();
+ crate::openhuman::memory::binding::install_diagnostics_for_test(
+ &config.workspace_dir,
+ &config.subsystems.memory,
+ Default::default(),
+ queue,
+ );
+ (tmp, config)
}
struct ChannelCapture {
@@ -399,35 +489,55 @@ mod tests {
);
}
+ /// The mapping from the driver's `QueueStats` onto the RPC shape, including
+ /// the fields the contract does not carry.
+ ///
+ /// This replaces a test that drove the in-process engine's `IngestionState`
+ /// counters directly. That test passed while the production RPC was
+ /// answering permanent idle, because it initialised the very engine
+ /// singleton production had stopped booting — the assertion held against a
+ /// path nothing reached.
#[tokio::test]
- async fn memory_ingestion_status_reflects_initialized_client_snapshot() {
- let _serial = crate::openhuman::memory::ops::GLOBAL_MEMORY_TEST_LOCK
- .lock()
- .await;
- let _guard = test_mutex()
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let client = ensure_memory_client();
- let state = client.ingestion_state();
+ async fn ingestion_status_reports_the_bound_drivers_queue() {
+ let (_tmp, config) =
+ bind_queue(crate::openhuman::memory::api::provider::types::QueueStats {
+ ready: 3,
+ running: 1,
+ last_completed_ms: Some(1_700_000_000_000),
+ ..Default::default()
+ });
+
+ let status = ingestion_status_for_config(&config)
+ .await
+ .expect("ingestion status");
+
+ assert!(status.running, "a held job means the queue is working");
+ assert_eq!(status.queue_depth, 3, "queue_depth is the ready count");
+ assert_eq!(status.last_completed_at, Some(1_700_000_000_000));
- // Reset any residue from background ingestion left by prior tests.
- state.reset_for_test();
+ // The reduction, asserted rather than assumed: `QueueStats` is counts,
+ // not job identity, so nothing fills these and nothing is invented for
+ // them. If a future contract member does carry the in-flight document,
+ // this is the test that should stop compiling as written.
+ assert!(status.current_document_id.is_none());
+ assert!(status.current_title.is_none());
+ assert!(status.current_namespace.is_none());
+ assert!(status.last_document_id.is_none());
+ assert!(status.last_success.is_none());
+ }
- state.enqueue();
- state.mark_running("doc-sync", "Sync Title", "sync-test");
+ /// An idle queue reports idle — the answer the broken handler used to give
+ /// unconditionally, now given only when the driver actually says so.
+ #[tokio::test]
+ async fn ingestion_status_reports_idle_for_an_empty_queue() {
+ let (_tmp, config) = bind_queue(Default::default());
- let status = memory_ingestion_status()
+ let status = ingestion_status_for_config(&config)
.await
- .expect("memory_ingestion_status")
- .value;
-
- assert!(status.running);
- assert_eq!(status.current_document_id.as_deref(), Some("doc-sync"));
- assert_eq!(status.current_title.as_deref(), Some("Sync Title"));
- assert_eq!(status.current_namespace.as_deref(), Some("sync-test"));
- assert_eq!(status.queue_depth, 1);
+ .expect("ingestion status");
- state.dequeue();
- state.mark_completed("doc-sync", true, 12345);
+ assert!(!status.running);
+ assert_eq!(status.queue_depth, 0);
+ assert!(status.last_completed_at.is_none());
}
}
diff --git a/src/openhuman/memory/ops/test_support.rs b/src/openhuman/memory/ops/test_support/mod.rs
similarity index 68%
rename from src/openhuman/memory/ops/test_support.rs
rename to src/openhuman/memory/ops/test_support/mod.rs
index 8f4fbe7f22..bd06e736fa 100644
--- a/src/openhuman/memory/ops/test_support.rs
+++ b/src/openhuman/memory/ops/test_support/mod.rs
@@ -1,11 +1,28 @@
//! Shared test infrastructure for `memory::ops` submodule tests.
//!
-//! All `ops` submodules that need a global [`MemoryClient`] call
+//! All `ops` submodules that need a global `MemoryClient` call
//! [`ensure_shared_memory_client`] instead of creating their own
//! `OnceLock<PathBuf>`. Sharing one leaked workspace means concurrent
//! `global::init()` calls always resolve to the same path and hit the
//! no-op fast-path inside `init_in_slot`, preventing one test thread
//! from silently rebinding the global under another thread's feet.
+//!
+//! # This is the one engine reference in `memory::ops` that is meant to stay
+//!
+//! Everything else under `ops/` was routed onto the contract for openhuman#5560
+//! so `tinymemory-core` can leave `[dependencies]` and survive as a
+//! **dev-dependency only**. This fixture deliberately still boots the
+//! in-process engine, because that is what it is for: it hands the `ops` tests a
+//! real store to write rows into and read back, and a dev-dependency reference
+//! from `#[cfg(test)]` code is not linked into the shipped binary.
+//!
+//! It lives in a `test_support/` **directory** rather than as a
+//! `test_support.rs` file for one reason: both memory ratchets skip by path, and
+//! `is_test_path` matches a *path component* named `test_support`, not a file
+//! stem. As a flat file this module had to carry an entry in
+//! `direct_engine_refs_tests::ALLOWED` that read like an unmigrated production
+//! call site. The same reasoning already put `memory::test_support` in a
+//! directory — see its module docs.
use std::path::PathBuf;
use std::sync::OnceLock;
diff --git a/src/openhuman/memory/sources/mod.rs b/src/openhuman/memory/sources/mod.rs
index cfdcf2f679..af0e79956c 100644
--- a/src/openhuman/memory/sources/mod.rs
+++ b/src/openhuman/memory/sources/mod.rs
@@ -9,30 +9,44 @@
//!
//! 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 —
+//! `[[memory_sources]]`, and `tinymemory_core::sources` is mostly a wrapper —
//! `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:
+//! `tinymemory_sources::registry::SourceRegistry` with the host's config path
+//! and a write lock, and five of the seven readers (`folder`, `conversation`,
+//! `rss`, `web_page`, `github`) delegate to `tinymemory_sources::readers`.
+//! Three things stand between this file and that move, and all three are
+//! outside it:
//!
//! 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.
+//! not list. It is *reachable* without a new dependency: the `tinymemory`
+//! crate this manifest already takes re-exports it as `tinymemory::sources`
+//! behind an off-by-default `sources` feature (the network readers need
+//! `sources-network` on top). So the unlock is a feature line rather than a
+//! new entry — but it is still a `Cargo.toml` decision, not a code one.
+//! 2. **Two of the seven readers have no upstream twin.** `composio` and
+//! `twitter` are implemented in `tinymemory-core` itself. Neither reaches
+//! engine internals — both name only `sources::types`, the host `Config`
+//! and the local `SourceReader` trait — so they are portable, but they are
+//! code to move rather than a re-export to repoint.
+//! 3. **`sources::sync` and `sources::status` are wired into the pieces #5560
+//! has not moved yet.** `sync` reaches `engine::run_source_pipeline`,
+//! `engine::{needs_rebuild, rebuild_tree_from_raw}`,
+//! `queue::store::retry_all_failed`, `sync::composio` and `sync::audit`;
+//! `status` reaches `store::chunks::store::with_connection` — the ingest
+//! pipeline, the re-embed queue and the raw SQLite chunk door. (That last
+//! one is `status`', not `sync`'s; an earlier revision of this note
+//! attributed it to `sync`.) 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.
+//! CRUD member for a configured connector. And it is the *whole* of
+//! `Capability::Sources`: there is no `MemorySources` family in the contract,
+//! so a listing member is an upstream ask, not a call site nobody routed.
pub use tinymemory_core::sources::*;
diff --git a/src/openhuman/memory/sources/rpc.rs b/src/openhuman/memory/sources/rpc.rs
index d377159267..91b4433703 100644
--- a/src/openhuman/memory/sources/rpc.rs
+++ b/src/openhuman/memory/sources/rpc.rs
@@ -1,4 +1,43 @@
//! RPC handler implementations for memory sources.
+//!
+//! # The engine references in this file (#5560), by surface
+//!
+//! This file sits on `direct_engine_refs_tests::ALLOWED` as `NeedsWiderSeam`.
+//! That verdict was re-tested on 2026-08-25 and it holds, for two independent
+//! reasons that are worth recording so the next reader does not re-derive
+//! them: **no** `MemoryProvider` member expresses any of the four surfaces
+//! below, and **every** symbol they name is defined in `tinymemory-core`
+//! itself rather than re-exported from a crate this manifest already lists, so
+//! there is no repoint available either. (Absence was checked against the
+//! contract at `vendor/tinymemory` HEAD, which leads the pinned release — an
+//! absence there is an absence in the pin.) `tinymemory_core::tinycortex` is
+//! an alias for `tinymemory_core::engine`, which is why all four read as
+//! `tinycortex::…` below.
+//!
+//! - **Coding sessions** — `CodingSessionIngestRequest`,
+//! `CodingSessionIngestResponse`, `CodingSessionSourceStatus`,
+//! `coding_session_status`, `ingest_coding_sessions`. TinyCortex's persona
+//! pipeline: `walkdir` over session roots, `RawSession`, `FileStateStore`.
+//! No capability family covers any of it.
+//! - **Raw-archive coverage** — `raw_coverage`, `rebuild_tree_from_raw`. A
+//! filesystem-vs-tree crosscheck. `MemoryTree` is namespace-addressed
+//! (`append` / `query_source` / `drill_down` / `seal` / `cascade` /
+//! `summary_forest` / `recent_leaves`) and has no coverage member.
+//! - **Sync audit log** — `SyncAuditEntry`, `read_audit_log`. A host-owned log
+//! read out of `MemoryHostConfig::workspace_dir`; nothing in the contract
+//! reads it.
+//! - **Sync cost model** — `estimate_cost_usd`. Pure arithmetic, so it *looks*
+//! like a free move host-side — but the same constants back
+//! `SyncAuditEntry::effective_cost_usd` (used in `monthly_cost_summary_rpc`
+//! below) and the engine's own cost accumulator. Copying it here would be a
+//! second price that can drift from the one the audit rows were written with.
+//!
+//! Clearing this file needs all four to move, not any one of them, and the
+//! first two are the persona and sync pipelines going behind the bus — Phase F
+//! work, not a call-site migration. One thing not to do in the meantime:
+//! re-routing these through the `memory::sync` / `memory::tinycortex`
+//! re-export shims takes the path off the scanner without removing an ounce of
+//! coupling, which is exactly the edit that would make the ratchet lie.
// `to_arc` / the config accessors are `MemoryHostConfig` trait methods.
use crate::openhuman::config::rpc as config_rpc;
@@ -11,17 +50,13 @@ 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.
+/// 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 — so 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. The module docs above record why it has not moved yet.
pub use tinymemory_core::tinycortex::CodingSessionIngestRequest;
#[derive(Debug, serde::Serialize)]
diff --git a/src/openhuman/memory/sync/composio/mod.rs b/src/openhuman/memory/sync/composio/mod.rs
index 5b60790de4..28cd946f5f 100644
--- a/src/openhuman/memory/sync/composio/mod.rs
+++ b/src/openhuman/memory/sync/composio/mod.rs
@@ -5,51 +5,66 @@
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::sync::composio::…` path resolving.
//!
-//! # 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,
-//! so the obvious reading is that this file goes with it.
-//!
-//! **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 (**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.
+//! # This shim cannot go yet — but the reason changed, so read this before acting on it
+//!
+//! **The upstream blocker is closed.** This section used to say the loops could
+//! not move because the pinned v1.5.0 module carried a heading reading *"The
+//! periodic sync loops are deliberately NOT started here"* and three reasons
+//! behind it: the pipeline read Composio credentials off `Config` rather than
+//! the `ComposioHost` seam, `global::client_if_ready()` was `None` inside the
+//! module, and `EngineRuntimeConfig::memory_sync_interval_secs()` answered
+//! `Some(0)` (which the contract defines as *manual only*, so every tick would
+//! skip every source silently).
+//!
+//! tinymemory#100 closed all three and shipped as **v1.6.0**, which is what
+//! `modules::registry` and `modules::memory`'s `ARTIFACT_CAPABILITIES_PIN` now
+//! pin. The host's half is wired too: `modules::ops` puts
+//! `memory_sync_interval_secs`, `composio_mode` and `composio_entity_id` into
+//! the `ModuleConfig` precisely so the module's own loops have a cadence and a
+//! mode to run with. `core/runtime/services.rs` no longer starts either loop
+//! and its comment block records why.
+//!
+//! # So what still pins this file, and it is not the loop
+//!
+//! The glob below is the only definition of every name in this list, and each
+//! one has a live caller and no capability family:
+//!
+//! - `periodic` — reached by `integrations::composio::{mod, periodic}`, and by
+//! `super::bus`, which calls `periodic::record_sync_success` after a
+//! trigger-driven sync.
+//! - `init_default_composio_sync_providers` + `all_composio_sync_providers` —
+//! `memory::sources::rpc`'s supported-toolkit list is built from exactly this
+//! pair; `get_composio_sync_provider` joins them in `tests/raw_coverage/`.
+//! - `SyncTarget` / `list_sync_targets` — `memory::ops::sync`'s manual
+//! trigger path.
+//! - `ComposioProvider`, `ProviderContext`, `ProviderUserProfile`,
+//! `SyncOutcome`, `SyncReason` — re-exported onward by
+//! `integrations::composio`.
+//!
+//! None has a capability family: the sync pipelines are engine-internal, and
+//! `MemorySourceSink` addresses source *records*, not provider runs. So this
+//! shim goes when the pipelines themselves move behind the bus — the same ask
+//! as `sync/composio/bus.rs` and `providers/slack/rpc.rs`, both of which call
+//! `tinycortex::run_composio_connection` directly.
+//!
+//! # ⚠ One host caller did not get the memo (found 2026-08-25)
+//!
+//! `services.rs` dropped its `start_periodic_sync()` call, but
+//! `channels/runtime/startup.rs` still makes one, through
+//! `integrations::composio::start_periodic_sync` → `periodic` → this glob. That
+//! is the *engine's* loop, started in this process, next to the module's own —
+//! which is the case `services.rs` warns is "worse than a duplicate", because
+//! the `cdylib` links its own `tinymemory-core` and neither loop's
+//! `SCHEDULER_STARTED` `OnceLock` can see the other. Its store handle is a
+//! second question: no production path calls `tinymemory_core::global::init`
+//! any more — only test fixtures do — so whatever that loop reaches is not the
+//! client the rest of the host uses.
+//!
+//! It is left alone here deliberately — that file is outside this change — but
+//! do not read "the loops moved" as done until it goes. Composio sync degrades
+//! **quietly** in either direction: a run that reports zero connections is
+//! indistinguishable from a user who has none, so a half-removed loop looks
+//! like a working one until someone notices their mail stopped being indexed.
pub use tinymemory_core::sync::composio::*;
diff --git a/src/openhuman/memory/sync/composio/providers/mod.rs b/src/openhuman/memory/sync/composio/providers/mod.rs
index a9a47e2adc..ee6dd6a06b 100644
--- a/src/openhuman/memory/sync/composio/providers/mod.rs
+++ b/src/openhuman/memory/sync/composio/providers/mod.rs
@@ -4,6 +4,26 @@
//! 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::composio::providers::…` path resolving.
+//!
+//! # The widest shim in the memory tree, and the least ambiguous (#5560)
+//!
+//! `integrations::composio::providers` is `pub use …providers::*` over this
+//! module, so the whole engine registry is public surface under two names: the
+//! six per-toolkit providers (`clickup`, `github`, `gmail`, `linear`, `notion`,
+//! `slack`), the curated catalogs, `tool_scope`, `user_scopes`, `sync_state`,
+//! `profile` / `profile_md`, and the `ComposioProvider` trait itself. Over a
+//! hundred call sites across `src/` and `tests/` reach it under one of the two
+//! — `flows`, the agent capability matrix, `memory::sources`, `read_rpc`, the
+//! composio RPC ops.
+//!
+//! There is nothing to route it through. The provider registry *is* the sync
+//! pipeline, no capability family addresses it, and the contract's
+//! `MemorySourceSink` covers source **records** rather than provider runs. So
+//! unlike the tree shims, this one is not blocked on a type identity or on a
+//! release — it is blocked on the sync pipelines moving behind the bus, which
+//! is a design pass upstream. Note the local `pub mod slack` below shadows the
+//! engine's `slack` from this glob; see that file before assuming either is
+//! droppable.
pub use tinymemory_core::sync::composio::providers::*;
diff --git a/src/openhuman/memory/sync/composio/providers/slack/mod.rs b/src/openhuman/memory/sync/composio/providers/slack/mod.rs
index 0776931e75..0e2fc44ee1 100644
--- a/src/openhuman/memory/sync/composio/providers/slack/mod.rs
+++ b/src/openhuman/memory/sync/composio/providers/slack/mod.rs
@@ -4,6 +4,19 @@
//! 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::composio::providers::slack::…` path resolving.
+//!
+//! # This one looks droppable from `src/` alone, and is not (#5560)
+//!
+//! Nothing under `src/` names a single item the glob supplies: `rpc.rs` reaches
+//! `SyncOutcome` through the parent `providers` module, and `schemas.rs` only
+//! reaches `super::rpc`. Reading that as "unused" and deleting the line breaks
+//! the build — four `tests/raw_coverage/` targets import `SlackProvider`,
+//! `run_backfill_via_search` and `post_process` through **this** path, and the
+//! engine's own module doc says `post_process` is `pub` for exactly that
+//! reason.
+//!
+//! `cargo test --lib` does not compile `tests/`, so that break would land in
+//! CI rather than locally. Grep both trees before narrowing any shim here.
pub use tinymemory_core::sync::composio::providers::slack::*;
diff --git a/src/openhuman/memory/sync/mod.rs b/src/openhuman/memory/sync/mod.rs
index a20ff06386..436ca403ae 100644
--- a/src/openhuman/memory/sync/mod.rs
+++ b/src/openhuman/memory/sync/mod.rs
@@ -1,11 +1,31 @@
-//! Host layer over [`tinymemory_core::sync`].
+//! Host layer over the memory sync domain.
//!
-//! 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::…` path resolving.
-
-pub use tinymemory_core::sync::*;
+//! What lives here is the JSON-RPC surface — handlers and controller schemas
+//! name OpenHuman's `RpcOutcome` and `ControllerSchema`, which no engine crate
+//! can see. The two submodules below are that surface.
+//!
+//! # Why there is no `pub use tinymemory_core::sync::*;` here any more (#5560)
+//!
+//! There was one, described as keeping "every historical `memory::sync::…` path
+//! resolving". It resolved nothing. The glob's only reachable contribution was
+//! four engine modules — `audit`, `mcp`, `pipelines`, `workspace` — because the
+//! other two names it carried (`composio`, `sync_status`) are declared below
+//! and an explicit item shadows a glob import. A repo-wide search for those
+//! four under this path found **no consumer**: not in `src/`, not in `tests/`,
+//! not in the desktop shell's separate Cargo world. Every real caller reaches
+//! the engine's sync pipelines by naming `tinycortex::memory::sync::…` (see
+//! `integrations::composio::ops::memory_cleanup`) or goes through
+//! `memory::sync::composio`, which is its own module.
+//!
+//! So this line was a compile-time edge to `tinymemory-core` bought for nobody,
+//! and dropping it is not a carve-out or a substitution — nothing resolved
+//! through it, so nothing changes shape. The sibling shims that *are* load
+//! bearing (`composio`, `composio::providers`, `composio::providers::slack`)
+//! keep theirs and say what pins them.
+//!
+//! Note that `sync_status` made the opposite move earlier and for a different
+//! reason: its glob carried two real names, and they were repointed at
+//! `tinycortex`, which defines them. See that module's own docs.
pub mod composio;
pub mod sync_status;
diff --git a/src/openhuman/memory/tool_memory/mod.rs b/src/openhuman/memory/tool_memory/mod.rs
index df05b16b8a..07b529c2a7 100644
--- a/src/openhuman/memory/tool_memory/mod.rs
+++ b/src/openhuman/memory/tool_memory/mod.rs
@@ -30,11 +30,15 @@
//! 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)]`
+//! `MockMemory` is a test fixture reached from four 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.
+//! engine crate in the shipped binary. It now sits in `test_support/` — a
+//! directory both memory lints skip by path, and `#[cfg(test)]` so it is not
+//! link-resolvable from a docs build — which is why the one line of this file
+//! that named the engine crate no longer reads as an unmigrated production
+//! call. See that module for why the classification is the point.
use std::sync::Arc;
@@ -62,14 +66,22 @@ pub fn tool_memory_store(memory: Arc<dyn Memory>) -> ToolMemoryStore {
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`.
+// The engine crate's `MockMemory` fixture, re-exported under its historical
+// path `memory::tool_memory::test_helpers`.
+//
+// Test-only in both directions: `tinymemory-core` compiles it behind
+// `cfg(any(test, feature = "test-support"))`, and both items below are
+// `#[cfg(test)]`, so they exist only in `cargo test --lib` builds where the
+// dev-dependency at `Cargo.toml`'s `[dev-dependencies]` supplies the crate.
+// Four inline `#[cfg(test)]` modules reach it — `capture` in this directory,
+// `agent::experience::{capture, store}` and
+// `agent::tinyagents::host::experience_store`.
+//
+// The `pub use tinymemory_core::…` line itself sits one level down, in
+// `test_support/mod.rs`; that module's docs say why, and the path callers use
+// does not change.
+#[cfg(test)]
+pub mod test_support;
+
#[cfg(test)]
-pub use tinymemory_core::tool_memory::test_helpers;
+pub use test_support::test_helpers;
diff --git a/src/openhuman/memory/tool_memory/test_support/mod.rs b/src/openhuman/memory/tool_memory/test_support/mod.rs
new file mode 100644
index 0000000000..f3da257f36
--- /dev/null
+++ b/src/openhuman/memory/tool_memory/test_support/mod.rs
@@ -0,0 +1,35 @@
+//! The engine crate's tool-memory test fixtures, re-exported for this tree.
+//!
+//! One line, and it lives in its own directory on purpose. `MockMemory` is a
+//! `tinymemory-core` fixture compiled behind `cfg(any(test, feature =
+//! "test-support"))`, reached from four inline `#[cfg(test)]` modules —
+//! `memory::tool_memory::capture`, `agent::experience::{capture, store}` and
+//! `agent::tinyagents::host::experience_store`. `cfg(test)` code links the
+//! `tinymemory-core` **dev-dependency** (declared with `features =
+//! ["test-support"]` at `Cargo.toml`'s `[dev-dependencies]`), which survives
+//! #5560's shed — so this names the engine crate without putting a byte of it
+//! in the shipped binary.
+//!
+//! # Why it is not in the parent `mod.rs`
+//!
+//! It was, as a `#[cfg(test)] pub use`, and the parent's own docs already
+//! explained that it is dev-only. `memory::direct_engine_refs_tests` could not
+//! see that explanation: its scanner reads line by line and skips only comments
+//! and whole files, deliberately, because brace-tracking inline `#[cfg(test)]`
+//! blocks is the complexity that lint's docs say it does not want. So a
+//! genuinely test-only reference kept a production file on the direct-reference
+//! allowlist, which made "deliberate" and "not migrated yet" look identical in
+//! the one list that exists to tell them apart.
+//!
+//! `test_support/` is the escape hatch both scanners already honour by path
+//! (`is_test_path` in `direct_engine_refs_tests` and in `bypass_allowlist_tests`
+//! each match on a `test_support` path *component*, which is why this is a
+//! directory and not a `test_support.rs`). Moving the line here classifies it
+//! rather than hiding it: the reference is unchanged, still `#[cfg(test)]`, and
+//! still the dev-dependency's.
+//!
+//! The public path callers use is unchanged —
+//! `memory::tool_memory::test_helpers::MockMemory` — because the parent
+//! re-exports this module's contents under that name.
+
+pub use tinymemory_core::tool_memory::test_helpers;
diff --git a/src/openhuman/memory/tools/flavour.rs b/src/openhuman/memory/tools/flavour.rs
index 72be75a7b6..ff599de768 100644
--- a/src/openhuman/memory/tools/flavour.rs
+++ b/src/openhuman/memory/tools/flavour.rs
@@ -24,26 +24,6 @@ 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.
const VALID_FLAVOURS: &str =
@@ -114,7 +94,37 @@ pub(crate) fn lookup_flavour(config: &Config, flavour_raw: &str) -> Result<Flavo
format!("Unknown flavour '{flavour_raw}'. Valid flavours: {VALID_FLAVOURS}")
})?;
- let mc = memory_config_from(config, config.workspace_dir.clone());
+ // The `MemoryConfig` the three TinyCortex calls below take, built here
+ // rather than through `tinymemory_core::tinycortex::memory_config_from` —
+ // the engine crate's `Config` → `MemoryConfig` mapping, and what used to be
+ // the one `tinymemory_core::` reference in this file (#5560).
+ //
+ // That mapping sets three fields. Two of them are read on this path and are
+ // reproduced verbatim: `workspace`, which is where `get_tree_by_scope` and
+ // `compile_flavoured_root` open the shared chunk/tree connection, and
+ // `content_root`, which `flavoured_root_abs_path` resolves the compiled
+ // artifact under (`memory_tree.content_dir` when the user set one, else
+ // `<workspace>/memory_tree/content`). `Config::memory_tree_content_root` is
+ // the host's own single source of truth for that path, so this reads the
+ // same value the engine mapping read.
+ //
+ // The third — `embedding`, whose `provider` the engine derives from its
+ // `effective_embedder_slug` ladder — is deliberately left at its default,
+ // and this is the one reduction to be aware of. That field is the signature
+ // per-model embedding sidecar rows are keyed by, so it matters wherever a
+ // vector is written or matched; **nothing on this path is.** `memory_flavour`
+ // is strictly read-only over the flavoured tree: `get_tree_by_scope` and
+ // `store::get_summary` are plain SQL over `mem_tree_trees` /
+ // `mem_tree_summaries`, and `compile_flavoured_root` clamps the root node's
+ // stored content to `tree.flavour_root_token_budget` and stages it as
+ // markdown. None of the three reads `config.embedding`.
+ //
+ // So: if a call that embeds, re-embeds, or matches a vector is ever added
+ // to this file, this config is no longer sufficient and the embedder ladder
+ // has to come with it. A defaulted signature would file rows under the
+ // wrong provider, which is silent rather than loud.
+ let mut mc = tinycortex::memory::MemoryConfig::new(config.workspace_dir.clone());
+ mc.content_root = Some(config.memory_tree_content_root());
let scope = facet.tree_scope();
let heading = facet.heading();
diff --git a/src/openhuman/memory/tree/health/mod.rs b/src/openhuman/memory/tree/health/mod.rs
index 63a5bc882e..13e93d9b90 100644
--- a/src/openhuman/memory/tree/health/mod.rs
+++ b/src/openhuman/memory/tree/health/mod.rs
@@ -2,6 +2,35 @@
//!
//! The health model and its classifier are core; what stays here is the
//! `user_error` wire payload, which rides a web channel.
+//!
+//! # Do not repoint this at `memory::api::health` — it is a different thing (#5560)
+//!
+//! The name collides and the types do not. `tinymemory_api::health` is
+//! `MemoryHealth`, driver *liveness*, one enum. This module is pipeline
+//! *failure classification* — `FailureCode`, `FailureClass`, `PipelineFailure`,
+//! `DegradedState` — and `tinycortex::memory::health`'s own docs call the
+//! confusion out by name. A swap would compile at neither end.
+//!
+//! What the glob carries splits cleanly in two, which is why it cannot go yet
+//! and equally cannot be half-repointed without saying so:
+//!
+//! - **The taxonomy** (`FailureCode`, `FailureClass`, `PipelineFailure`,
+//! `DegradedState`, `classify_embed_error{,_str}`) is `tinycortex`'s; the
+//! engine crate only re-exports it. These would follow the
+//! `memory::sync::sync_status` precedent and be named on `tinycortex`
+//! directly.
+//! - **The process-global degradation flags** (`mark_*` / `clear_*` /
+//! `current_degraded_state`), the `doctor` report and its `test_guard` are
+//! defined *in* `tinymemory-core`. They have no home to be repointed at, so
+//! they are what actually pins this file — and the reason mixing the two
+//! halves into one `pub use` line hides which is which.
+//!
+//! Worth knowing before trusting a reading of `current_degraded_state()`: the
+//! flags are process statics, and the loaded module links its **own** copy of
+//! `tinymemory-core`. A degradation the module observes never reaches the
+//! statics this host reads. That is pre-existing and is not #5560's to fix, but
+//! it is the reason moving the flags host-side is a design question rather than
+//! a file move.
pub use tinymemory_core::tree::health::*;
diff --git a/src/openhuman/memory/tree/mod.rs b/src/openhuman/memory/tree/mod.rs
index 665394271f..0e7f7fb7f4 100644
--- a/src/openhuman/memory/tree/mod.rs
+++ b/src/openhuman/memory/tree/mod.rs
@@ -4,6 +4,36 @@
//! 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::tree::…` path resolving.
+//!
+//! # What the glob still carries, checked rather than assumed (#5560)
+//!
+//! Four of the nine module names it supplies (`health`, `retrieval`, `tree`,
+//! `tree_runtime`) are shadowed by the `pub mod` declarations below — an
+//! explicit item beats a glob import — so its live contribution is narrower
+//! than it looks, and all of it is engine-owned:
+//!
+//! - `score`, `summarise`, `nlp`, `ingest` — real code in `tinymemory-core`,
+//! not thin aliases: `score::embed::{Embedder, build_embedder_from_config,
+//! effective_embedder_slug, EMBEDDING_DIM}`, `score::extract::EntityKind`,
+//! `score::store`, `score::resolver`, `summarise::{summarise,
+//! fallback_summary, SummaryContext, SummaryInput}` and
+//! `nlp::extract_query_entities` are reached from the archivist, the
+//! sub-agent runner, `read_rpc::entities`, `inference::embeddings::rpc` and
+//! `retrieval/rpc.rs` in this directory.
+//! - the seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
+//! ReadResult, WriteOutcome, WriteRequest}` I/O types, which the crate
+//! re-exports out of `engine::backend::tree`. Nothing in `src/` names them —
+//! `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all seven,
+//! which is why narrowing this glob to what `src/` uses would compile here
+//! and break the integration lane.
+//!
+//! (`graph` is the fifth unshadowed name and has no caller under this path at
+//! all — it is carried only because the glob is all-or-nothing.)
+//!
+//! None of it has a contract equivalent: `tinymemory_api::tree` is the summary
+//! node vocabulary, not an embedder or an entity extractor. So this shim is
+//! pinned by the engine's *scoring and summarisation* internals, and it goes
+//! when those move behind the bus — not before.
pub use tinymemory_core::tree::*;
diff --git a/src/openhuman/memory/tree/retrieval/mod.rs b/src/openhuman/memory/tree/retrieval/mod.rs
index 3da77b65e4..48ed15158e 100644
--- a/src/openhuman/memory/tree/retrieval/mod.rs
+++ b/src/openhuman/memory/tree/retrieval/mod.rs
@@ -11,6 +11,14 @@
// The engine's hit carries a `tree_kind` the contract's has no field for, so
// repointing this shim at `memory::api::provider` is a wire change and not a
// path swap. Probe the item identity before assuming a carve-out is free.
+//
+// What keeps this line alive (#5560): `fast_retrieve` + `FastRetrieveOptions`
+// (memory::agent::ops, memory::schema::handlers), `types::{NodeKind,
+// QueryResponse, RetrievalHit}` (read_rpc::chunks, the sub-agent runner),
+// `source::{SourceQuery, query_source_scoped}` (read_rpc::chunks) and
+// `search::search_entities` — plus `{query_source, search_entities}` from the
+// memory e2e suites. Every one names a shape the contract does not carry, so
+// this is the same wire-change ask as the paragraph above, not a routing one.
pub use tinymemory_core::tree::retrieval::*;
pub mod rpc;
diff --git a/src/openhuman/memory/tree/tree/mod.rs b/src/openhuman/memory/tree/tree/mod.rs
index 845dfe8b6e..93884a5fd7 100644
--- a/src/openhuman/memory/tree/tree/mod.rs
+++ b/src/openhuman/memory/tree/tree/mod.rs
@@ -11,6 +11,15 @@
// different type from the contract's `TreeStatus`, which the sibling
// `tree_runtime` module exports. Two same-named types one module apart, so
// check which one a call site means before moving it.
+//
+// What keeps this line alive (#5560), so the next reader does not re-derive it:
+// `read_rpc::admin`'s `flush_source_tree` needs `TreeFactory` and
+// `flush::force_flush_tree`, and `integrations::composio::ops_tests` +
+// `tests/raw_coverage/` reach `bucket_seal::{seal_one_level, LabelStrategy}`,
+// `store::get_tree_by_scope`, `registry::is_unique_violation` and
+// `set_summary_embedding`. `MemoryTree` on the contract is namespace-addressed
+// (append / query_source / drill_down / seal / cascade / summary_forest /
+// recent_leaves) and has no door onto a tree *object*, which is the ask.
pub use tinymemory_core::tree::tree::*;
pub mod rpc;
diff --git a/src/openhuman/memory/tree/tree/rpc.rs b/src/openhuman/memory/tree/tree/rpc.rs
index a3ab0dd5b4..6643c300d2 100644
--- a/src/openhuman/memory/tree/tree/rpc.rs
+++ b/src/openhuman/memory/tree/tree/rpc.rs
@@ -334,27 +334,47 @@ fn response_from_engine(source_id: String, result: IngestResult) -> IngestRespon
/// swap and not a wire change —
/// `the_response_body_serialises_exactly_as_the_engine_summary` still holds.
///
-/// **Mail stays on the in-process pipeline**, for two reasons that the pin
-/// does not touch:
+/// **Mail is still on the in-process pipeline, and it is the last thing in this
+/// file that is** (#5560). This paragraph used to list two blockers, and
+/// **both are closed** — re-checked 2026-08-25 rather than inherited, because
+/// leaving them stated is what would stop the next reader from finishing it:
///
-/// 1. `IngestItem` carries no recipient list, no per-message subject and no
-/// `List-Unsubscribe`, and the driver's mail mapping fills those with
-/// `Vec::new()` / the thread subject / `None`. A thread routed through
-/// `ingest_email` therefore loses those header lines from the canonical
-/// markdown — content that is chunked, embedded and searched, and, for the
-/// unsubscribe link, read back out of retrieved mail to populate the
-/// `gmail_unsubscribe` tool's required argument. Nothing on this side can
-/// preserve them: the loss happens inside the driver's mapping, below any
-/// field this handler can set.
-/// 2. `ModuleMemoryProvider` — the driver every shipped build binds — does not
-/// forward `IngestEmail`. The module declares the method and the contract
-/// has served it since v1.4.0, but the host-side forwarder in
-/// `modules::memory` implements only `ingest_document` and `ingest_chat`,
-/// so the trait's default body would answer `Unsupported` and every mail
-/// ingest would fail at run time.
+/// 1. *"`IngestItem` carries no recipient list, no per-message subject and no
+/// `List-Unsubscribe`."* It carries all of them now, plus `platform`, and
+/// the contract's own field docs are written for this path — they say
+/// dropping the unsubscribe header makes the unsubscribe flow impossible
+/// rather than merely less complete. `chat_items` and `document_item`
+/// already spell the five mail fields as their not-mail values.
+/// 2. *"`ModuleMemoryProvider` does not forward `IngestEmail`."* It does —
+/// `modules::memory` implements `ingest_email` beside `ingest_document` and
+/// `ingest_chat`, and the module declares the member.
///
-/// Both have to be answered before the mail arm can move: (1) by widening
-/// `IngestItem` upstream, (2) by a forwarder in `modules::memory`.
+/// The driver's mapping is a lossless inverse: it rebuilds `EmailThread` with
+/// `provider` from `platform`, `thread_subject` from `channel_label`, `from`
+/// from `author`, and `to` / `cc` / `subject` / `list_unsubscribe` verbatim,
+/// then calls the same `ingest_pipeline::ingest_email` this arm calls now.
+///
+/// So what is left is host work plus one verification, and neither is a
+/// contract change:
+///
+/// - An `email_items(source_id, owner, tags, EmailThread)` mapper that is the
+/// **exact** inverse of that reconstruction (`platform: Some(provider)`,
+/// `channel_label: Some(thread_subject)`, `author: Some(from)`,
+/// `subject: Some(msg.subject)` — always `Some`, so no `unwrap_or` fallback
+/// on the far side can substitute a different value), a `DataSource` chooser
+/// in the shape of `chat_data_source`, and a `DriverIngest::Email` arm.
+/// - A decision on empty bodies, which is a real behaviour delta and wants its
+/// own test: `validate_ingest_item` answers `Invalid` for empty content and
+/// the driver validates every item before ingesting any, so one body-less
+/// message fails the whole thread where the in-process pipeline writes the
+/// rest of it. The chat arm answers this by filtering first; mail has to
+/// choose the same, and a header-only message is more plausible in mail.
+/// - **Check the released artifact, not the submodule.** The five mail fields
+/// are `#[serde(default)]`, so a pinned module that predates them decodes
+/// every one to its default and mail loses its headers **silently** — the
+/// capability check stays green because the family and the member both
+/// exist. `vendor/tinymemory` is currently *behind* the pinned release, so
+/// grep the tag.
pub async fn ingest_rpc(
config: &Config,
req: IngestRequest,
diff --git a/src/openhuman/memory/tree/tree_runtime/mod.rs b/src/openhuman/memory/tree/tree_runtime/mod.rs
index d21eed461c..9309126b7f 100644
--- a/src/openhuman/memory/tree/tree_runtime/mod.rs
+++ b/src/openhuman/memory/tree/tree_runtime/mod.rs
@@ -4,6 +4,29 @@
//! 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::tree::tree_runtime::…` path resolving.
+//!
+//! # What is left of the glob, and the one thing that pins it (#5560)
+//!
+//! Everything below this line is already off the engine crate: the node model
+//! is named on the contract (see the next comment), and `ops.rs` reaches the
+//! summarisation entry points at `tinycortex::memory::tree::runtime::*`
+//! directly. What the glob still supplies is exactly two modules:
+//!
+//! - `engine` — `run_summarization` / `rebuild_tree` / `run_hourly_loop`,
+//! thin adapters that wrap the host `Config` around tinycortex's `*_observed`
+//! entry points and publish `TreeSummarizer*` events.
+//! - `store` — ~18 `Config`-taking wrappers over
+//! `tinycortex::memory::tree::runtime::store`.
+//!
+//! Both are one step: they call `engine_config(config)`, which is
+//! `tinymemory_core::tinycortex::memory_config_from`. So the blocker here is
+//! not a capability family, it is that **nothing host-side can build a
+//! `tinycortex::memory::MemoryConfig`.** That function resolves the embedder
+//! slug through the engine's own resolution ladder (`effective_embedder_slug`),
+//! and keying a vector sidecar on the wrong provider files local vectors under
+//! the cloud one — so it is not a helper worth reimplementing from the outside.
+//! `memory::sync::sync_status::rpc` and `memory::tools::flavour` are blocked on
+//! the same call.
pub use tinymemory_core::tree::tree_runtime::*;