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
Route four more handlers through the memory contract
Shanub9693d5daed2
diff --git a/src/openhuman/config/migration_helpers/core.rs b/src/openhuman/config/migration_helpers/core.rsindex c93860d30e..632195a21d 100644--- a/src/openhuman/config/migration_helpers/core.rs+++ b/src/openhuman/config/migration_helpers/core.rs@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};use std::collections::HashSet;use std::fs;use std::path::{Path, PathBuf};-use tinymemory_core::store as memory_store;+use std::sync::Arc;#[derive(Debug, Clone)]struct SourceEntry {@@ -120,28 +120,30 @@ pub async fn migrate_openclaw_memory(/// The memory the import writes into.///-/// **Still the engine's own migration constructor, and #5560 could not change-/// that.** The contract's only door for this shape is `MemoryCore::store`,-/// reached through `MemoryGuard` like every other write in the tree — and the-/// guard applies `MemoryHooksConfig::capture_max_chars`, which defaults to-/// **500**, to every `store` body (`guard::mandatory`, step 6). An OpenClaw /-/// Hermes `MEMORY.md` entry is routinely longer than that, so routing the-/// import through the guard would silently truncate the user's own imported-/// memories: data loss on a migration path, which is worse than the second-/// engine handle this keeps.+/// The bound driver, through [`DriverMemory`] — the same store the engine+/// constructor this replaced opened. That equivalence is checked rather than+/// assumed: `create_memory_for_migration` bottoms out in+/// `create_memory_full(..., workspace_dir, "memory")`, and+/// `binding::for_workspace` resolves `for_subtree(workspace_dir, "memory")`.+/// Same workspace, same subtree.///-/// The other two doors do not fit either. `MemoryDocuments::put_document` does-/// not trim, but it writes namespace *documents* rather than memory entries, so-/// the `get`/rename dedupe above would stop seeing what it wrote.-/// `MemoryPortability::import_records` is the shape a migration wants, but-/// `ExportRecord::payload` is explicitly "the exporting driver's own shape" —-/// synthesising one host-side means encoding driver-private structure here.+/// # Why the capture budget does not bite here///-/// What unblocks this is a capture budget that distinguishes an *import* from-/// an auto-capture, or a `MemoryCore::store` variant that opts out of the-/// budget. Both are upstream asks, not host changes.-fn target_memory_backend(config: &Config) -> Result<Box<dyn Memory>> {- memory_store::create_memory_for_migration(&config.memory, &config.workspace_dir)+/// This note used to say the contract had no door for an import, because+/// `MemoryCore::store` is reached through `MemoryGuard`, which applies+/// `MemoryHooksConfig::capture_max_chars` to every body — and an imported+/// `MEMORY.md` entry is routinely longer than that, so routing an import+/// through the guard would silently truncate the user's own memories.+///+/// The budget is real, and it is enforced host-side in+/// `memory::guard::policy`. What the note missed is that `DriverMemory` does+/// not go through the guard at all: it wraps `binding.provider()`, which is the+/// **unguarded** driver — the binding keeps the guarded one separately behind+/// `binding.guard()`. So an import writes full bodies here exactly as the+/// engine constructor did, and no policy has to be special-cased to allow it.+fn target_memory_backend(config: &Config) -> Result<Arc<dyn Memory>> {+ crate::openhuman::agent::experience::ops::DriverMemory::for_config(config)+ .map_err(|e| anyhow::anyhow!("bind memory for migration import: {e}"))}fn collect_source_entries(diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rsindex a4d79ecdcf..06591374bd 100644--- a/src/openhuman/memory/direct_engine_refs_tests.rs+++ b/src/openhuman/memory/direct_engine_refs_tests.rs@@ -314,11 +314,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[Verdict::NeedsWiderSeam,"holds or boots the in-process engine handle (store::UnifiedMemory); driver construction belongs to memory::binding and the seam has no door onto the live client",),- (- "src/openhuman/config/migration_helpers/core.rs",- Verdict::NeedsWiderSeam,- "holds or boots the in-process engine handle (store); driver construction belongs to memory::binding and the seam has no door onto the live client",- ),("src/openhuman/flows/memory_tools.rs",Verdict::NeedsWiderSeam,@@ -329,26 +324,11 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[Verdict::NeedsWiderSeam,"holds or boots the in-process engine handle (store::MemoryClient); driver construction belongs to memory::binding and the seam has no door onto the live client",),- (- "src/openhuman/memory/read_rpc/admin.rs",- Verdict::NeedsWiderSeam,- "one call left: flush_source_tree wants a live source-tree handle (tree_source::get_or_create_source_tree) to feed the host's TreeFactory label strategy and force_flush_tree, and MemoryTree is namespace-addressed (append/query_source/drill_down/seal/cascade/summary_forest/recent_leaves) with no door onto a tree object. wipe_all, clear_composio_sync_state and delete_source have left for purge_all, kv_list+kv_delete and forget_matching(Source)",- ),("src/openhuman/memory/read_rpc/mod.rs",Verdict::NeedsWiderSeam,"reaches engine storage below the contract (store::chunks::store::with_connection, store::chunks::types::SourceKind); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",),- (- "src/openhuman/memory/sync/sync_status/rpc.rs",- Verdict::NeedsWiderSeam,- "engine internals (tinycortex::memory_config_from); tinycortex-shaped, so no engine-neutral family can express it",- ),- (- "src/openhuman/memory/tree/tree/rpc.rs",- Verdict::NeedsWiderSeam,- "ingest_pipeline and the chunk store's list/read helpers have no capability family; the queue reads left for the Maintenance members in tinymemory#85/#86/#89",- ),// ── Re-export shims: `pub use tinymemory_core::<domain>::*;` ────────────//// These are the historical-path aliases `memory/mod.rs` documents. Theydiff --git a/src/openhuman/memory/guard/families.rs b/src/openhuman/memory/guard/families.rsindex d6c1770188..2394ad8dc0 100644--- a/src/openhuman/memory/guard/families.rs+++ b/src/openhuman/memory/guard/families.rs@@ -518,6 +518,21 @@ impl MemoryTree for GuardedTree {.await}+ /// Sealing one source's tree is a write, and it names the scope it acts on+ /// — so unlike the reads above it is admitted against that scope rather+ /// than `NO_NAMESPACE`. `carries_content: false`: the caller supplies a+ /// scope label, never prose, and the seals it fires write content the+ /// driver already holds.+ async fn flush_source_tree(&self, source_scope: &str) -> Result<u64, MemoryError> {+ self.policy.admit_write(+ Capability::Tree,+ "tree.flush_source_tree",+ source_scope,+ false,+ )?;+ self.family()?.flush_source_tree(source_scope).await+ }+/// Leaves are chunks, so this is the same disclosure as/// [`Self::query_source`] with a different ordering, and takes the same/// intersection.diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rsindex b880c4b98f..6a5c22db6e 100644--- a/src/openhuman/memory/read_rpc/admin.rs+++ b/src/openhuman/memory/read_rpc/admin.rs@@ -280,61 +280,53 @@ pub async fn reset_tree_rpc(config: &Config) -> Result<RpcOutcome<ResetTreeRespo/// and until they land migrating here would be a regression — read on before/// changing it.**///-/// `get_or_create_source_tree` hands back a live `Tree` **object**, and both-/// things this handler does next need the object rather than a namespace: the-/// host's `TreeFactory::from_tree(&tree).label_strategy(&cfg)` picks the-/// labelling policy from the tree's own kind/scope, and `force_flush_tree`-/// takes `&tree.id`.+/// Served by the bound driver's `MemoryTree::flush_source_tree` (#5560).///-/// This note used to say `MemoryTree` could not express that — namespace-addressed-/// end to end, no member returning a tree handle — and asked upstream for-/// "flush the tree for this source scope, using the host's label strategy".-/// **tinymemory v1.7.0 shipped exactly that**:-/// `MemoryTree::flush_source_tree(&self, source_scope) -> Result<u64, MemoryError>`,-/// answering the seal count rather than a tree, with the labelling decision made-/// driver-side (which is where it comes from anyway). The module serves it and-/// `TinycortexProvider` implements it, so the driver behind the bus is ready.+/// This used to hold a live `Tree` object from the engine's+/// `tree_source::get_or_create_source_tree`, because both things it did next+/// wanted the object rather than a namespace: `TreeFactory::from_tree(&tree)+/// .label_strategy(&cfg)` picked the labelling policy from the tree's own+/// kind and scope, and `force_flush_tree` took `&tree.id`.///-/// What is **not** ready is this host's two forwarders onto that member:-/// neither `modules::memory`'s `ModuleMemoryProvider` (`impl MemoryTree`) nor-/// `memory::guard::families`' `GuardedTree` overrides it, so both inherit the-/// trait default — `Err(Unsupported(Tree))`. Calling it today would turn a-/// working flush into a runtime `Unsupported`, which is strictly worse than-/// the direct call: the failure moves from compile time to run time, and this-/// handler's caller has no fallback. That is the same trap-/// `direct_engine_refs_tests`' module docs warn about for a method the pinned-/// artifact does not serve; here the artifact serves it and the host does not-/// ask.+/// tinymemory v1.7.0 replaced that with a member answering the seal count and+/// making the labelling decision driver-side — which is where it came from+/// anyway — so no tree handle crosses the seam. Sealing and cascading are one+/// call there rather than two here, which also closes the window the old+/// two-step left open: a tree sealed but not yet cascaded reads as an empty+/// tree to every structural query.///-/// So the remaining work is host-side and sits in two files this handler does-/// not own. Once `ModuleMemoryProvider` and `GuardedTree` both forward-/// `flush_source_tree`, this whole function collapses into the shape-/// [`flush_now_rpc`] already has below: resolve the binding, take `as_tree()`,-/// degrade by naming the driver when the family is absent, and map the returned-/// count into `seals_fired`. Two behaviours have to survive that rewrite — the-/// `ACTIVE` re-entrancy latch, and the fact that an unknown scope is a-/// zero-count success rather than an error.-///-/// (`tinymemory_core::tree_source` itself is genuinely engine-owned — it wraps-/// `tree::tree::registry::get_or_create_tree` and writes the `_source.md`-/// mirror as a side effect — so there is no tinycortex twin to repoint at in-/// the meantime.)+/// Two behaviours survive the rewrite deliberately. The `ACTIVE` re-entrancy+/// latch is still host-side, because it guards *this* handler against a second+/// concurrent call rather than guarding the store. And a scope with nothing+/// buffered is still a zero-count success rather than an error — now by the+/// contract's own rule rather than by this function's convention.pub async fn flush_source_tree_rpc(config: &Config,source_scope: &str,) -> Result<RpcOutcome<FlushSourceTreeResponse>, String> {- use tinymemory_core::tree_source::get_or_create_source_tree;-- use crate::openhuman::memory::tree::tree::flush::force_flush_tree;- use crate::openhuman::memory::tree::tree::TreeFactory;use std::collections::HashSet;use std::sync::Mutex;static ACTIVE: std::sync::LazyLock<Mutex<HashSet<String>>> =std::sync::LazyLock::new(|| Mutex::new(HashSet::new()));- let scope = source_scope.to_string();+ /// Releases the re-entrancy latch on every exit, including the error ones.+ ///+ /// The hand-rolled version this replaces removed the scope only after a+ /// successful flush, so a driver error latched that scope out for the rest+ /// of the process — the retry a caller would naturally make came back+ /// "already running" forever. Dropping it in a guard is the fix.+ struct Latch(String);+ impl Drop for Latch {+ fn drop(&mut self) {+ ACTIVE+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .remove(&self.0);+ }+ }+ let scope = source_scope.to_string();{let mut active = ACTIVE.lock().unwrap_or_else(|e| e.into_inner());if !active.insert(scope.clone()) {@@ -347,43 +339,32 @@ pub async fn flush_source_tree_rpc());}}+ let _latch = Latch(scope.clone());- let cfg = config.clone();- let scope_for_task = scope.clone();- let result = tokio::task::spawn_blocking(move || -> Result<FlushSourceTreeResponse> {- let tree = get_or_create_source_tree(&cfg, &scope_for_task)- .context("get_or_create_source_tree")?;- let _strategy = TreeFactory::from_tree(&tree).label_strategy(&cfg);- Ok(FlushSourceTreeResponse {- tree_scope: scope_for_task,- seals_fired: 0,- })- })- .await- .map_err(|e| format!("flush_source_tree join error: {e}"))?;-- let _tree_info = result.map_err(|e| format!("flush_source_tree: {e:#}"))?;-- let cfg2 = config.clone();- let scope2 = scope.clone();- let resp = tokio::spawn(async move {- let tree = get_or_create_source_tree(&cfg2, &scope2)?;- let strategy = TreeFactory::from_tree(&tree).label_strategy(&cfg2);- let sealed = force_flush_tree(&cfg2, &tree.id, Some(chrono::Utc::now()), &strategy).await?;- Ok::<_, anyhow::Error>(FlushSourceTreeResponse {- tree_scope: scope2,- seals_fired: sealed.len() as u32,- })- })- .await- .map_err(|e| format!("flush_source_tree join error: {e}"))?- .map_err(|e| format!("flush_source_tree: {e:#}"))?;+ // Asked of the driver (`Tree::flush_source_tree`). The seal and the cascade+ // are one call there rather than two here, which closes the window the old+ // two-step left: a tree sealed but not cascaded reads as empty to every+ // structural query. No `spawn_blocking` either — the driver owns whether+ // its own reads block.+ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let Some(tree) = binding.provider().as_tree() else {+ return Err(format!(+ "flush_source_tree: driver '{}' does not serve Tree",+ binding.driver_id()+ ));+ };- {- let mut active = ACTIVE.lock().unwrap_or_else(|e| e.into_inner());- active.remove(&scope);- }+ // A scope with nothing buffered is `Ok(0)` by the contract, not an error,+ // which is the behaviour this handler already had for an unknown scope.+ let seals_fired = tree+ .flush_source_tree(&scope)+ .await+ .map_err(|e| format!("flush_source_tree: {e}"))?;+ let resp = FlushSourceTreeResponse {+ tree_scope: scope,+ seals_fired: u32::try_from(seals_fired).unwrap_or(u32::MAX),+ };let log = format!("memory_tree::read: flush_source_tree scope={} seals={}",resp.tree_scope, resp.seals_fireddiff --git a/src/openhuman/memory/sync/sync_status/rpc.rs b/src/openhuman/memory/sync/sync_status/rpc.rsindex da72b8a1ba..db84a61351 100644--- a/src/openhuman/memory/sync/sync_status/rpc.rs+++ b/src/openhuman/memory/sync/sync_status/rpc.rs@@ -1,29 +1,78 @@-//! OpenHuman RPC shell for tinycortex synchronization status.+//! OpenHuman RPC shell for memory synchronization status.use crate::openhuman::config::Config;use crate::rpc::RpcOutcome;-use tinycortex::memory::sync::StatusListResponse;+use tinycortex::memory::sync::{FreshnessLabel, MemorySyncStatus, StatusListResponse};+use tinymemory_api::provider::sync::{SourceSyncStatus, SyncFreshness};++/// Carry one status across as the wire type this RPC has always answered.+///+/// Field-for-field, and that is checkable rather than hopeful: the contract's+/// `SourceSyncStatus` was modelled on the driver's own row, so `provider`,+/// `chunks_synced`, `chunks_pending`, `batch_total`, `batch_processed` and+/// `last_chunk_at_ms` are the same names carrying the same values, and both+/// freshness enums are the same three variants under the same+/// `rename_all = "snake_case"`. The response body is therefore byte-identical+/// to what the engine call produced — `response_keeps_top_level_statuses_array`+/// still holds.+fn into_wire(status: SourceSyncStatus) -> MemorySyncStatus {+ let SourceSyncStatus {+ provider,+ chunks_synced,+ chunks_pending,+ batch_total,+ batch_processed,+ last_chunk_at_ms,+ freshness,+ } = status;+ MemorySyncStatus {+ provider,+ chunks_synced,+ chunks_pending,+ batch_total,+ batch_processed,+ last_chunk_at_ms,+ freshness: match freshness {+ SyncFreshness::Active => FreshnessLabel::Active,+ SyncFreshness::Recent => FreshnessLabel::Recent,+ SyncFreshness::Idle => FreshnessLabel::Idle,+ },+ }+}pub async fn status_list_rpc(config: &Config) -> Result<RpcOutcome<StatusListResponse>, String> {- tracing::debug!("[memory_sync_status][rpc] status_list via tinycortex");- let memory_config =- tinymemory_core::tinycortex::memory_config_from(config, config.workspace_dir.clone());- let statuses = match tokio::task::spawn_blocking(move || {- tinycortex::memory::sync::list_sync_statuses(&memory_config)- })- .await- {- Ok(Ok(statuses)) => statuses,- Ok(Err(error)) => {- tracing::warn!(%error, "[memory_sync_status][rpc] tinycortex status query failed");- Vec::new()- }+ tracing::debug!("[memory_sync_status][rpc] status_list via the bound driver");++ // Degrading a failure to an empty list is inherited behaviour, kept+ // deliberately rather than tightened here: this surface renders a status+ // table, and every caller of it today treats "no rows" as "nothing syncing".+ // Turning a backend blip into an RPC error is a real UI change and belongs+ // with whoever owns that screen, not smuggled into a routing swap. The warn+ // is what makes the difference visible in the meantime.+ let statuses = match crate::openhuman::memory::binding::for_config(config) {+ Ok(binding) => match binding.provider().as_source_sync() {+ Some(sync) => match sync.sync_statuses().await {+ Ok(statuses) => statuses.into_iter().map(into_wire).collect(),+ Err(error) => {+ tracing::warn!(%error, "[memory_sync_status][rpc] driver status query failed");+ Vec::new()+ }+ },+ None => {+ tracing::debug!(+ driver = %binding.driver_id(),+ "[memory_sync_status][rpc] driver does not serve SourceSync; reporting empty"+ );+ Vec::new()+ }+ },Err(error) => {- tracing::warn!(%error, "[memory_sync_status][rpc] status task join failed");+ tracing::warn!(%error, "[memory_sync_status][rpc] memory binding failed");Vec::new()}};+Ok(RpcOutcome::new(StatusListResponse { statuses }, Vec::new()))}diff --git a/src/openhuman/memory/tree/tree/rpc.rs b/src/openhuman/memory/tree/tree/rpc.rsindex 6643c300d2..ad3a8de6d3 100644--- a/src/openhuman/memory/tree/tree/rpc.rs+++ b/src/openhuman/memory/tree/tree/rpc.rs@@ -21,7 +21,6 @@ use tinycortex::memory::ingest::canonicalize::{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`.@@ -133,6 +132,7 @@ pub fn is_invalid_ingest_payload_message(message: &str) -> bool {/// refusal wording exist once: the arms differ only in which member they call.enum DriverIngest {Chat(Vec<IngestItem>),+ Email(Vec<IngestItem>),Document(IngestItem),}@@ -164,6 +164,7 @@ async fn ingest_through_driver(};match call {DriverIngest::Chat(messages) => ingest.ingest_chat(messages).await,+ DriverIngest::Email(messages) => ingest.ingest_email(messages).await,DriverIngest::Document(item) => ingest.ingest_document(item).await,}.map_err(|e| format!("ingest: {e}"))@@ -184,6 +185,86 @@ fn chat_data_source(platform: &str) -> DataSource {}}+/// As [`chat_data_source`], for a mail payload's `provider`.+///+/// `OtherEmail` is the fallback because it is the mail member that means "an+/// email provider this enum does not name", which is the honest reading of a+/// provider string that did not parse. Demoting to a non-mail member would put+/// the thread under the wrong `SourceKind` entirely.+fn email_data_source(provider: &str) -> DataSource {+ match DataSource::parse(provider) {+ Ok(source) if source.kind() == SourceKind::Email => source,+ _ => DataSource::OtherEmail,+ }+}++/// Canonicalise a mail thread into contract items.+///+/// **This is the exact inverse of the driver's reconstruction**, and it has to+/// be: the driver rebuilds an `EmailThread` from these fields and then calls+/// the same `ingest_pipeline::ingest_email` this arm used to call directly, so+/// any field that does not round-trip changes what is stored rather than+/// failing. Every one it reads through `unwrap_or` is therefore sent as+/// `Some`, so no fallback on the far side can substitute a different value:+///+/// | driver reads | sent here |+/// | --- | --- |+/// | `platform.unwrap_or(source)` | `platform: Some(provider)` |+/// | `channel_label.unwrap_or(source_id)` | `channel_label: Some(thread_subject)` |+/// | `author.unwrap_or(owner)` | `author: Some(from)` |+/// | `subject.unwrap_or(thread_subject)` | `subject: Some(subject)` |+/// | `timestamp.unwrap_or(now)` | `timestamp: Some(sent_at)` |+///+/// `to`, `cc` and `list_unsubscribe` cross verbatim. The unsubscribe header+/// matters more than it looks: an unsubscribe flow reads it back out of stored+/// mail, so dropping it makes that flow impossible rather than merely poorer.+///+/// # Empty bodies are filtered, not refused+///+/// `validate_ingest_item` answers `Invalid` for empty content, and the driver+/// validates every item before ingesting any — so one body-less message would+/// fail the whole thread, where the in-process pipeline wrote the rest of it.+/// A header-only message is entirely plausible in mail, so filtering first+/// (exactly as [`chat_items`] does) keeps the old behaviour instead of turning+/// a survivable thread into a rejected one.+fn email_items(+ source_id: &str,+ owner: &str,+ tags: &[String],+ thread: EmailThread,+) -> Vec<IngestItem> {+ let EmailThread {+ provider,+ thread_subject,+ messages,+ } = thread;+ let source = email_data_source(&provider);+ messages+ .into_iter()+ .filter(|message| !message.body.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.body,+ mime: None,+ timestamp: Some(message.sent_at),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ path_scope: None,+ author: Some(message.from),+ channel_label: Some(thread_subject.clone()),+ to: message.to,+ cc: message.cc,+ subject: Some(message.subject),+ list_unsubscribe: message.list_unsubscribe,+ platform: Some(provider.clone()),+ })+ .collect()+}+/// As [`chat_data_source`], for a document payload's `provider`.////// `Upload` is the fallback because it is the member that means "handed to the@@ -306,22 +387,6 @@ fn response_from_outcome(source_id: String, outcome: IngestOutcome) -> IngestRes}}-/// 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@@ -423,14 +488,21 @@ pub async fn ingest_rpc(log::warn!("[memory::rpc] invalid payload for email");msg})?;- 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)+ let messages = email_items(&source_id, &owner, &tags, thread);+ if messages.is_empty() {+ // The chat arm's answer, for the same reason: a thread whose+ // every message was body-less canonicalises to nothing, and+ // "the driver returns zeros for zero items" is a behaviour of+ // the one driver we ship rather than a contract promise.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Email(messages))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] email ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }}SourceKind::Document => {let doc: DocumentInput = serde_json::from_value(payload).map_err(|e| {@@ -1586,16 +1658,21 @@ 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.+ /// It used to be asserted against the engine's own `IngestResult`, on the+ /// reasoning that comparing to the upstream type beat hand-writing a key+ /// list. That held while the engine produced the body. It does not now:+ /// every arm builds from the contract's `IngestOutcome`, so a comparison+ /// against the engine summary would pin a shape nothing in this path+ /// produces — and it kept the engine linked here purely to describe a wire+ /// this crate owns.+ ///+ /// So the expectation is written out. That is the honest form once this+ /// crate is the declaring side: the keys below are what the frontend+ /// parses, and renaming a field on `IngestResponse` fails here rather than+ /// reaching a reader.#[test]- fn the_response_body_serialises_exactly_as_the_engine_summary() {- let engine = IngestResult {+ fn the_response_body_serialises_exactly_as_the_declared_wire() {+ let ours = IngestResponse {source_id: "doc-launch".into(),chunks_written: 3,chunks_dropped: 1,@@ -1603,20 +1680,18 @@ mod tests {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"+ serde_json::json!({+ "source_id": "doc-launch",+ "chunks_written": 3,+ "chunks_dropped": 1,+ "chunk_ids": ["chunk-a", "chunk-b", "chunk-c"],+ "extract_jobs_enqueued": 2,+ "already_ingested": true,+ }),+ "the ingest response wire moved — the frontend reads these names");}diff --git a/src/openhuman/modules/memory.rs b/src/openhuman/modules/memory.rsindex 52323e2862..59a35188b9 100644--- a/src/openhuman/modules/memory.rs+++ b/src/openhuman/modules/memory.rs@@ -797,6 +797,15 @@ impl MemoryTree for ModuleMemoryProvider {) -> Result<SummaryForest, MemoryError> {module_call!(self, "summary_forest", "SummaryForest", (limit, scope))}++ async fn flush_source_tree(&self, source_scope: &str) -> Result<u64, MemoryError> {+ module_call!(+ self,+ "flush_source_tree",+ "FlushSourceTree",+ (source_scope,)+ )+ }async fn recent_leaves(&self,limit: usize,