The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(memory): pin v1.4.0 and route ingest and retrieval through the contract
Shanu65b895b7b671
diff --git a/Cargo.lock b/Cargo.lockindex e34087272c..4a792d65a9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2682,7 +2682,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.57.0",][[package]]@@ -6553,7 +6553,7 @@ dependencies = [[[package]]name = "tinymemory"-version = "1.3.0"+version = "1.4.0"dependencies = ["anyhow","async-trait",diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lockindex 3678a2905c..d2e755d40f 100644--- a/app/src-tauri/Cargo.lock+++ b/app/src-tauri/Cargo.lock@@ -2798,7 +2798,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.57.0",+ "windows-core 0.58.0",][[package]]@@ -7273,7 +7273,7 @@ dependencies = [[[package]]name = "tinymemory"-version = "1.3.0"+version = "1.4.0"dependencies = ["anyhow","async-trait",diff --git a/src/openhuman/memory/bypass_allowlist_tests.rs b/src/openhuman/memory/bypass_allowlist_tests.rsindex b5102f45cd..b1c2f65638 100644--- a/src/openhuman/memory/bypass_allowlist_tests.rs+++ b/src/openhuman/memory/bypass_allowlist_tests.rs@@ -211,6 +211,11 @@ const ALLOWED: &[(&str, &str, &str)] = &["MemoryClient::from_workspace_dir(","inline #[cfg(test)] module only; the scanner does not brace-track test blocks",),+ (+ "src/openhuman/memory/tree/retrieval/rpc.rs",+ "NullMemoryProvider::new(",+ "inline #[cfg(test)] module only; it builds the no-retrieval driver these handlers must degrade against, which is the opposite of a bypass — the test exists to prove the family is asked for and its absence handled",+ ),("src/openhuman/agent/learning/startup.rs","binding::for_workspace(",diff --git a/src/openhuman/memory/tree/retrieval/rpc.rs b/src/openhuman/memory/tree/retrieval/rpc.rsindex f91ceac3e9..a05d248ca1 100644--- a/src/openhuman/memory/tree/retrieval/rpc.rs+++ b/src/openhuman/memory/tree/retrieval/rpc.rs@@ -1,48 +1,68 @@//! JSON-RPC handler bodies for Phase 4 retrieval tools (#710).//!-//! Each handler is a thin wrapper around its `retrieval::<tool>` function.-//! Shapes mirror the internal API — in particular, `QueryResponse` and-//! `Vec<RetrievalHit>` / `Vec<EntityMatch>` all serialise directly without-//! an extra envelope.+//! Shapes mirror the contract's — `RetrievalResponse` and `Vec<RetrievalHit>` /+//! `Vec<EntityMatch>` all serialise directly, without an extra envelope.//!-//! # Why these five still call the engine when `MemoryRetrieval` exists+//! # All five read through `MemoryRetrieval`//!-//! The contract family covers every one of them member for member-//! (`retrieve_source`, `cover_window`, `retrieve_children`, `retrieve_leaves`,-//! `search_entities`), the pinned artifact serves them, and-//! `memory::query::backend` — the agent-tool path over the *same* primitives —-//! already goes through it. What stops these handlers following is the-//! response body, not the seam.+//! Member for member: `retrieve_source`, `cover_window`, `retrieve_children`,+//! `retrieve_leaves`, `search_entities`. Nothing here reaches the engine.//!-//! `QueryResponse` here is the engine's, and its `RetrievalHit` carries a-//! `tree_kind` field that the contract's `RetrievalHit` does not have. It is-//! serialised unconditionally, so routing through the family would silently-//! drop a field from four public methods' output. `EntityMatch` is the-//! opposite case and is safe: its `kind` is a `#[serde(rename_all =-//! "snake_case")]` enum against the contract's open `String`, so the two encode-//! identically — the whole delta is `tree_kind`.+//! The four hit-returning handlers were held back while the pinned artifact was+//! TinyMemory v1.3.0, whose `RetrievalHit` had no `tree_kind`. The field is+//! `skip_serializing_if = "Option::is_none"`, so routing them then would have+//! decoded every hit's kind as `None` and dropped the key from four public+//! responses. v1.4.0 (tinymemory#95) carries it, and `modules::registry` plus+//! `ARTIFACT_CAPABILITIES_PIN` both name that release, so the loss is no longer+//! reachable: the engine's own `RetrievalHit::tree_kind` is a **non-optional**+//! `TreeKind`, the driver builds the contract's hit by serialising the engine's,+//! and a `#[serde(rename_all = "snake_case")]` enum against the contract's open+//! `String` encodes identically. Every hit that reaches this file therefore+//! carries `Some(kind)` and re-emits the same key with the same value+//! (`source`, `topic`, `global`, `flavoured`). A `None` would take a driver that+//! never ran the engine at all, and for that one the contract's reading — no+//! tree, so no kind to report — is why the key is omitted rather than sent as+//! `null`; inventing `source` there would be the silent-wrong-data case the+//! placeholder rule already rejects for summaries.//!-//! Migrating therefore means renegotiating the wire shape (or teaching the-//! contract the field), which is a decision about the RPC surface rather than a-//! routing change, and belongs in its own change.+//! `EntityMatch` is the same kind of identity: the engine's `kind` is a+//! snake_case enum where the contract's is an open `String`.//!-//! The `*_scoped` variants are deliberate and must stay: the ambient twins read-//! the **engine's** task-local, which this host no longer sets, and an absent-//! scope means unrestricted — a per-profile source gate failing open. See-//! `memory::source_scope`.+//! The envelopes match field for field and in declaration order —+//! `RetrievalResponse` against the engine's `QueryResponse` (`hits`, `total`,+//! `truncated`) and `RetrievalHit` against the engine's (`node_id` through+//! `source_ref`) — so the JSON these handlers emit is byte-identical to what+//! they emitted while they called the engine directly. The frontend reads it.+//!+//! # The scope argument is the source gate, and is never a literal `None`+//!+//! `binding.provider()` is the **unguarded** driver: nothing between this file+//! and the store re-applies the per-profile `memory_sources` allowlist, so the+//! scope each call passes is the gate. The engine's `*_scoped` entry points+//! existed for the same reason — their ambient twins read the ENGINE's+//! task-local, which a separately compiled module cannot see, and an absent+//! scope means unrestricted, i.e. the gate failing open.+//!+//! Every call below passes `source_scope::as_bus_scope()`, which renders this+//! host's own task-local in the contract's vocabulary. `None` from it means+//! genuinely unrestricted and must stay `None`: an **empty** `SourceScope`+//! denies every source-attributed row, so mapping "no restriction" onto one+//! would invert the policy. A literal `None` written at the call site instead+//! is the open failure this seam exists to prevent.+//!+//! `search_entities` is the one member that takes no scope on either side — the+//! entity index is not source-attributed — so there is nothing to pass.use serde::{Deserialize, Serialize};use crate::openhuman::config::Config;-use crate::openhuman::memory::source_scope::current_source_scope;-use crate::openhuman::memory::tree::retrieval::{- cover::cover_window_scoped,- drill_down::drill_down_scoped,- fetch::fetch_leaves_scoped,- search::search_entities,- source::{query_source_scoped, SourceQuery},- types::{EntityMatch, QueryResponse, RetrievalHit},+// The contract's retrieval vocabulary, not the engine's: these handlers return+// what the driver handed back. The two encode identically (see the module+// docs), so this is a Rust-type change and not a wire one.+use crate::openhuman::memory::api::provider::retrieval::{+ CoverWindowQuery, EntityMatch, RetrievalHit, RetrievalResponse, SourceRetrievalQuery,};+use crate::openhuman::memory::source_scope::as_bus_scope;use crate::openhuman::memory::tree::score::extract::EntityKind;use crate::rpc::RpcOutcome;use tinymemory_api::chunks::SourceKind;@@ -50,7 +70,9 @@ use tinymemory_api::chunks::SourceKind;// ── query_source ──────────────────────────────────────────────────────/// Request body for `memory_tree_query_source`. All fields are optional;-/// see [`super::source::query_source`] for selection semantics.+/// see [`MemoryRetrieval::retrieve_source`] for selection semantics.+///+/// [`MemoryRetrieval::retrieve_source`]: crate::openhuman::memory::api::provider::retrieval::MemoryRetrieval::retrieve_source#[derive(Clone, Debug, Default, Serialize, Deserialize)]pub struct QuerySourceRequest {#[serde(default)]@@ -69,32 +91,51 @@ pub struct QuerySourceRequest {pub limit: Option<usize>,}-/// JSON-RPC handler body for `memory_tree_query_source`. Parses the-/// request, delegates to [`super::source::query_source`], and wraps the+/// JSON-RPC handler body for `memory_tree_query_source`. Parses the request,+/// reads through the bound driver's `MemoryRetrieval` family, and wraps the/// outcome with a PII-redacted log line.pub async fn query_source_rpc(config: &Config,req: QuerySourceRequest,-) -> Result<RpcOutcome<QueryResponse>, String> {+) -> Result<RpcOutcome<RetrievalResponse>, String> {+ // Parsed before the driver is resolved, so an unknown kind stays a caller+ // error naming the offending value rather than a driver round trip that+ // matches nothing and reads as an empty store.let source_kind = match req.source_kind.as_deref() {Some(s) => Some(SourceKind::parse(s).map_err(|e| format!("query_source: {e}"))?),None => None,};- let limit = req.limit.unwrap_or(0);- // Explicit scope — see the note in `cover_window_rpc`.- let resp = query_source_scoped(- config,- SourceQuery {- source_id: req.source_id.as_deref(),- source_kind,- time_window_days: req.time_window_days,- query: req.query.as_deref(),- limit,- },- current_source_scope(),- )- .await- .map_err(|e| format!("query_source: {e}"))?;+ let query = SourceRetrievalQuery {+ source_id: req.source_id.clone(),+ source_kind,+ time_window_days: req.time_window_days,+ query: req.query.clone(),+ // 0 is the engine's "no caller preference" sentinel, not a request for+ // zero rows, and the driver forwards `limit` verbatim — so the+ // absent-limit default stays the engine's, exactly as it was on the+ // direct call.+ limit: req.limit.unwrap_or(0),+ };+ // The explicit scope, never `None` — see the module docs.+ let scope = as_bus_scope();++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let resp = match binding.provider().as_retrieval() {+ Some(retrieval) => retrieval+ .retrieve_source(&query, scope.as_ref())+ .await+ .map_err(|e| format!("query_source: {e}"))?,+ // Read-only, so an empty page is the honest answer: a driver with no+ // retrieval family keeps no summary tree to rank, which is a true+ // statement about it rather than a fault the caller can act on.+ None => {+ log::debug!(+ "[memory-tree][rpc] query_source: driver '{}' does not serve Retrieval; reporting empty",+ binding.driver_id()+ );+ RetrievalResponse::default()+ }+ };let n = resp.hits.len();// Omit scope / source_id from the log — can carry PII. Log counts only.Ok(RpcOutcome::single_log(@@ -113,7 +154,9 @@ pub async fn query_source_rpc(/// Request body for `memory_tree_cover_window`. `since_ms`/`until_ms` are the/// inclusive window bounds in epoch-milliseconds; the source filter mirrors-/// `query_source`. See [`super::cover::cover_window`] for cover semantics.+/// `query_source`. See [`MemoryRetrieval::cover_window`] for cover semantics.+///+/// [`MemoryRetrieval::cover_window`]: crate::openhuman::memory::api::provider::retrieval::MemoryRetrieval::cover_window#[derive(Clone, Debug, Default, Serialize, Deserialize)]pub struct CoverWindowRequest {pub since_ms: i64,@@ -127,11 +170,15 @@ pub struct CoverWindowRequest {}/// JSON-RPC handler body for `memory_tree_cover_window`. Parses the request,-/// delegates to [`super::cover::cover_window`], logs PII-redacted counts.+/// reads through the bound driver, logs PII-redacted counts.+///+/// An inverted window is the driver's rejection to make, not this handler's:+/// the bound engine already refuses one naming both bounds, and duplicating the+/// guard here would let the two disagree about what a valid window is.pub async fn cover_window_rpc(config: &Config,req: CoverWindowRequest,-) -> Result<RpcOutcome<QueryResponse>, String> {+) -> Result<RpcOutcome<RetrievalResponse>, String> {log::debug!("[rpc][memory_tree] cover_window enter since_ms={} until_ms={} has_source_id={} has_source_kind={} has_limit={}",req.since_ms,@@ -147,24 +194,38 @@ pub async fn cover_window_rpc(}None => None,};- let limit = req.limit.unwrap_or(0);- log::trace!("[rpc][memory_tree] cover_window dispatch limit={limit}");- // `cover_window_scoped`, not `cover_window`: the ambient variant reads the- // ENGINE's task-local, and this host now sets its own- // (`memory::source_scope`) because a task-local cannot cross to the loadable- // memory module. Reading the engine's here would find it absent, and absent- // means unrestricted — a per-profile source gate failing open.- let resp = cover_window_scoped(- config,- req.since_ms,- req.until_ms,- req.source_id.as_deref(),+ log::trace!(+ "[rpc][memory_tree] cover_window dispatch limit={:?}",+ req.limit+ );+ let window = CoverWindowQuery {+ since_ms: req.since_ms,+ until_ms: req.until_ms,+ source_id: req.source_id.clone(),source_kind,- limit,- current_source_scope(),- )- .await- .map_err(|e| format!("cover_window: {e}"))?;+ // Forwarded as the caller sent it: the driver maps an absent limit onto+ // the engine's 0 sentinel, which is what `None` has always meant here.+ limit: req.limit,+ };+ // The explicit scope, never `None` — see the module docs.+ let scope = as_bus_scope();++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let resp = match binding.provider().as_retrieval() {+ Some(retrieval) => retrieval+ .cover_window(&window, scope.as_ref())+ .await+ .map_err(|e| format!("cover_window: {e}"))?,+ // Read-only: a driver with no retrieval family has no nodes to cover+ // the window with, which is a true statement about it.+ None => {+ log::debug!(+ "[memory-tree][rpc] cover_window: driver '{}' does not serve Retrieval; reporting empty",+ binding.driver_id()+ );+ RetrievalResponse::default()+ }+ };let n = resp.hits.len();log::debug!("[rpc][memory_tree] cover_window exit hits={} total={}",@@ -204,7 +265,8 @@ pub struct SearchEntitiesResponse {}/// JSON-RPC handler body for `memory_tree_search_entities`. Validates the-/// optional `kinds` filter against [`EntityKind`].+/// optional `kinds` filter against [`EntityKind`], then reads the entity index+/// through the bound driver's `MemoryRetrieval` family.pub async fn search_entities_rpc(config: &Config,req: SearchEntitiesRequest,@@ -212,20 +274,47 @@ pub async fn search_entities_rpc(// Capture logging-friendly summary BEFORE we move fields out of `req`.let query_len = req.query.len();let has_kinds = req.kinds.is_some();- let kinds = match req.kinds {+ // Parsed before the driver is resolved, so an unknown kind stays a caller+ // error naming the offending value rather than a driver round trip that+ // matches nothing and reads as an empty index — the ambiguity the contract+ // requires this filter to be validated against. `EntityKind::parse` is+ // exact-match, so `as_str` re-emits what a caller that got it right sent.+ let kinds: Option<Vec<String>> = match req.kinds {None => None,Some(list) => {- let parsed: Result<Vec<EntityKind>, String> = list+ let parsed: Result<Vec<String>, String> = list.iter()- .map(|s| EntityKind::parse(s).map_err(|e| format!("search_entities: {e}")))+ .map(|s| {+ EntityKind::parse(s)+ .map(|kind| kind.as_str().to_string())+ .map_err(|e| format!("search_entities: {e}"))+ }).collect();Some(parsed?)}};+ // 0 is the engine's "no caller preference" sentinel, not a request for zero+ // rows, and the driver forwards `limit` verbatim — so the absent-limit+ // default stays the engine's, exactly as it was on the direct call.let limit = req.limit.unwrap_or(0);- let matches = search_entities(config, &req.query, kinds, limit)- .await- .map_err(|e| format!("search_entities: {e}"))?;++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let matches = match binding.provider().as_retrieval() {+ Some(retrieval) => retrieval+ .search_entities(&req.query, kinds.as_deref(), limit)+ .await+ .map_err(|e| format!("search_entities: {e}"))?,+ // Read-only, so an empty match list is the honest answer: a driver with+ // no retrieval family keeps no entity index to search, which is a true+ // statement about it rather than a fault the caller can act on.+ None => {+ log::debug!(+ "[memory-tree][rpc] search_entities: driver '{}' does not serve Retrieval; reporting empty",+ binding.driver_id()+ );+ Vec::new()+ }+ };let n = matches.len();// Don't log the raw search query — can be an email, handle, etc. Log// only its length and the kind filter.@@ -261,22 +350,41 @@ pub struct DrillDownResponse {}/// JSON-RPC handler body for `memory_tree_drill_down`.+///+/// Reads through the contract's `retrieve_children`, which is this tool's+/// member despite the name: the tree family's `drill_down` returns a node and+/// its direct children, where this returns ranked hits several levels deep.pub async fn drill_down_rpc(config: &Config,req: DrillDownRequest,) -> Result<RpcOutcome<DrillDownResponse>, String> {let depth = req.max_depth.unwrap_or(1);- // Explicit scope — see the note in `cover_window_rpc`.- let hits = drill_down_scoped(- config,- &req.node_id,- depth,- req.query.as_deref(),- req.limit,- current_source_scope(),- )- .await- .map_err(|e| format!("drill_down: {e}"))?;+ // The explicit scope, never `None` — see the module docs.+ let scope = as_bus_scope();++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let hits = match binding.provider().as_retrieval() {+ Some(retrieval) => retrieval+ .retrieve_children(+ &req.node_id,+ depth,+ req.query.as_deref(),+ req.limit,+ scope.as_ref(),+ )+ .await+ .map_err(|e| format!("drill_down: {e}"))?,+ // Read-only, and an empty vector is already this handler's answer for a+ // node with no children — a driver with no retrieval family has no tree+ // to walk, so the degrade is indistinguishable from the ordinary miss.+ None => {+ log::debug!(+ "[memory-tree][rpc] drill_down: driver '{}' does not serve Retrieval; reporting empty",+ binding.driver_id()+ );+ Vec::new()+ }+ };let n = hits.len();// node_id can embed source scope (e.g. "chat:slack:#eng:0") which may// carry workspace hints — log only the structural prefix.@@ -313,14 +421,35 @@ pub struct FetchLeavesResponse {}/// JSON-RPC handler body for `memory_tree_fetch_leaves`.+///+/// Ids that do not resolve are omitted by the driver, so the response may be+/// shorter than the request and callers must not index by position. A chunk+/// whose source falls outside the scope is omitted the same way, which is what+/// stops naming a chunk id directly from reading around the source gate.pub async fn fetch_leaves_rpc(config: &Config,req: FetchLeavesRequest,) -> Result<RpcOutcome<FetchLeavesResponse>, String> {- // Explicit scope, for the reason given in `cover_window_rpc`.- let hits = fetch_leaves_scoped(config, &req.chunk_ids, current_source_scope())- .await- .map_err(|e| format!("fetch_leaves: {e}"))?;+ // The explicit scope, never `None` — see the module docs. It matters most+ // here: this member takes ids the caller chose.+ let scope = as_bus_scope();++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let hits = match binding.provider().as_retrieval() {+ Some(retrieval) => retrieval+ .retrieve_leaves(&req.chunk_ids, scope.as_ref())+ .await+ .map_err(|e| format!("fetch_leaves: {e}"))?,+ // Read-only, and omitting unresolvable ids is already this member's+ // contract — a driver with no retrieval family resolves none of them.+ None => {+ log::debug!(+ "[memory-tree][rpc] fetch_leaves: driver '{}' does not serve Retrieval; reporting empty",+ binding.driver_id()+ );+ Vec::new()+ }+ };let n = hits.len();Ok(RpcOutcome::single_log(FetchLeavesResponse { hits },@@ -333,22 +462,68 @@ mod tests {//! Unit tests for the Phase 4 retrieval RPC handlers.//!//! Scope: the handler layer specifically — param parsing, default- //! fallbacks, `SourceKind` / `EntityKind` validation, `RpcOutcome`- //! envelope shape, and PII-redacted log formatting. Deeper domain- //! behaviour is already covered by the per-module tests in- //! `source.rs`, `topic.rs`, `drill_down.rs`, etc. — these tests- //! intentionally do NOT re-verify retrieval correctness.+ //! fallbacks, `SourceKind` / `EntityKind` validation, the scope each call+ //! forwards to the contract, `RpcOutcome` envelope shape, and PII-redacted+ //! log formatting. Retrieval correctness is the driver's and is covered by+ //! the engine's own tests; these deliberately do NOT re-verify it.+ //!+ //! All five handlers read through the bound driver, and a unit test cannot+ //! load the compiled module — so every test that gets past parameter+ //! validation binds one. [`bind_without_retrieval`] pins the degrade path;+ //! [`bind_recording`] pins what the handler hands the contract and what it+ //! does with the answer.+ //!+ //! One test binds the real in-process driver instead+ //! ([`install_tinycortex_for_test`]): the source gate has to be proved end+ //! to end, because "the handler passed a scope" and "a restricted profile+ //! cannot read another source" are different claims and only the second one+ //! is the security property. It is the driver the loadable module wraps,+ //! which is as close to production as a test process can get.//!- //! All tests run against a fresh empty workspace. `with_connection`- //! initialises the schema idempotently on first access, so read-only- //! calls return empty responses rather than erroring.+ //! [`install_tinycortex_for_test`]: crate::openhuman::memory::test_support::install_tinycortex_for_test+ use std::sync::{Arc, Mutex};+use super::*;+ use async_trait::async_trait;use chrono::{TimeZone, Utc};use tempfile::TempDir;++ use crate::openhuman::memory::api::capabilities::Capabilities;+ use crate::openhuman::memory::api::error::MemoryError;+ use crate::openhuman::memory::api::health::MemoryHealth;+ use crate::openhuman::memory::api::provider::retrieval::{+ FastRetrieveQuery, MemoryRetrieval, RetrievalNodeKind,+ };+ use crate::openhuman::memory::api::provider::types::{+ ExportPage, ExportRecord, ImportOutcome, SourceScope,+ };+ use crate::openhuman::memory::api::provider::{+ MemoryCore, MemoryPortability, MemoryProvider, MemoryRecall,+ };+ use crate::openhuman::memory::api::recall::OwnedRecallOpts;+ use crate::openhuman::memory::api::types::{+ MemoryCategory, MemoryEntry, MemoryTaint, NamespaceMemoryHit, NamespaceSummary,+ };+ use crate::openhuman::memory::source_scope::with_source_scope;use tinymemory_api::chunks::{chunk_id, Chunk, Metadata, SourceRef};+ use tinymemory_api::null::NullMemoryProvider;use tinymemory_core::store::chunks::store::upsert_chunks;use tinymemory_core::store::content as content_store;+ fn test_config() -> (TempDir, Config) {+ let tmp = TempDir::new().unwrap();+ let mut cfg = Config::default();+ cfg.workspace_dir = tmp.path().to_path_buf();+ // Inert embedder: the driver-backed test below must not reach a real+ // embedding endpoint, and none of these reads rank against a query.+ cfg.memory_tree.embedding_endpoint = None;+ cfg.memory_tree.embedding_model = None;+ cfg.memory_tree.embedding_strict = false;+ (tmp, cfg)+ }++ /// Write chunks the in-process driver can read back — both the row and the+ /// staged content body, since a hit carries the body.fn stage_test_chunks(cfg: &Config, chunks: &[Chunk]) {let content_root = cfg.memory_tree_content_root();std::fs::create_dir_all(&content_root).expect("create content_root for test");@@ -363,18 +538,6 @@ mod tests {.expect("persist staged chunk pointers");}- fn test_config() -> (TempDir, Config) {- let tmp = TempDir::new().unwrap();- let mut cfg = Config::default();- cfg.workspace_dir = tmp.path().to_path_buf();- // Phase 4 (#710): inert embedder keeps tests deterministic and- // avoids any real Ollama call.- cfg.memory_tree.embedding_endpoint = None;- cfg.memory_tree.embedding_model = None;- cfg.memory_tree.embedding_strict = false;- (tmp, cfg)- }-fn sample_chunk(source: &str, seq: u32) -> Chunk {let ts = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();Chunk {@@ -397,14 +560,373 @@ mod tests {}}+ /// Bind a driver with no retrieval family as `cfg`'s memory driver.+ ///+ /// `FixedDiagnostics` is `NullMemoryProvider`-backed and overrides only+ /// `as_maintenance`, so `as_retrieval()` is `None` — the shape of a driver+ /// that serves memory without exposing the engine's retrieval primitives.+ /// Every test that reaches a handler past its parameter validation needs a+ /// binding installed: without one, resolving a driver tries to load the+ /// compiled module, which in a test process can block rather than fail.+ fn bind_without_retrieval(cfg: &Config) {+ crate::openhuman::memory::binding::install_diagnostics_for_test(+ &cfg.workspace_dir,+ &cfg.subsystems.memory,+ Default::default(),+ Default::default(),+ );+ }++ /// Bind `driver` as `cfg`'s memory driver and keep a handle on it.+ fn bind_recording(cfg: &Config, driver: RecordingRetrieval) -> Arc<RecordingRetrieval> {+ let driver = Arc::new(driver);+ crate::openhuman::memory::binding::install_for_test(+ &cfg.workspace_dir,+ &cfg.subsystems.memory,+ Arc::clone(&driver) as Arc<dyn MemoryProvider>,+ );+ driver+ }++ /// One scripted hit, carrying the `tree_kind` every engine-produced hit has.+ fn hit(node_id: &str) -> RetrievalHit {+ let ts = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();+ RetrievalHit {+ node_id: node_id.to_string(),+ node_kind: RetrievalNodeKind::Leaf,+ tree_id: String::new(),+ tree_kind: Some("source".to_string()),+ tree_scope: String::new(),+ level: 0,+ content: format!("content-{node_id}"),+ entities: Vec::new(),+ topics: Vec::new(),+ time_range_start: ts,+ time_range_end: ts,+ score: 1.0,+ child_ids: Vec::new(),+ source_ref: None,+ }+ }++ /// What one contract call was handed.+ #[derive(Default)]+ struct Calls {+ /// The scope argument per member, in call order. Recorded because an+ /// absent scope means UNRESTRICTED on the far side: a handler that+ /// passed `None` where a turn had an allowlist would fail the source+ /// gate open, and the answer would look identical either way.+ scopes: Vec<(String, Option<SourceScope>)>,+ source_queries: Vec<SourceRetrievalQuery>,+ windows: Vec<CoverWindowQuery>,+ }++ /// A driver whose only advertised behaviour is retrieval: it records the+ /// arguments it was handed and answers with scripted hits, or with a+ /// rejection when one is scripted.+ struct RecordingRetrieval {+ inner: NullMemoryProvider,+ hits: Vec<RetrievalHit>,+ invalid: Option<String>,+ calls: Mutex<Calls>,+ }++ impl RecordingRetrieval {+ fn new() -> Self {+ Self {+ inner: NullMemoryProvider::new(),+ hits: Vec::new(),+ invalid: None,+ calls: Mutex::new(Calls::default()),+ }+ }++ fn answering(mut self, hits: Vec<RetrievalHit>) -> Self {+ self.hits = hits;+ self+ }++ /// Reject every retrieval call with `message`, the way the engine+ /// rejects an inverted window.+ fn rejecting(mut self, message: &str) -> Self {+ self.invalid = Some(message.to_string());+ self+ }++ fn record(&self, member: &str, scope: Option<&SourceScope>) {+ self.calls+ .lock()+ .expect("calls lock")+ .scopes+ .push((member.to_string(), scope.cloned()));+ }++ /// The scope `member` was handed. The outer `Option` distinguishes+ /// "never called" from "called with no scope".+ fn scope_for(&self, member: &str) -> Option<Option<SourceScope>> {+ self.calls+ .lock()+ .expect("calls lock")+ .scopes+ .iter()+ .find(|(m, _)| m == member)+ .map(|(_, scope)| scope.clone())+ }++ fn source_query(&self) -> SourceRetrievalQuery {+ self.calls+ .lock()+ .expect("calls lock")+ .source_queries+ .first()+ .cloned()+ .expect("retrieve_source was called")+ }++ fn window(&self) -> CoverWindowQuery {+ self.calls+ .lock()+ .expect("calls lock")+ .windows+ .first()+ .cloned()+ .expect("cover_window was called")+ }++ fn answer(&self) -> Result<Vec<RetrievalHit>, MemoryError> {+ match &self.invalid {+ Some(message) => Err(MemoryError::Invalid(message.clone())),+ None => Ok(self.hits.clone()),+ }+ }++ fn page(&self) -> Result<RetrievalResponse, MemoryError> {+ let hits = self.answer()?;+ let total = hits.len();+ Ok(RetrievalResponse {+ hits,+ total,+ truncated: false,+ })+ }+ }++ #[async_trait]+ impl MemoryRetrieval for RecordingRetrieval {+ async fn cover_window(+ &self,+ window: &CoverWindowQuery,+ scope: Option<&SourceScope>,+ ) -> Result<RetrievalResponse, MemoryError> {+ self.record("cover_window", scope);+ self.calls+ .lock()+ .expect("calls lock")+ .windows+ .push(window.clone());+ self.page()+ }++ async fn retrieve_source(+ &self,+ query: &SourceRetrievalQuery,+ scope: Option<&SourceScope>,+ ) -> Result<RetrievalResponse, MemoryError> {+ self.record("retrieve_source", scope);+ self.calls+ .lock()+ .expect("calls lock")+ .source_queries+ .push(query.clone());+ self.page()+ }++ async fn retrieve_children(+ &self,+ _node_id: &str,+ _max_depth: u32,+ _query: Option<&str>,+ _limit: Option<usize>,+ scope: Option<&SourceScope>,+ ) -> Result<Vec<RetrievalHit>, MemoryError> {+ self.record("retrieve_children", scope);+ self.answer()+ }++ async fn retrieve_leaves(+ &self,+ _chunk_ids: &[String],+ scope: Option<&SourceScope>,+ ) -> Result<Vec<RetrievalHit>, MemoryError> {+ self.record("retrieve_leaves", scope);+ self.answer()+ }++ // The family's remaining members are not reachable from these handlers.+ // They say so rather than returning a plausible empty value that could+ // make a future test pass for the wrong reason.+ async fn fast_retrieve(+ &self,+ _query: &str,+ _options: FastRetrieveQuery,+ _scope: Option<&SourceScope>,+ ) -> Result<RetrievalResponse, MemoryError> {+ unimplemented!("no retrieval RPC reaches fast_retrieve")+ }++ async fn recall_namespace_scored(+ &self,+ _namespace: &str,+ _query: &str,+ _limit: usize,+ _exclude_session_id: Option<&str>,+ ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {+ unimplemented!("no retrieval RPC reaches recall_namespace_scored")+ }++ async fn recall_namespace_recent(+ &self,+ _namespace: &str,+ _limit: usize,+ ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {+ unimplemented!("no retrieval RPC reaches recall_namespace_recent")+ }++ async fn search_entities(+ &self,+ _query: &str,+ _kinds: Option<&[String]>,+ _limit: usize,+ ) -> Result<Vec<EntityMatch>, MemoryError> {+ unimplemented!("search_entities has its own degrade-path tests")+ }+ }++ // The mandatory three are supertraits of `MemoryProvider`, so a stub cannot+ // skip them. Delegated to the null driver: this double exists to observe+ // retrieval, and nothing here stores or recalls.+ #[async_trait]+ impl MemoryCore for RecordingRetrieval {+ async fn store(+ &self,+ namespace: &str,+ key: &str,+ content: &str,+ category: MemoryCategory,+ session_id: Option<&str>,+ taint: MemoryTaint,+ ) -> Result<(), MemoryError> {+ self.inner+ .store(namespace, key, content, category, session_id, taint)+ .await+ }++ async fn get(+ &self,+ namespace: &str,+ key: &str,+ ) -> Result<Option<MemoryEntry>, MemoryError> {+ self.inner.get(namespace, key).await+ }++ async fn forget(&self, namespace: &str, key: &str) -> Result<bool, MemoryError> {+ self.inner.forget(namespace, key).await+ }++ async fn list(+ &self,+ namespace: Option<&str>,+ category: Option<&MemoryCategory>,+ session_id: Option<&str>,+ ) -> Result<Vec<MemoryEntry>, MemoryError> {+ self.inner.list(namespace, category, session_id).await+ }++ async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {+ self.inner.namespaces().await+ }+ }++ #[async_trait]+ impl MemoryRecall for RecordingRetrieval {+ async fn recall(+ &self,+ query: &str,+ limit: usize,+ opts: &OwnedRecallOpts,+ scope: Option<&SourceScope>,+ ) -> Result<Vec<MemoryEntry>, MemoryError> {+ self.inner.recall(query, limit, opts, scope).await+ }+ }++ #[async_trait]+ impl MemoryPortability for RecordingRetrieval {+ async fn export_page(+ &self,+ cursor: Option<&str>,+ limit: usize,+ ) -> Result<ExportPage, MemoryError> {+ self.inner.export_page(cursor, limit).await+ }++ async fn import_records(+ &self,+ records: Vec<ExportRecord>,+ ) -> Result<ImportOutcome, MemoryError> {+ self.inner.import_records(records).await+ }+ }++ #[async_trait]+ impl MemoryProvider for RecordingRetrieval {+ fn driver_id(&self) -> &str {+ "recording-retrieval"+ }++ fn capabilities(&self) -> Capabilities {+ Capabilities::all()+ }++ async fn health(&self) -> MemoryHealth {+ MemoryHealth::Ready+ }++ fn as_retrieval(&self) -> Option<&dyn MemoryRetrieval> {+ Some(self)+ }+ }+// ── query_source_rpc ──────────────────────────────────────────────+ /// An unknown kind is rejected **before** a driver is resolved, which is why+ /// this test installs no binding: a caller mistake must not need a working+ /// driver to be reported, and must not reach one and come back as an empty+ /// store instead.+ #[tokio::test]+ async fn query_source_rpc_rejects_invalid_source_kind() {+ let (_tmp, cfg) = test_config();+ let req = QuerySourceRequest {+ source_id: None,+ source_kind: Some("bogus".into()),+ time_window_days: None,+ query: None,+ limit: None,+ };+ let err = query_source_rpc(&cfg, req).await.unwrap_err();+ assert!(err.contains("unknown source kind: bogus"), "got {err}");+ }++ /// The read degrades rather than fails when the bound driver has no+ /// retrieval family, and still logs the count it served — a silent empty+ /// and a degraded empty look identical downstream otherwise.#[tokio::test]- async fn query_source_rpc_returns_hits_with_no_filters() {+ async fn query_source_rpc_degrades_to_empty_without_the_retrieval_family() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let outcome = query_source_rpc(&cfg, QuerySourceRequest::default()).await- .unwrap();+ .expect("a driver without the retrieval family is not an error");assert!(outcome.value.hits.is_empty());assert_eq!(outcome.value.total, 0);assert_eq!(outcome.logs.len(), 1);@@ -416,8 +938,9 @@ mod tests {}#[tokio::test]- async fn query_source_rpc_parses_valid_source_kind_and_limit() {+ async fn query_source_rpc_redacts_source_id_from_its_log() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = QuerySourceRequest {source_id: Some("slack:#eng".into()),source_kind: Some("chat".into()),@@ -434,25 +957,88 @@ mod tests {assert!(!log.contains("slack:#eng"), "log leaked source_id: {log}");}+ /// The filters reach the contract intact, and so does the turn's source+ /// allowlist — the gate this handler is the only thing applying.#[tokio::test]- async fn query_source_rpc_rejects_invalid_source_kind() {+ async fn query_source_rpc_forwards_its_filters_and_the_turn_scope() {let (_tmp, cfg) = test_config();+ let driver = bind_recording(&cfg, RecordingRetrieval::new());let req = QuerySourceRequest {+ source_id: Some("slack:#eng".into()),+ source_kind: Some("chat".into()),+ time_window_days: Some(7),+ query: Some("phoenix".into()),+ limit: Some(5),+ };+ with_source_scope(Some(vec!["slack:#eng".into()]), async {+ query_source_rpc(&cfg, req).await.unwrap()+ })+ .await;++ let query = driver.source_query();+ assert_eq!(query.source_id.as_deref(), Some("slack:#eng"));+ assert_eq!(query.source_kind, Some(SourceKind::Chat));+ assert_eq!(query.time_window_days, Some(7));+ assert_eq!(query.query.as_deref(), Some("phoenix"));+ assert_eq!(query.limit, 5);++ let scope = driver+ .scope_for("retrieve_source")+ .expect("retrieve_source was called")+ .expect("a restricted turn must not reach the driver as unrestricted");+ assert_eq!(scope.allow, vec!["slack:#eng".to_string()]);+ }++ /// Outside a turn there is genuinely no restriction, and that has to travel+ /// as `None`: an **empty** `SourceScope` denies every source-attributed row,+ /// so mapping "unrestricted" onto one would blank recall out instead.+ #[tokio::test]+ async fn query_source_rpc_leaves_the_scope_absent_when_unrestricted() {+ let (_tmp, cfg) = test_config();+ let driver = bind_recording(&cfg, RecordingRetrieval::new());+ query_source_rpc(&cfg, QuerySourceRequest::default())+ .await+ .unwrap();+ assert_eq!(+ driver.scope_for("retrieve_source"),+ Some(None),+ "no ambient allowlist must reach the driver as None, not Some(empty)"+ );+ }++ /// An absent `limit` stays the engine's default rather than becoming a+ /// request for zero rows.+ #[tokio::test]+ async fn query_source_rpc_maps_an_absent_limit_to_the_engine_sentinel() {+ let (_tmp, cfg) = test_config();+ let driver = bind_recording(&cfg, RecordingRetrieval::new());+ query_source_rpc(&cfg, QuerySourceRequest::default())+ .await+ .unwrap();+ assert_eq!(driver.source_query().limit, 0);+ }++ // ── cover_window_rpc ──────────────────────────────────────────────++ #[tokio::test]+ async fn cover_window_rpc_rejects_invalid_source_kind() {+ let (_tmp, cfg) = test_config();+ let req = CoverWindowRequest {+ since_ms: 0,+ until_ms: 1,source_id: None,source_kind: Some("bogus".into()),- time_window_days: None,- query: None,limit: None,};- let err = query_source_rpc(&cfg, req).await.unwrap_err();+ let err = cover_window_rpc(&cfg, req).await.unwrap_err();+ assert!(err.contains("cover_window:"), "got {err}");assert!(err.contains("unknown source kind: bogus"), "got {err}");}- // ── cover_window_rpc ──────────────────────────────────────────────-#[tokio::test]- async fn cover_window_rpc_returns_empty_with_no_data_and_redacts_log() {+ async fn cover_window_rpc_degrades_to_empty_and_redacts_its_log() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = CoverWindowRequest {since_ms: 0,until_ms: 4_000_000_000_000,@@ -460,7 +1046,9 @@ mod tests {source_kind: Some("chat".into()),limit: None,};- let outcome = cover_window_rpc(&cfg, req).await.unwrap();+ let outcome = cover_window_rpc(&cfg, req)+ .await+ .expect("a driver without the retrieval family is not an error");assert!(outcome.value.hits.is_empty());assert_eq!(outcome.value.total, 0);assert_eq!(outcome.logs.len(), 1);@@ -473,23 +1061,69 @@ mod tests {}#[tokio::test]- async fn cover_window_rpc_rejects_invalid_source_kind() {+ async fn cover_window_rpc_forwards_its_window_and_the_turn_scope() {let (_tmp, cfg) = test_config();+ let driver = bind_recording(&cfg, RecordingRetrieval::new());let req = CoverWindowRequest {- since_ms: 0,- until_ms: 1,+ since_ms: 10,+ until_ms: 20,+ source_id: Some("slack:#eng".into()),+ source_kind: Some("chat".into()),+ limit: Some(3),+ };+ with_source_scope(Some(vec!["slack:#eng".into()]), async {+ cover_window_rpc(&cfg, req).await.unwrap()+ })+ .await;++ let window = driver.window();+ assert_eq!(window.since_ms, 10);+ assert_eq!(window.until_ms, 20);+ assert_eq!(window.source_id.as_deref(), Some("slack:#eng"));+ assert_eq!(window.source_kind, Some(SourceKind::Chat));+ // Forwarded as sent: the driver, not this handler, maps absence onto+ // the engine's 0 sentinel.+ assert_eq!(window.limit, Some(3));++ let scope = driver+ .scope_for("cover_window")+ .expect("cover_window was called")+ .expect("a restricted turn must not reach the driver as unrestricted");+ assert_eq!(scope.allow, vec!["slack:#eng".to_string()]);+ }++ /// An inverted window is now the driver's rejection, and it has to arrive as+ /// an error rather than as an empty page — the two are indistinguishable to+ /// a caller otherwise, and one of them is a bug report.+ #[tokio::test]+ async fn cover_window_rpc_surfaces_a_driver_rejection() {+ let (_tmp, cfg) = test_config();+ bind_recording(+ &cfg,+ RecordingRetrieval::new().rejecting("until_ms 50 is before since_ms 100"),+ );+ let req = CoverWindowRequest {+ since_ms: 100,+ until_ms: 50,source_id: None,- source_kind: Some("bogus".into()),+ source_kind: None,limit: None,};let err = cover_window_rpc(&cfg, req).await.unwrap_err();assert!(err.contains("cover_window:"), "got {err}");- assert!(err.contains("unknown source kind: bogus"), "got {err}");+ assert!(err.contains("until_ms"), "got {err}");+ assert!(err.contains("since_ms"), "got {err}");}+ /// The source gate, end to end through the real driver.+ ///+ /// The tests above prove the handler *passes* a scope; this one proves a+ /// restricted profile cannot read a source it was not granted. It has to+ /// bind the in-process driver rather than the double, because the filtering+ /// is the engine's — and `binding.provider()` is unguarded, so the scope+ /// this handler passes is the only thing standing between the two.#[tokio::test]async fn cover_window_rpc_honors_profile_source_scope() {- use crate::openhuman::memory::source_scope::with_source_scope;let (_tmp, cfg) = test_config();// Two memory-source chunks in different sources, both inside the window.let mut allowed = sample_chunk("slack:#eng", 0);@@ -498,6 +1132,7 @@ mod tests {blocked.metadata.tags = vec!["memory_sources".into(), "chat".into()];upsert_chunks(&cfg, &[allowed.clone(), blocked.clone()]).unwrap();stage_test_chunks(&cfg, &[allowed.clone(), blocked.clone()]);+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);let req = || CoverWindowRequest {since_ms: 0,@@ -507,9 +1142,6 @@ mod tests {limit: None,};- // A restricted profile (allowlist = #eng only) must not surface #secret,- // even though cover_window does its DB work on a spawn_blocking thread- // that does not inherit the source_scope task-local.let resp = with_source_scope(Some(vec!["slack:#eng".into()]), async {cover_window_rpc(&cfg, req()).await})@@ -525,42 +1157,34 @@ mod tests {"disallowed source must be filtered out: {ids:?}");- // With no profile scope active, both sources are visible.+ // With no profile scope active, both sources are visible — which is what+ // makes the assertion above a filter rather than an empty store.let unrestricted = cover_window_rpc(&cfg, req()).await.unwrap();assert_eq!(unrestricted.value.hits.len(), 2);}- #[tokio::test]- async fn cover_window_rpc_rejects_inverted_window() {- let (_tmp, cfg) = test_config();- let req = CoverWindowRequest {- since_ms: 100,- until_ms: 50,- source_id: None,- source_kind: None,- limit: None,- };- let err = cover_window_rpc(&cfg, req).await.unwrap_err();- // The guard names both bounds so callers can see the inversion.- assert!(err.contains("until_ms"), "got {err}");- assert!(err.contains("since_ms"), "got {err}");- }-// ── search_entities_rpc ───────────────────────────────────────────+ /// The search degrades rather than fails when the bound driver has no+ /// retrieval family, and still logs the count it served — a silent empty+ /// and a degraded empty look identical downstream otherwise.#[tokio::test]async fn search_entities_rpc_passes_through_kinds_none() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = SearchEntitiesRequest {query: "alice".into(),kinds: None,limit: None,};- let outcome = search_entities_rpc(&cfg, req).await.unwrap();+ let outcome = search_entities_rpc(&cfg, req)+ .await+ .expect("a driver without the retrieval family is not an error");assert!(outcome.value.matches.is_empty());let log = &outcome.logs[0];assert!(log.contains("query_len=5"), "log: {log}");assert!(log.contains("has_kinds=false"), "log: {log}");+ assert!(log.contains("n=0"), "log: {log}");// PII redaction — the raw query value must NOT appear in the log.assert!(!log.contains("alice"), "log leaked raw query: {log}");}@@ -568,6 +1192,7 @@ mod tests {#[tokio::test]async fn search_entities_rpc_parses_valid_kinds_list() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = SearchEntitiesRequest {query: "x".into(),kinds: Some(vec!["email".into(), "topic".into()]),@@ -582,6 +1207,10 @@ mod tests {);}+ /// An unknown kind is rejected **before** a driver is resolved, which is why+ /// this test installs no binding: a caller mistake must not need a working+ /// driver to be reported, and must not reach one and come back as an empty+ /// index instead.#[tokio::test]async fn search_entities_rpc_rejects_unknown_entity_kind() {let (_tmp, cfg) = test_config();@@ -599,6 +1228,7 @@ mod tests {#[tokio::test]async fn drill_down_rpc_defaults_max_depth_to_one_when_unset() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = DrillDownRequest {node_id: "chat:missing".into(),max_depth: None,@@ -616,6 +1246,7 @@ mod tests {#[tokio::test]async fn drill_down_rpc_logs_node_kind_prefix_for_colon_separated_id() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = DrillDownRequest {node_id: "chat:slack:#eng:0".into(),max_depth: Some(2),@@ -633,6 +1264,7 @@ mod tests {#[tokio::test]async fn drill_down_rpc_logs_unknown_when_node_id_has_no_colon() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = DrillDownRequest {node_id: "rootnode".into(),max_depth: None,@@ -647,43 +1279,87 @@ mod tests {);}+ /// A node id names a node, not a permission: the walk still has to run under+ /// the turn's allowlist.+ #[tokio::test]+ async fn drill_down_rpc_forwards_the_turn_scope() {+ let (_tmp, cfg) = test_config();+ let driver = bind_recording(&cfg, RecordingRetrieval::new());+ let req = DrillDownRequest {+ node_id: "chat:slack:#eng:0".into(),+ max_depth: None,+ query: None,+ limit: None,+ };+ with_source_scope(Some(vec!["slack:#eng".into()]), async {+ drill_down_rpc(&cfg, req).await.unwrap()+ })+ .await;+ let scope = driver+ .scope_for("retrieve_children")+ .expect("retrieve_children was called")+ .expect("a restricted turn must not reach the driver as unrestricted");+ assert_eq!(scope.allow, vec!["slack:#eng".to_string()]);+ }+// ── fetch_leaves_rpc ──────────────────────────────────────────────#[tokio::test]async fn fetch_leaves_rpc_returns_empty_response_for_empty_input() {let (_tmp, cfg) = test_config();+ bind_without_retrieval(&cfg);let req = FetchLeavesRequest { chunk_ids: vec![] };let outcome = fetch_leaves_rpc(&cfg, req).await.unwrap();assert!(outcome.value.hits.is_empty());assert!(outcome.logs[0].contains("n=0"), "log: {}", outcome.logs[0]);}+ /// Naming chunk ids directly must not read around the source gate, so the+ /// scope travels with the ids.#[tokio::test]- async fn fetch_leaves_rpc_hydrates_valid_ids() {+ async fn fetch_leaves_rpc_returns_driver_hits_under_the_turn_scope() {let (_tmp, cfg) = test_config();- let c1 = sample_chunk("slack:#eng", 0);- let c2 = sample_chunk("slack:#eng", 1);- upsert_chunks(&cfg, &[c1.clone(), c2.clone()]).unwrap();- stage_test_chunks(&cfg, &[c1.clone(), c2.clone()]);+ let driver = bind_recording(+ &cfg,+ RecordingRetrieval::new().answering(vec![hit("chunk-a"), hit("chunk-b")]),+ );let req = FetchLeavesRequest {- chunk_ids: vec![c1.id.clone(), c2.id.clone()],+ chunk_ids: vec!["chunk-a".into(), "chunk-b".into(), "ghost".into()],};- let outcome = fetch_leaves_rpc(&cfg, req).await.unwrap();+ let outcome = with_source_scope(Some(vec!["slack:#eng".into()]), async {+ fetch_leaves_rpc(&cfg, req).await.unwrap()+ })+ .await;assert_eq!(outcome.value.hits.len(), 2);assert!(outcome.logs[0].contains("n=2"), "log: {}", outcome.logs[0]);++ let scope = driver+ .scope_for("retrieve_leaves")+ .expect("retrieve_leaves was called")+ .expect("a restricted turn must not reach the driver as unrestricted");+ assert_eq!(scope.allow, vec!["slack:#eng".to_string()]);}+ /// `tree_kind` is `skip_serializing_if = "Option::is_none"`, so a hit that+ /// lost its kind on the way through would take the key out of the response+ /// rather than fail — the silent field loss that held this migration back+ /// while the artifact predated the field.#[tokio::test]- async fn fetch_leaves_rpc_skips_missing_ids_silently() {+ async fn retrieval_hits_keep_tree_kind_on_the_wire() {let (_tmp, cfg) = test_config();- let c1 = sample_chunk("slack:#eng", 0);- upsert_chunks(&cfg, &[c1.clone()]).unwrap();- stage_test_chunks(&cfg, &[c1.clone()]);- let req = FetchLeavesRequest {- chunk_ids: vec![c1.id.clone(), "ghost:nonexistent".into()],- };- let outcome = fetch_leaves_rpc(&cfg, req).await.unwrap();- assert_eq!(outcome.value.hits.len(), 1);- assert!(outcome.logs[0].contains("n=1"), "log: {}", outcome.logs[0]);+ bind_recording(+ &cfg,+ RecordingRetrieval::new().answering(vec![hit("chunk-a")]),+ );+ let outcome = fetch_leaves_rpc(+ &cfg,+ FetchLeavesRequest {+ chunk_ids: vec!["chunk-a".into()],+ },+ )+ .await+ .unwrap();+ let json = serde_json::to_value(&outcome.value).unwrap();+ assert_eq!(json["hits"][0]["tree_kind"], serde_json::json!("source"));}}diff --git a/src/openhuman/memory/tree/tree/rpc.rs b/src/openhuman/memory/tree/tree/rpc.rsindex 47296ae6f1..36391d93e6 100644--- a/src/openhuman/memory/tree/tree/rpc.rs+++ b/src/openhuman/memory/tree/tree/rpc.rs@@ -2,8 +2,10 @@//!//! Public JSON-RPC surface://! - `openhuman.memory_tree_ingest` — one unified ingest. Caller supplies-//! `source_kind` + generic JSON `payload` (adapter-specific). Internally-//! dispatches to chat / email / document canonicalisers.+//! `source_kind` + generic JSON `payload` (adapter-specific). Chat and+//! document are canonicalised into contract items and handed to the bound+//! driver's `Ingest` family; mail still canonicalises in process, for the+//! reasons on [`ingest_rpc`].//! - `openhuman.memory_tree_list_chunks` — listing with filters.//! - `openhuman.memory_tree_get_chunk` — single chunk fetch.@@ -16,11 +18,10 @@ use crate::rpc::RpcOutcome;use tinycortex::memory::ingest::canonicalize::{chat::ChatBatch, document::DocumentInput, email::EmailThread,};-use tinymemory_api::chunks::{Chunk, SourceKind};-use tinymemory_core::ingest_pipeline::{- ingest_chat as do_ingest_chat, ingest_document as do_ingest_document,- ingest_email as do_ingest_email, IngestResult,-};+use tinymemory_api::chunks::{Chunk, DataSource, SourceKind, SourceRef};+use tinymemory_api::provider::types::{IngestItem, IngestOutcome};+use tinymemory_api::types::MemoryTaint;+use tinymemory_core::ingest_pipeline::{ingest_email as do_ingest_email, IngestResult};/// Unified ingest request. The `payload` shape is adapter-specific and is/// validated inside the dispatch based on `source_kind`.@@ -44,6 +45,47 @@ pub struct IngestRequest {pub payload: Value,}+/// Response body of the `memory_tree_ingest` RPC.+///+/// Declared here rather than returned as the engine's own summary type,+/// because this is a wire shape the frontend reads: a body owned by a foreign+/// crate is one an upstream field rename can reshape without anything in this+/// repository failing to compile. Every key and JSON type is what that summary+/// serialised and must stay that way —+/// `the_response_body_serialises_exactly_as_the_engine_summary` is the pin, and+/// it is what the chat and document arms' move onto the driver contract had to+/// keep true. Those two build this body from an `IngestOutcome` now, mail still+/// from the pipeline's summary, and both spell the same six keys.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct IngestResponse {+ /// Logical source id the ingest was scoped to — the one the caller+ /// supplied, echoed back so a batched caller can pair a reply with its+ /// request.+ pub source_id: String,+ /// Units persisted by this call.+ pub chunks_written: usize,+ /// Units produced and not admitted. Dropped units only: a call refused+ /// outright is [`Self::already_ingested`], not a drop of everything.+ pub chunks_dropped: usize,+ /// Ids of the units this call produced. A caller fetches a chunk back by+ /// these, so a write that names none is unusable even when the count is+ /// right.+ pub chunk_ids: Vec<String>,+ /// Follow-up extraction jobs this call scheduled. Read next to+ /// [`Self::chunks_written`] it answers whether the material just handed+ /// over will be picked up at all — rows can land with nothing scheduled to+ /// derive from them, and the write count alone reports that as success.+ pub extract_jobs_enqueued: usize,+ /// True when the call was a no-op because `(source_kind, source_id)` had+ /// been ingested before.+ ///+ /// Distinct from a zero-write result, and the distinction is the point:+ /// only a refusal is a reason to go and clear the source gate. The gate is+ /// keyed on the logical source rather than on the content, so re-sending+ /// *changed* material under a claimed `source_id` also writes nothing.+ pub already_ingested: bool,+}+/// Build the validation error returned when an ingest payload does not match/// the canonicaliser schema for its `source_kind`.///@@ -85,11 +127,226 @@ pub fn is_invalid_ingest_payload_message(message: &str) -> bool {.any(|k| rest.starts_with(&format!("{} payload: ", k.as_str())))}+/// Which `Ingest` member a canonicalised request lands on.+///+/// One type rather than two resolve sites, so the family lookup and its+/// refusal wording exist once: the arms differ only in which member they call.+enum DriverIngest {+ Chat(Vec<IngestItem>),+ Document(IngestItem),+}++/// Hand canonicalised items to the bound driver's `Ingest` family.+///+/// A missing family is **refused**, not degraded. The read handlers below+/// answer empty for one because "this driver stores no chunks" is a true+/// answer to what they were asked; this is a write, and the only empty answer+/// available to it — zero written, zero dropped — is byte-identical to a+/// successful ingest of nothing, so the content would go on the floor while+/// the caller was told it landed.+///+/// Resolved on `provider()`, the same seam [`store_stats`] and [`queue_stats`]+/// use, and deliberately not on `binding.guard()`: the guard's `Ingest`+/// decorator re-stamps `taint`, and `ExternalSync` — what it stamps whenever a+/// source scope is active — is exactly what the driver's own+/// `validate_ingest_item` refuses for the chunk tier, so routing this path+/// through the guard would fail every ingest issued during a sync.+async fn ingest_through_driver(+ config: &Config,+ call: DriverIngest,+) -> Result<IngestOutcome, String> {+ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let Some(ingest) = binding.provider().as_ingest() else {+ return Err(format!(+ "ingest: driver '{}' does not serve Ingest",+ binding.driver_id()+ ));+ };+ match call {+ DriverIngest::Chat(messages) => ingest.ingest_chat(messages).await,+ DriverIngest::Document(item) => ingest.ingest_document(item).await,+ }+ .map_err(|e| format!("ingest: {e}"))+}++/// The [`DataSource`] a chat payload's `platform` string names.+///+/// The verbatim string still crosses as `IngestItem::platform`, which is what+/// the driver rebuilds `ChatBatch::platform` from, so this enum only has to+/// agree with the arm it came from. An unrecognised platform is `Conversation`+/// — the generic chat member — rather than a rejection: this RPC has always+/// taken any platform string, and a new integration must not start failing at+/// the seam because its name is not in an enum here.+fn chat_data_source(platform: &str) -> DataSource {+ match DataSource::parse(platform) {+ Ok(source) if source.kind() == SourceKind::Chat => source,+ _ => DataSource::Conversation,+ }+}++/// As [`chat_data_source`], for a document payload's `provider`.+///+/// `Upload` is the fallback because it is the member that means "handed to the+/// memory layer directly, with no upstream to re-read it from", which is what+/// a document arriving over this RPC is.+fn document_data_source(provider: &str) -> DataSource {+ match DataSource::parse(provider) {+ Ok(source) if source.kind() == SourceKind::Document => source,+ _ => DataSource::Upload,+ }+}++/// Canonicalise a chat batch into the contract's items.+///+/// The attribution trio is what keeps the stored rows identical to the ones+/// the in-process pipeline wrote. The driver rebuilds a `ChatBatch` from the+/// **first** item's `platform` and `channel_label` and from each item's+/// `author`, falling back to values that are not this payload's (the+/// `DataSource` name and the `source_id`), so all three are set on every item+/// rather than only where they differ.+///+/// Messages whose text trims to empty are dropped before the call.+/// `validate_ingest_item` answers `Invalid` for empty content and the driver+/// checks every item before ingesting any, so one attachment-only message+/// would fail the whole batch where the in-process pipeline wrote the rest of+/// it. What the filter costs is that message's bare `## <ts> — <author>`+/// header, which carried no content. Same filter, for the same reason, as+/// `agent::harness::archivist::tree_ingest`.+fn chat_items(source_id: &str, owner: &str, tags: &[String], batch: ChatBatch) -> Vec<IngestItem> {+ let ChatBatch {+ platform,+ channel_label,+ messages,+ } = batch;+ let source = chat_data_source(&platform);+ messages+ .into_iter()+ .filter(|message| !message.text.trim().is_empty())+ .map(|message| IngestItem {+ namespace: None,+ source,+ source_id: source_id.to_string(),+ owner: owner.to_string(),+ source_ref: message.source_ref.map(SourceRef::new),+ content: message.text,+ // The payload carries no MIME. `None` is the honest answer — the+ // driver validates what it is told, and naming a type here would+ // be asserting one the caller never claimed.+ mime: None,+ timestamp: Some(message.timestamp),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ path_scope: None,+ author: Some(message.author),+ channel_label: Some(channel_label.clone()),+ platform: Some(platform.clone()),+ })+ .collect()+}++/// Canonicalise a document payload into the contract's single item.+///+/// `title` does not cross, and the contract's `ingest_document` hard-codes an+/// empty one on the way back in. Nothing is lost by that: the document+/// canonicaliser writes the body alone into the stored markdown and carries+/// the title nowhere else — it reads it only to decide whether the payload was+/// wholly empty, which [`ingest_rpc`] now answers before the call.+fn document_item(source_id: &str, owner: &str, tags: &[String], doc: DocumentInput) -> IngestItem {+ IngestItem {+ namespace: None,+ source: document_data_source(&doc.provider),+ source_id: source_id.to_string(),+ owner: owner.to_string(),+ source_ref: doc.source_ref.map(SourceRef::new),+ content: doc.body,+ mime: None,+ timestamp: Some(doc.modified_at),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ // This handler called `ingest_document_with_scope(.., None)`, so the+ // scope stays unset rather than falling back to `source_id`.+ path_scope: None,+ author: None,+ channel_label: None,+ platform: None,+ }+}++/// Map the driver's outcome onto the wire body.+///+/// `source_id` comes from the request, not from the outcome echoing it back:+/// the caller supplied it, and reading it off the producer is what would let a+/// reply be paired with the wrong request if a producer ever normalised it.+///+/// `written` / `skipped` are the contract's names for the two counts this wire+/// calls `chunks_written` / `chunks_dropped`, and they carry the same two+/// facts: `skipped` counts dropped units only, a refused call being+/// `already_ingested` instead, which is what `chunks_dropped` has always meant+/// here.+fn response_from_outcome(source_id: String, outcome: IngestOutcome) -> IngestResponse {+ IngestResponse {+ source_id,+ chunks_written: outcome.written as usize,+ chunks_dropped: outcome.skipped as usize,+ chunk_ids: outcome.ids,+ extract_jobs_enqueued: outcome.extract_jobs_enqueued as usize,+ already_ingested: outcome.already_ingested,+ }+}++/// Map the in-process pipeline's summary onto the same wire body.+///+/// Kept beside [`response_from_outcome`] rather than folded into it: the two+/// carry the same six facts under different field names, and the mail arm is+/// the only caller left on this one.+fn response_from_engine(source_id: String, result: IngestResult) -> IngestResponse {+ IngestResponse {+ source_id,+ chunks_written: result.chunks_written,+ chunks_dropped: result.chunks_dropped,+ chunk_ids: result.chunk_ids,+ extract_jobs_enqueued: result.extract_jobs_enqueued,+ already_ingested: result.already_ingested,+ }+}+/// Unified ingest RPC handler. Dispatches on `source_kind`.+///+/// Chat and document go to the bound driver's `Ingest` family. At the v1.3.0+/// module pin they could not: the contract's `IngestOutcome` carried neither+/// `already_ingested` nor `extract_jobs_enqueued` (both would have decoded to+/// their serde defaults, reporting every duplicate submission as a plain empty+/// write, forever) and its `skipped` counted duplicate-refusals rather than+/// dropped units, so `chunks_dropped` would have carried a different fact+/// under the same name. v1.4.0 closes all three, which is why the swap is a+/// 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:+///+/// 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.+///+/// Both have to be answered before the mail arm can move: (1) by widening+/// `IngestItem` upstream, (2) by a forwarder in `modules::memory`.pub async fn ingest_rpc(config: &Config,req: IngestRequest,-) -> Result<RpcOutcome<IngestResult>, String> {+) -> Result<RpcOutcome<IngestResponse>, String> {let IngestRequest {source_kind,source_id,@@ -104,23 +361,29 @@ pub async fn ingest_rpc(source_id);- // Phase 2: ingest functions are async. Their scoring stage awaits the- // extractor (cheap for regex, not-cheap for future GLiNER/LLM impls)- // and the DB work is isolated on `spawn_blocking` inside `persist`.- let result = match source_kind {+ let response = match source_kind {SourceKind::Chat => {let batch: ChatBatch = serde_json::from_value(payload).map_err(|e| {let msg = invalid_payload_message(SourceKind::Chat, &e);log::warn!("[memory::rpc] invalid payload for chat");msg})?;- do_ingest_chat(config, &source_id, &owner, tags, batch)- .await- .map_err(|e| {- let msg = format!("ingest: {e}");- log::warn!("[memory::rpc] chat ingestion failed");- msg- })?+ let messages = chat_items(&source_id, &owner, &tags, batch);+ if messages.is_empty() {+ // Answered here rather than handed over. The in-process+ // pipeline returned an empty summary for a batch it could not+ // canonicalise, and "the driver returns zeros for zero items"+ // is a behaviour of the one driver we ship, not something the+ // contract promises of the next one.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Chat(messages))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] chat ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }}SourceKind::Email => {let thread: EmailThread = serde_json::from_value(payload).map_err(|e| {@@ -128,13 +391,14 @@ pub async fn ingest_rpc(log::warn!("[memory::rpc] invalid payload for email");msg})?;- do_ingest_email(config, &source_id, &owner, tags, thread)+ let result = do_ingest_email(config, &source_id, &owner, tags, thread).await.map_err(|e| {let msg = format!("ingest: {e}");log::warn!("[memory::rpc] email ingestion failed");msg- })?+ })?;+ response_from_engine(source_id.clone(), result)}SourceKind::Document => {let doc: DocumentInput = serde_json::from_value(payload).map_err(|e| {@@ -142,18 +406,31 @@ pub async fn ingest_rpc(log::warn!("[memory::rpc] invalid payload for document");msg})?;- do_ingest_document(config, &source_id, &owner, tags, doc)- .await- .map_err(|e| {- let msg = format!("ingest: {e}");- log::warn!("[memory::rpc] document ingestion failed");- msg- })?+ let item = document_item(&source_id, &owner, &tags, doc);+ if item.content.trim().is_empty() {+ // The chat arm's filter, on this arm's single item. Empty+ // content is `Invalid` at the driver, so a body-less document+ // would arrive as a failed call; the in-process pipeline+ // instead canonicalised it to a lone whitespace chunk. Neither+ // is worth keeping — "nothing to ingest" is. What it gives up+ // is that a body-less payload under an already-claimed+ // `source_id` used to answer `already_ingested`, and there is+ // nothing behind that gate to go and clear when the body was+ // empty.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Document(item))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] document ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }}};Ok(RpcOutcome::single_log(- result,+ response,format!("memory_tree: ingest kind={} source_id={source_id}",source_kind.as_str()@@ -1270,6 +1547,43 @@ mod tests {}}+ /// The ingest response is this crate's declaration of a wire the frontend+ /// reads, so nothing upstream keeps its keys honest any more.+ ///+ /// Asserted against the engine summary it was lifted from rather than+ /// against a hand-written key list, because that is the shape callers are+ /// already parsing: a key renamed, dropped, or retyped on either side fails+ /// here instead of silently reaching a reader. It stayed the right assertion+ /// across the move onto the driver contract — the chat and document arms+ /// build the body from an `IngestOutcome` now, and this is what says the+ /// wire did not move with them.+ #[test]+ fn the_response_body_serialises_exactly_as_the_engine_summary() {+ let engine = IngestResult {+ source_id: "doc-launch".into(),+ chunks_written: 3,+ chunks_dropped: 1,+ chunk_ids: vec!["chunk-a".into(), "chunk-b".into(), "chunk-c".into()],+ extract_jobs_enqueued: 2,+ already_ingested: true,+ };+ let ours = IngestResponse {+ source_id: engine.source_id.clone(),+ chunks_written: engine.chunks_written,+ chunks_dropped: engine.chunks_dropped,+ chunk_ids: engine.chunk_ids.clone(),+ extract_jobs_enqueued: engine.extract_jobs_enqueued,+ already_ingested: engine.already_ingested,+ };++ assert_eq!(+ serde_json::to_value(&engine).unwrap(),+ serde_json::to_value(&ours).unwrap(),+ "the ingest response must serialise key-for-key as the summary it \+ replaced — the frontend reads these names"+ );+ }+fn sample_document(title: &str, body: &str) -> DocumentInput {DocumentInput {provider: "notion".into(),@@ -1282,20 +1596,15 @@ mod tests {/// Ingest reports what it wrote.///- /// This used to read the chunks back through `list_chunks_rpc` /- /// `get_chunk_rpc` and assert the round trip. It cannot any more, and the- /// reason is the seam rather than the assertion: ingest is still the- /// in-process pipeline writing under `cfg.workspace_dir`, while the two- /// read handlers now ask the bound driver — which a unit test binds to the- /// shared test workspace, not to this tempdir. Asserting across the two- /// would be asserting that the two stores happen to coincide, which is- /// true in the product and deliberately not true here.- ///- /// The read side's own contract is pinned by- /// [`list_and_get_report_empty_when_the_driver_has_no_chunk_tier`].+ /// Bound to the in-process TinyCortex driver rather than left to resolve on+ /// its own: the handler asks the driver for the `Ingest` family now, and+ /// what a bare test workspace binds is the null driver, which serves none.+ /// This is the engine the loadable module wraps, so the counts asserted+ /// below are the ones production gets over the bus.#[tokio::test]async fn ingest_document_reports_the_chunks_it_wrote() {let (_tmp, cfg) = test_config();+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);let outcome = ingest_rpc(&cfg,IngestRequest {@@ -1351,9 +1660,14 @@ mod tests {assert!(listed.logs[0].contains("n=0"), "log: {}", listed.logs[0]);}+ /// The source gate is the driver's, and it survives the move onto the+ /// contract: `IngestOutcome::already_ingested` is the field the v1.3.0 pin+ /// did not have, and reporting a refused call as a plain empty write is+ /// exactly what this test would have started passing over.#[tokio::test]async fn ingest_document_is_idempotent_for_duplicate_source_id() {let (_tmp, cfg) = test_config();+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);let req = IngestRequest {source_kind: SourceKind::Document,source_id: "doc-dup".into(),@@ -1368,9 +1682,8 @@ mod tests {assert!(!first.already_ingested);// `already_ingested` with a zero write count is the whole claim:// documents are append-only, so a repeat submission must be recognised- // rather than duplicated. Re-listing the store to confirm the count- // would now query the driver instead of the pipeline that wrote —- // see `ingest_document_reports_the_chunks_it_wrote`.+ // rather than duplicated — and told apart from a write that produced+ // nothing, which is the same two numbers with a different cause.assert_eq!(second.chunks_written, 0);assert!(second.already_ingested);assert_eq!(second.source_id, first.source_id);@@ -1381,6 +1694,7 @@ mod tests {#[tokio::test]async fn ingest_chat_accepts_rfc3339_timestamps() {let (_tmp, cfg) = test_config();+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);let outcome = ingest_rpc(&cfg,IngestRequest {@@ -1413,6 +1727,11 @@ mod tests {/// Regression #3568 / CORE-2K: email payloads with RFC-3339 timestamps must/// be accepted.+ ///+ /// No driver is bound: the mail arm is the one still on the in-process+ /// pipeline, for the two reasons on [`ingest_rpc`]. When it moves, this+ /// test needs `install_tinycortex_for_test` like its siblings — and the+ /// header lines it does not assert are what has to be checked first.#[tokio::test]async fn ingest_email_accepts_rfc3339_timestamps() {let (_tmp, cfg) = test_config();@@ -1443,6 +1762,92 @@ mod tests {assert!(!outcome.value.chunk_ids.is_empty());}+ /// One empty message must not fail the batch around it.+ ///+ /// `validate_ingest_item` answers `Invalid` for content that trims to+ /// empty, and the driver validates every item before ingesting any — so an+ /// attachment-only message, which reaches this handler as a message with no+ /// text, would turn a batch that has real content in it into a failed call.+ /// The in-process pipeline wrote the rest of the batch and rendered that+ /// message as a bare header; the filter keeps the first half of that and+ /// gives up only the header.+ #[tokio::test]+ async fn an_empty_chat_message_does_not_fail_the_batch_around_it() {+ let (_tmp, cfg) = test_config();+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);+ let outcome = ingest_rpc(+ &cfg,+ IngestRequest {+ source_kind: SourceKind::Chat,+ source_id: "slack:#attachment-only".into(),+ owner: "alice".into(),+ tags: vec![],+ payload: json!({+ "platform": "slack",+ "channel_label": "#eng",+ "messages": [+ {+ "author": "alice",+ "timestamp": "2026-05-17T19:30:00Z",+ "text": " "+ },+ {+ "author": "bob",+ "timestamp": "2026-05-17T19:31:00Z",+ "text": "here is the plan"+ }+ ]+ }),+ },+ )+ .await+ .expect("an empty message is dropped, not a batch failure");+ assert!(+ !outcome.value.chunk_ids.is_empty(),+ "the surviving message must still be written"+ );+ }++ /// An ingest is a write, so a driver without the family is refused rather+ /// than answered with zeros.+ ///+ /// The counts have no way to say "nothing was handed over": zero written+ /// and zero dropped is what a successful ingest of nothing looks like too,+ /// so degrading here would report content dropped on the floor as a+ /// success. `FixedDiagnostics` advertises `Capabilities::all()` while+ /// serving no `Ingest` accessor, which also pins that the refusal keys off+ /// the accessor and not off the advertised set.+ #[tokio::test]+ async fn ingest_refuses_a_driver_that_does_not_serve_the_ingest_family() {+ let (_tmp, cfg) = test_config();+ bind_diagnostics(&cfg, Default::default(), Default::default());++ let err = ingest_rpc(+ &cfg,+ IngestRequest {+ source_kind: SourceKind::Chat,+ source_id: "slack:#no-ingest".into(),+ owner: "alice".into(),+ tags: vec![],+ payload: json!({+ "platform": "slack",+ "channel_label": "#eng",+ "messages": [{ "author": "alice", "text": "anything at all" }],+ }),+ },+ )+ .await+ .unwrap_err();+ assert!(+ err.contains("does not serve Ingest"),+ "the refusal must name the missing family: {err}"+ );+ assert!(+ err.contains("fixed-diagnostics"),+ "the refusal must name the driver that refused: {err}"+ );+ }+#[tokio::test]async fn ingest_rpc_rejects_invalid_document_payload() {let (_tmp, cfg) = test_config();diff --git a/src/openhuman/modules/memory.rs b/src/openhuman/modules/memory.rsindex 7e6b52b195..b71a368073 100644--- a/src/openhuman/modules/memory.rs+++ b/src/openhuman/modules/memory.rs@@ -48,7 +48,7 @@ use tinymemory_api::capabilities::{Capabilities, Capability};/// Checked against the registry pin by `the_capability_list_matches_the_pinned_release`,/// so bumping the pin without re-reading the list is a red test rather than a/// silent over-claim.-pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.3.0";+pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.4.0";/// The capability families the **pinned artifact** actually serves.///diff --git a/src/openhuman/modules/registry.rs b/src/openhuman/modules/registry.rsindex 1d5fd4525b..b3e63b261f 100644--- a/src/openhuman/modules/registry.rs+++ b/src/openhuman/modules/registry.rs@@ -202,63 +202,63 @@ const TINYMEMORY: ModuleRecord = ModuleRecord {description: "Local memory engine: store, ranked recall, and portable export",bus_name: "ai.tinyhumans.tinymemory.Memory",object_path: "/ai/tinyhumans/tinymemory/Memory",- version: "1.3.0",- release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.3.0",+ version: "1.4.0",+ release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.4.0",assets: &[PlatformAsset {host_key: "ubuntu-24.04-x86_64",- archive: "tinymemory-module-1.3.0-ubuntu-24.04-x86_64.tar.gz",- sha256: "87e2557dbd09f8fe67ea8a91a1fb2d9d014b9e52e6f26ef7267892f8b570bf03",+ archive: "tinymemory-module-1.4.0-ubuntu-24.04-x86_64.tar.gz",+ sha256: "3cd26ffd585c4ea47e950454208ffbb8028b8c9f288a6d37002b6449a2caea25",},PlatformAsset {host_key: "ubuntu-24.04-arm64",- archive: "tinymemory-module-1.3.0-ubuntu-24.04-arm64.tar.gz",- sha256: "552975f1a3267a3129efcdf706e2c970312fe22b597a774e114578e7337bd371",+ archive: "tinymemory-module-1.4.0-ubuntu-24.04-arm64.tar.gz",+ sha256: "3ab2b78457f46c75e12cba9591a63aec53b9c654b10d28d47af865a03cd79894",},PlatformAsset {host_key: "ubuntu-22.04-x86_64",- archive: "tinymemory-module-1.3.0-ubuntu-22.04-x86_64.tar.gz",- sha256: "3e30368c10d24153128f5a51130ac0b322b5c0e1fe5e8257a98d6e06d4eb8cff",+ archive: "tinymemory-module-1.4.0-ubuntu-22.04-x86_64.tar.gz",+ sha256: "d722d36e9fc35ef4ddbbb96499949a6a608f044e924d023f719deb9aa3f5875d",},PlatformAsset {host_key: "ubuntu-22.04-arm64",- archive: "tinymemory-module-1.3.0-ubuntu-22.04-arm64.tar.gz",- sha256: "480c407df5d469d96cb6f007c660a27c6b4e1e2473c2c16ac72da2c46139d06d",+ archive: "tinymemory-module-1.4.0-ubuntu-22.04-arm64.tar.gz",+ sha256: "25a39d8d1b866e3693d0eef6372a5eab74497da8389a04407234139b83b01373",},PlatformAsset {host_key: "macos-26-arm64",- archive: "tinymemory-module-1.3.0-macos-26-arm64.tar.gz",- sha256: "34b2478c299a8ad45963a6495ead171a66ff1cca2da47d52e1cd6f400fa42d7c",+ archive: "tinymemory-module-1.4.0-macos-26-arm64.tar.gz",+ sha256: "26ecc5f8f066d2ef3ce7a88c9373683dfd8c2b79b60d5fe32c07bca793c2be9d",},PlatformAsset {host_key: "macos-26-x86_64",- archive: "tinymemory-module-1.3.0-macos-26-x86_64.tar.gz",- sha256: "e468c0625f5109f7c6dcff2c146cc211d95505fdfef9f15b8a3c39e894aaafff",+ archive: "tinymemory-module-1.4.0-macos-26-x86_64.tar.gz",+ sha256: "1c82e091618f0b390c9d772390b86d8ee597d477ace279133b7fd5ed2f50f1cd",},PlatformAsset {host_key: "macos-15-arm64",- archive: "tinymemory-module-1.3.0-macos-15-arm64.tar.gz",- sha256: "8b1c780e9690c2401952deab8885b9ad941034cea45988ddc6eddaae150bd53b",+ archive: "tinymemory-module-1.4.0-macos-15-arm64.tar.gz",+ sha256: "1ba808517f9c1e2d438dabacb214ea40112d2f659ae1bd751664fd1103309e3d",},PlatformAsset {host_key: "macos-15-x86_64",- archive: "tinymemory-module-1.3.0-macos-15-x86_64.tar.gz",- sha256: "01882fafa650da131db51cd740c50e38c7c9731189579ef7b7f31c1eee84ca90",+ archive: "tinymemory-module-1.4.0-macos-15-x86_64.tar.gz",+ sha256: "c942505e7ee7d4311a9a81826ae66512aecfab3b3083c806421cb35c775bfe22",},PlatformAsset {host_key: "windows-2025-x86_64",- archive: "tinymemory-module-1.3.0-windows-2025-x86_64.zip",- sha256: "e7fcc65d59d3d9445d15bc92607b449a34a72f5e07d1254c73e72c218dfc263a",+ archive: "tinymemory-module-1.4.0-windows-2025-x86_64.zip",+ sha256: "69ad29b061085da95939237ada6e323f5b04c80837a637ad0a55484ec7542226",},PlatformAsset {host_key: "windows-2022-x86_64",- archive: "tinymemory-module-1.3.0-windows-2022-x86_64.zip",- sha256: "431899ac20cf1f0aaa5ed0e9ac9f232ed04e9d739b5275c941dbd0dc95aabaae",+ archive: "tinymemory-module-1.4.0-windows-2022-x86_64.zip",+ sha256: "31ff3dfc7b1ea0b4749beec49edf6d44b6cc8e3a49d2c20dde6306bce924f91b",},PlatformAsset {host_key: "windows-11-arm64",- archive: "tinymemory-module-1.3.0-windows-11-arm64.zip",- sha256: "2377a06ff1d6026fca303999d74a657ce37602b59960d9ae05658fff5286bb23",+ archive: "tinymemory-module-1.4.0-windows-11-arm64.zip",+ sha256: "00c111b3ad2e42b092f21b44a7d98764d6af8c48bd03995cc751af079bf7ed8a",},],// Eager, unlike the two codecs above. A codec that is never asked for shoulddiff --git a/vendor/tinymemory b/vendor/tinymemoryindex 2dfb6e8cbf..346fe4eba1 160000--- a/vendor/tinymemory+++ b/vendor/tinymemory@@ -1 +1 @@-Subproject commit 2dfb6e8cbfebfb872381f89509f7feb97282ada3+Subproject commit 346fe4eba15bdef29007cbfc5eef5b4a25a143b1