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
chore: remove obsolete learning and memory test infrastructure
Steven Enamakelea59771e9017
diff --git a/crates/openhuman-core/src/channels/tests/memory.rs b/crates/openhuman-core/src/channels/tests/memory.rsdeleted file mode 100644index e310220790..0000000000--- a/crates/openhuman-core/src/channels/tests/memory.rs+++ /dev/null@@ -1,254 +0,0 @@-use super::super::context::{- build_memory_context, clear_sender_history, conversation_history_key, conversation_memory_key,- ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS,-};-use super::super::runtime::process_channel_message;-use super::super::{traits, Channel};-use super::common::{HistoryCaptureModel, RecordingChannel};-use crate::inference::provider;-use std::collections::HashMap;-use std::sync::{Arc, Mutex};-use tinymemory_api::provider::MemoryCore as _;--fn conversation_memory_key_uses_message_id() {- let msg = traits::ChannelMessage {- id: "msg_abc123".into(),- sender: "U123".into(),- reply_target: "C456".into(),- content: "hello".into(),- channel: "slack".into(),- timestamp: 1,- thread_ts: None,- };-- assert_eq!(conversation_memory_key(&msg), "slack_U123_msg_abc123");-}--#[test]-fn conversation_memory_key_is_unique_per_message() {- let msg1 = traits::ChannelMessage {- id: "msg_1".into(),- sender: "U123".into(),- reply_target: "C456".into(),- content: "first".into(),- channel: "slack".into(),- timestamp: 1,- thread_ts: None,- };- let msg2 = traits::ChannelMessage {- id: "msg_2".into(),- sender: "U123".into(),- reply_target: "C456".into(),- content: "second".into(),- channel: "slack".into(),- timestamp: 2,- thread_ts: None,- };-- assert_ne!(- conversation_memory_key(&msg1),- conversation_memory_key(&msg2)- );-}--#[tokio::test]-async fn build_memory_context_includes_recalled_entries() {- let (_provider, mem) = crate::memory::guard::in_memory::guarded_in_memory();- mem.store(- "",- "age_fact",- "Age is 45",- tinymemory_api::types::MemoryCategory::Conversation,- None,- tinymemory_api::types::MemoryTaint::Internal,- )- .await- .unwrap();-- let context = build_memory_context(&mem, "age", 0.0).await;- assert!(context.contains("[Memory context]"));- assert!(context.contains("Age is 45"));-}--#[tokio::test]-async fn process_channel_message_restores_per_sender_history_on_follow_ups() {- let _bus_guard = super::common::use_real_agent_handler().await;- let channel_impl = Arc::new(RecordingChannel::default());- let channel: Arc<dyn Channel> = channel_impl.clone();-- let mut channels_by_name = HashMap::new();- channels_by_name.insert(channel.name().to_string(), channel);-- let provider_impl = Arc::new(HistoryCaptureModel::default());-- let runtime_ctx = Arc::new(ChannelRuntimeContext {- channels_by_name: Arc::new(channels_by_name),- turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(- provider_impl.clone(),- )),- default_provider: Arc::new("test-provider".to_string()),- memory: crate::memory::guard::in_memory::guarded_fixed_recall(Vec::new()),- tools_registry: Arc::new(vec![]),- system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),- model: Arc::new("test-model".to_string()),- temperature: 0.0,- auto_save_memory: false,- max_tool_iterations: 5,- min_relevance_score: 0.0,- conversation_histories: Arc::new(Mutex::new(HashMap::new())),- turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())),- route_overrides: Arc::new(Mutex::new(HashMap::new())),- api_url: None,- inference_url: None,- reliability: Arc::new(crate::config::ReliabilityConfig::default()),- provider_runtime_options: provider::ProviderRuntimeOptions::default(),- workspace_dir: Arc::new(std::env::temp_dir()),- message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,- multimodal: crate::config::MultimodalConfig::default(),- multimodal_files: crate::config::MultimodalFileConfig::default(),- config: None,- });-- process_channel_message(- runtime_ctx.clone(),- traits::ChannelMessage {- id: "msg-a".to_string(),- sender: "alice".to_string(),- reply_target: "chat-1".to_string(),- content: "hello".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: None,- },- )- .await;-- process_channel_message(- runtime_ctx,- traits::ChannelMessage {- id: "msg-b".to_string(),- sender: "alice".to_string(),- reply_target: "chat-1".to_string(),- content: "follow up".to_string(),- channel: "test-channel".to_string(),- timestamp: 2,- thread_ts: None,- },- )- .await;-- let calls = provider_impl- .calls- .lock()- .unwrap_or_else(|e| e.into_inner());- assert_eq!(calls.len(), 2);- assert_eq!(calls[0].len(), 2);- assert_eq!(calls[0][0].0, "system");- assert_eq!(calls[0][1].0, "user");- assert_eq!(calls[1].len(), 4);- assert_eq!(calls[1][0].0, "system");- assert_eq!(calls[1][1].0, "user");- assert_eq!(calls[1][2].0, "assistant");- assert_eq!(calls[1][3].0, "user");- assert!(calls[1][1].1.contains("hello"));- assert!(calls[1][2].1.contains("response-1"));- assert!(calls[1][3].1.contains("follow up"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH): the assertion turns on \-ranked recall finding the autosaved turn, which the in-memory fake\'s substring match cannot do"]-async fn process_channel_message_uses_autosaved_memory_after_history_is_cleared() {- let _bus_guard = super::common::use_real_agent_handler().await;- let channel_impl = Arc::new(RecordingChannel::default());- let channel: Arc<dyn Channel> = channel_impl.clone();-- let mut channels_by_name = HashMap::new();- channels_by_name.insert(channel.name().to_string(), channel);-- let provider_impl = Arc::new(HistoryCaptureModel::default());- let (_memory_provider, memory) = crate::memory::guard::in_memory::guarded_in_memory();-- let runtime_ctx = Arc::new(ChannelRuntimeContext {- channels_by_name: Arc::new(channels_by_name),- turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(- provider_impl.clone(),- )),- default_provider: Arc::new("test-provider".to_string()),- memory,- tools_registry: Arc::new(vec![]),- system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),- model: Arc::new("test-model".to_string()),- temperature: 0.0,- auto_save_memory: true,- max_tool_iterations: 5,- min_relevance_score: 0.0,- conversation_histories: Arc::new(Mutex::new(HashMap::new())),- turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())),- route_overrides: Arc::new(Mutex::new(HashMap::new())),- api_url: None,- inference_url: None,- reliability: Arc::new(crate::config::ReliabilityConfig::default()),- provider_runtime_options: provider::ProviderRuntimeOptions::default(),- workspace_dir: Arc::new(std::env::temp_dir()),- message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,- multimodal: crate::config::MultimodalConfig::default(),- multimodal_files: crate::config::MultimodalFileConfig::default(),- config: None,- });-- let first = traits::ChannelMessage {- id: "msg-memory-a".to_string(),- sender: "alice".to_string(),- reply_target: "chat-1".to_string(),- content: "My launch code is phoenix-773.".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: None,- };- let history_key = conversation_history_key(&first);-- process_channel_message(runtime_ctx.clone(), first).await;-- clear_sender_history(&runtime_ctx, &history_key);-- process_channel_message(- runtime_ctx,- traits::ChannelMessage {- id: "msg-memory-b".to_string(),- sender: "alice".to_string(),- reply_target: "chat-1".to_string(),- content: "What is my launch code?".to_string(),- channel: "test-channel".to_string(),- timestamp: 2,- thread_ts: None,- },- )- .await;-- let calls = provider_impl- .calls- .lock()- .unwrap_or_else(|e| e.into_inner());- assert_eq!(calls.len(), 2);- assert_eq!(calls[1].len(), 2);- assert_eq!(calls[1][0].0, "system");- assert_eq!(calls[1][1].0, "user");- assert!(- calls[1][1].1.contains("[Memory context]"),- "second turn should include recalled memory context: {:?}",- calls[1][1]- );- assert!(- calls[1][1].1.contains("phoenix-773"),- "second turn should surface the autosaved fact: {:?}",- calls[1][1]- );- assert!(- calls[1][1].1.contains("What is my launch code?"),- "current user question should remain in the final prompt: {:?}",- calls[1][1]- );-}--// ── AIEOS Identity Tests (Issue #168) ─────────────────────────diff --git a/crates/openhuman-core/src/config/schema/learning.rs b/crates/openhuman-core/src/config/schema/learning.rsdeleted file mode 100644index 3a9f190c25..0000000000--- a/crates/openhuman-core/src/config/schema/learning.rs+++ /dev/null@@ -1,174 +0,0 @@-//! Self-learning configuration — reflection, user profiling, tool tracking.--use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--/// Which LLM to use for reflection inference.-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]-#[serde(rename_all = "snake_case")]-#[derive(Default)]-pub enum ReflectionSource {- /// Use the local Ollama model via `LocalAiService::prompt()`.- /// Model is determined by `config.local_ai.chat_model_id`.- #[default]- Local,- /// Use the cloud reasoning model via `Provider::simple_chat("hint:reasoning")`.- Cloud,-}--/// Configuration for the agent self-learning subsystem.-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct LearningConfig {- /// Master switch. Default: false.- #[serde(default)]- pub enabled: bool,-- /// Enable post-turn reflection (observation extraction). Default: true when learning is enabled.- #[serde(default = "default_true")]- pub reflection_enabled: bool,-- /// Enable automatic user profile extraction. Default: true when learning is enabled.- #[serde(default = "default_true")]- pub user_profile_enabled: bool,-- /// Enable tool effectiveness tracking. Default: true when learning is enabled.- #[serde(default = "default_true")]- pub tool_tracking_enabled: bool,-- /// Enable the tool-scoped memory capture hook (see- /// [`crate::memory::tool_memory::ToolMemoryCaptureHook`]).- ///- /// When enabled, the hook records user edicts ("never email Sarah")- /// as `Critical`-priority rules in the `tool-{name}` memory- /// namespace, and tallies repeated tool failures into- /// `Normal`-priority observations. Defaults to true when learning- /// is enabled — set to false to disable durable rule capture- /// without turning off learning entirely.- #[serde(default = "default_true")]- pub tool_memory_capture_enabled: bool,-- /// Which LLM to use for reflection. Default: local (Ollama).- #[serde(default)]- pub reflection_source: ReflectionSource,-- /// Maximum reflections per session before throttling. Default: 20.- #[serde(default = "default_max_reflections")]- pub max_reflections_per_session: usize,-- /// Minimum tool calls in a turn to trigger reflection. Default: 1.- #[serde(default = "default_min_turn_complexity")]- pub min_turn_complexity: usize,-- /// Pipe agent chat turns into the memory tree as `source="conversations:agent"`.- ///- /// When enabled, [`ArchivistHook`] calls `tree::ingest::ingest_chat` with a- /// two-message [`ChatBatch`] (user + assistant) after every completed turn.- /// Tool-call JSON is stripped from the assistant message before ingest —- /// only the prose response reaches the tree.- ///- /// Default: true. Disable to stop agent chat from flowing into the tree- /// without affecting the episodic-log write path.- #[serde(default = "default_true")]- pub chat_to_tree_enabled: bool,-- /// Enable the stability detector rebuild cycle. Default: true.- #[serde(default = "default_true")]- pub stability_detector_enabled: bool,-- /// Enable episodic capture (ArchivistHook) regardless of the master- /// `learning.enabled` toggle.- ///- /// Episodic capture is the system-of-record for chat turns- /// (`episodic_log` FTS5 table, conversation segmentation, segment- /// summaries with LLM recap, and segment embeddings). It must remain- /// active even when the inference stack- /// (reflection / stability-detector) is off.- ///- /// Default: `true`. Set to `false` to fully disable the Archivist.- ///- /// Override via `OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED=0|1`.- #[serde(default = "default_true")]- pub episodic_capture_enabled: bool,-- /// Enable preemptive STM recall injection at session start and on-demand- /// `stm_recall_search` tool exposure.- ///- /// When enabled, a bounded cross-thread context block is assembled from- /// recent episodic entries (FTS5 keyword arm) and segment recaps (cosine- /// similarity arm) from OTHER sessions and injected into the first turn's- /// user message. The `stm_recall_search` tool is also registered in the- /// agent's tool list.- ///- /// Default: `true`. Set to `false` to fully disable STM recall.- ///- /// Override via `OPENHUMAN_LEARNING_STM_RECALL_ENABLED=0|1`.- #[serde(default = "default_true")]- pub stm_recall_enabled: bool,-- /// How often the periodic rebuild loop runs in seconds. Default: 1800 (30 minutes).- #[serde(default = "default_rebuild_interval_secs")]- pub rebuild_interval_secs: u64,-- /// Enable explicit user-preference injection into the system prompt.- ///- /// When `true` (the default), preferences saved via the `remember_preference`- /// tool are injected into every session prompt regardless of whether the full- /// inference-based learning subsystem (`enabled`) is on. This is the- /// narrow, always-on path for user-authoritative pinned preferences —- /// no reflection, no heuristics, no stability engine.- ///- /// Explicitly set to `false` (or `OPENHUMAN_LEARNING_EXPLICIT_PREFERENCES_ENABLED=0`)- /// to suppress all preference injection even for explicitly pinned entries.- #[serde(default = "default_true")]- pub explicit_preferences_enabled: bool,-- /// Enable automatic enrichment of the long-term goals list- /// (`MEMORY_GOALS.md`) when the conversation context is summarized.- ///- /// When `true` (the default), a best-effort background `goals_agent`- /// run is fired after a segment recap so the user's durable goals stay- /// fresh. Set to `false` (or- /// `OPENHUMAN_LEARNING_GOALS_ENRICHMENT_ENABLED=0`) to only update the- /// goals list via explicit RPC/tools.- #[serde(default = "default_true")]- pub goals_enrichment_enabled: bool,-}--fn default_rebuild_interval_secs() -> u64 {- 1800-}--fn default_true() -> bool {- true-}--fn default_max_reflections() -> usize {- 20-}--fn default_min_turn_complexity() -> usize {- 1-}--impl Default for LearningConfig {- fn default() -> Self {- Self {- enabled: false,- reflection_enabled: default_true(),- user_profile_enabled: default_true(),- tool_tracking_enabled: default_true(),- tool_memory_capture_enabled: default_true(),- reflection_source: ReflectionSource::default(),- max_reflections_per_session: default_max_reflections(),- min_turn_complexity: default_min_turn_complexity(),- chat_to_tree_enabled: default_true(),- stability_detector_enabled: default_true(),- rebuild_interval_secs: default_rebuild_interval_secs(),- episodic_capture_enabled: default_true(),- stm_recall_enabled: default_true(),- explicit_preferences_enabled: default_true(),- goals_enrichment_enabled: default_true(),- }- }-}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay.rs b/crates/openhuman-core/src/config/schema/load/env_overlay.rsindex 0b592e0b5c..8e021430e7 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay.rs@@ -4,12 +4,11 @@//! config section's overrides live in a submodule below.mod dictation_context;-mod learning_memory;+mod embeddings;mod observability;mod proxy;mod runtime;mod search;-mod subsystems_update;use super::super::proxy::{set_runtime_proxy_config, ProxyScope};use super::super::Config;@@ -238,9 +237,7 @@ impl Config {self.apply_proxy_env(env);self.apply_runtime_env(env);self.apply_observability_env(env);- self.apply_learning_env(env);- self.apply_memory_tree_env(env);- self.apply_subsystems_env(env);+ self.apply_embedding_env(env);self.apply_update_env(env);self.apply_dictation_env(env);self.apply_context_env(env);diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rsnew file mode 100644index 0000000000..d2f994e4ae--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rs@@ -0,0 +1,15 @@+//! Env overrides for the embedding settings kept under `[memory]`.++use crate::config::schema::load::env::EnvLookup;+use crate::config::schema::Config;++impl Config {+ /// `OPENHUMAN_MEMORY_EMBED_RATE_LIMIT` — embedding requests per minute.+ pub(super) fn apply_embedding_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(val) = env.get("OPENHUMAN_MEMORY_EMBED_RATE_LIMIT") {+ if let Ok(per_min) = val.trim().parse::<u32>() {+ self.memory.embedding_rate_limit_per_min = per_min;+ }+ }+ }+}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rsdeleted file mode 100644index 708d30c850..0000000000--- a/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rs+++ /dev/null@@ -1,246 +0,0 @@-//! Env overrides for the learning subsystem and the memory tree.--use crate::config::schema::load::env::parse_env_bool;-use crate::config::schema::load::env::EnvLookup;-use crate::config::schema::Config;--impl Config {- pub(super) fn apply_learning_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_LEARNING_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.enabled = true,- "0" | "false" | "no" | "off" => self.learning.enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_REFLECTION_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.reflection_enabled = true,- "0" | "false" | "no" | "off" => self.learning.reflection_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_USER_PROFILE_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.user_profile_enabled = true,- "0" | "false" | "no" | "off" => self.learning.user_profile_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_TRACKING_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.tool_tracking_enabled = true,- "0" | "false" | "no" | "off" => self.learning.tool_tracking_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED") {- if let Some(enabled) = parse_env_bool(- "OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED",- flag.as_str(),- ) {- self.learning.tool_memory_capture_enabled = enabled;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_EXPLICIT_PREFERENCES_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.explicit_preferences_enabled = true,- "0" | "false" | "no" | "off" => self.learning.explicit_preferences_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_GOALS_ENRICHMENT_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.goals_enrichment_enabled = true,- "0" | "false" | "no" | "off" => self.learning.goals_enrichment_enabled = false,- _ => {}- }- }- if let Some(source) = env.get("OPENHUMAN_LEARNING_REFLECTION_SOURCE") {- let normalized = source.trim().to_ascii_lowercase();- match normalized.as_str() {- "local" => self.learning.reflection_source = crate::config::ReflectionSource::Local,- "cloud" => self.learning.reflection_source = crate::config::ReflectionSource::Cloud,- _ => {- tracing::warn!(- source = %source,- "ignoring invalid OPENHUMAN_LEARNING_REFLECTION_SOURCE (valid: local, cloud)"- );- }- }- }- if let Some(val) = env.get("OPENHUMAN_LEARNING_MAX_REFLECTIONS_PER_SESSION") {- if let Ok(max) = val.trim().parse::<usize>() {- self.learning.max_reflections_per_session = max;- }- }- if let Some(val) = env.get("OPENHUMAN_LEARNING_MIN_TURN_COMPLEXITY") {- if let Ok(min) = val.trim().parse::<usize>() {- self.learning.min_turn_complexity = min;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED", flag.as_str())- {- self.learning.episodic_capture_enabled = enabled;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_STM_RECALL_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_LEARNING_STM_RECALL_ENABLED", flag.as_str())- {- self.learning.stm_recall_enabled = enabled;- }- }- }-- pub(super) fn apply_memory_tree_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EMBED_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.embedding_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EMBED_MODEL") {- let trimmed = model.trim();- self.memory_tree.embedding_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EMBED_TIMEOUT_MS") {- if let Ok(timeout_ms) = val.trim().parse::<u64>() {- if timeout_ms > 0 {- self.memory_tree.embedding_timeout_ms = Some(timeout_ms);- }- }- }- if let Ok(flag) = std::env::var("OPENHUMAN_MEMORY_EMBED_STRICT") {- if let Some(strict) = parse_env_bool("OPENHUMAN_MEMORY_EMBED_STRICT", &flag) {- self.memory_tree.embedding_strict = strict;- }- }- if let Some(val) = env.get("OPENHUMAN_MEMORY_EMBED_RATE_LIMIT") {- if let Ok(per_min) = val.trim().parse::<u32>() {- self.memory.embedding_rate_limit_per_min = per_min;- }- }-- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.llm_extractor_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_MODEL") {- let trimmed = model.trim();- self.memory_tree.llm_extractor_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_TIMEOUT_MS") {- if let Ok(ms) = val.trim().parse::<u64>() {- if ms > 0 {- self.memory_tree.llm_extractor_timeout_ms = Some(ms);- }- }- }-- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.llm_summariser_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_MODEL") {- let trimmed = model.trim();- self.memory_tree.llm_summariser_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_TIMEOUT_MS") {- if let Ok(ms) = val.trim().parse::<u64>() {- if ms > 0 {- self.memory_tree.llm_summariser_timeout_ms = Some(ms);- }- }- }-- if let Some(dir) = env.get("OPENHUMAN_MEMORY_TREE_CONTENT_DIR") {- let trimmed = dir.trim();- self.memory_tree.content_dir = if trimmed.is_empty() {- None- } else {- Some(std::path::PathBuf::from(trimmed))- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_LLM_BACKEND") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match crate::config::LlmBackend::parse(trimmed) {- Ok(b) => {- log::debug!(- "[memory_tree] OPENHUMAN_MEMORY_TREE_LLM_BACKEND override applied: {}",- b.as_str()- );- self.memory_tree.llm_backend = b;- }- Err(e) => {- tracing::warn!(- value = trimmed,- error = %e,- "ignoring invalid OPENHUMAN_MEMORY_TREE_LLM_BACKEND (valid: cloud, local)"- );- }- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_LLM_MODEL") {- let trimmed = raw.trim();- self.memory_tree.cloud_llm_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SMART_WALK_MODEL") {- let trimmed = raw.trim();- self.memory_tree.smart_walk_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION", &raw) {- self.memory_tree.cloud_summarization_opt_in = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED", &raw) {- self.memory_tree.spacy_enabled = val;- }- }- }-}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rsdeleted file mode 100644index 8badc9320b..0000000000--- a/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rs+++ /dev/null@@ -1,108 +0,0 @@-//! Env overrides for the `[subsystems]` drivers and the auto-updater.--use crate::config::schema::load::env::parse_env_bool;-use crate::config::schema::load::env::EnvLookup;-use crate::config::schema::Config;-use crate::config::schema::UpdateRestartStrategy;--impl Config {- /// `[subsystems.memory]` overrides — kernel.md §3.6 / plan-memory.md §4.5. Mirrors- /// the `apply_memory_tree_env` reading pattern above. GREENFIELD: nothing- /// reads `self.subsystems` yet, so these overrides have no runtime effect- /// beyond making the field settable via env for forward compatibility.- pub(super) fn apply_subsystems_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(raw) = env.get("OPENHUMAN_MEMORY_DRIVER") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- self.subsystems.memory.driver = trimmed.to_string();- }- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL", &raw) {- self.subsystems.memory.hooks.auto_recall = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE", &raw) {- self.subsystems.memory.hooks.auto_capture = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.max_context_tokens = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS ignored; expected an unsigned integer"- ),- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.recall_max_chars = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS ignored; expected an unsigned integer"- ),- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.capture_max_chars = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS ignored; expected an unsigned integer"- ),- }- }- }- }-- pub(super) fn apply_update_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.update.enabled = true,- "0" | "false" | "no" | "off" => self.update.enabled = false,- _ => {}- }- }- if let Some(val) = env.get("OPENHUMAN_AUTO_UPDATE_INTERVAL_MINUTES") {- if let Ok(minutes) = val.trim().parse::<u32>() {- self.update.interval_minutes = minutes;- }- }- if let Some(raw) = env.get("OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY") {- match raw.trim().to_ascii_lowercase().as_str() {- "self_replace" | "self-replace" | "self" => {- self.update.restart_strategy = UpdateRestartStrategy::SelfReplace;- }- "supervisor" | "stage_only" | "stage-only" => {- self.update.restart_strategy = UpdateRestartStrategy::Supervisor;- }- other => {- tracing::warn!(- value = other,- "ignoring invalid OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY \- (valid: self_replace, supervisor)"- );- }- }- }- if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED", &flag)- {- self.update.rpc_mutations_enabled = enabled;- }- }- }-}diff --git a/crates/openhuman-core/src/flows/tinyflows/memory_node_e2e_tests.rs b/crates/openhuman-core/src/flows/tinyflows/memory_node_e2e_tests.rsdeleted file mode 100644index 8445ae292f..0000000000--- a/crates/openhuman-core/src/flows/tinyflows/memory_node_e2e_tests.rs+++ /dev/null@@ -1,378 +0,0 @@-//! End-to-end tests proving the `memory` node round-trips through the REAL-//! stack: the `tinyflows` engine executing a *compiled graph*, dispatching-//! through the real [`OpenHumanMemory`](super::memory_adapter::OpenHumanMemory)-//! host adapter — wired via [`build_capabilities`], NOT-//! `tinyflows::caps::mock::MockMemory` — against a real, on-disk `Memory`-//! store.-//!-//! **The gap this closes.** Two layers of unit coverage already exist:-//! - `memory_adapter_tests.rs` calls `OpenHumanMemory`'s methods directly-//! (scope lockdown, tier gate, trust boundary) but never through a compiled-//! graph or the engine, and never against the real store (every test there-//! uses a fresh empty `Config::workspace_dir` and only exercises the-//! error paths).-//! - `vendor/tinyflows/src/nodes/integration/memory.rs`'s own tests drive-//! `MemoryNode` through `compile`/`run`, but always against-//! `tinyflows::caps::mock::MockMemory` — the crate's own mock, not this-//! host's real adapter.-//!-//! Neither proves the actual wiring a saved flow run uses in production:-//! `flows::ops::flows_run` compiles a graph, calls-//! [`build_capabilities`] for a real `Capabilities` bundle, and hands both to-//! `tinyflows::engine::run`. This file reproduces exactly that path (see-//! [`trigger_to_memory`] / [`workflow_origin`]) so a regression in the-//! engine → `Capabilities::memory` → `OpenHumanMemory` → `Memory` store chain-//! fails a test, not just a live flow run.-//!-//! **Layer entered: full engine-run**, not a node-executor shortcut. Every-//! test below drives `tinyflows::compiler::compile` + `tinyflows::engine::run`-//! over a real [`build_capabilities`] bundle, under the same-//! `AgentTurnOrigin::TrustedAutomation { source: Workflow { .. }, .. }`-//! task-local scope `flows::ops::workflow_origin` scopes around a real-//! `flows_run` — the ONLY thing not reproduced is `flows::ops`'s own-//! run-bookkeeping (draft persistence, checkpointing, run-history rows),-//! which has nothing to do with whether the `memory` node's adapter wiring-//! works and is covered separately by `flows::ops_tests`.-//!-//! **Real store, not a stub.** `memory` here is the process-global-//! `MemoryClient` (`crate::memory::global`), bound to the shared-//! temp workspace `memory::ops::test_support::shared_memory_test_workspace`-//! already uses for every other `memory::ops` real-store test — the SAME-//! on-disk `UnifiedMemory`-backed store `flows_run` writes to in production.-//! Serialized against sibling tests with `GLOBAL_MEMORY_TEST_LOCK`, exactly-//! like `memory::ops::documents`/`memory::ops::sync`/etc already do (see-//! [`lock_shared_memory`]).--use std::sync::Arc;--use serde_json::{json, Value};-use tinyflows::model::{Edge, Node, NodeKind, WorkflowGraph};--use crate::agent::turn_origin::{self, AgentTurnOrigin, TrustedAutomationSource};-use crate::config::Config;-use crate::flows::memory_tools::FlowMemoryRecallTool;-use crate::security::AutonomyLevel;-use tinytools::Tool;--use super::build_capabilities;--// ── fixtures ────────────────────────────────────────────────────────────--/// Binds the process-global memory client to the shared test workspace and-/// holds the cross-test serialization lock for the caller's whole test body.-///-/// One on-disk SQLite store is shared across every test thread in this-/// binary (`memory::global` is a process-global `OnceLock`), so concurrent-/// `init`/read/write from sibling tests races on schema init and can bleed-/// data across tests. `GLOBAL_MEMORY_TEST_LOCK` + `shared_memory_test_workspace`-/// is the crate's existing, proven pattern for this (see-/// `memory::ops::documents::tests::ensure_memory_client` and-/// `composio::ops_tests::init_memory_client`) — reused verbatim here rather-/// than inventing a third variant.-async fn lock_shared_memory() -> tokio::sync::MutexGuard<'static, ()> {- let guard = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- crate::memory::ops::shared_memory_test_workspace();- guard-}--/// A `Config` rooted at its own fresh tempdir, with autonomy raised to-/// `Full`.-///-/// `remember`/`forget` are `CommandClass::Write` in-/// `OpenHumanMemory::tier_gate_write`, which needs a non-`Block` tier-/// decision to clear `enforce_node_tier_gate` at all. `Full` also keeps the-/// write from depending on whether some earlier test in this shared binary-/// has installed a global `ApprovalGate` — see [`workflow_origin`]'s doc for-/// why `require_approval: false` makes this safe either way.-fn full_autonomy_config() -> (tempfile::TempDir, Arc<Config>) {- let tmp = tempfile::TempDir::new().unwrap();- let mut cfg = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- cfg.autonomy.level = AutonomyLevel::Full;- (tmp, Arc::new(cfg))-}--/// A trusted, saved-flow run origin for `flow_id` — the ONLY source-/// `OpenHumanMemory::trusted_flow_id` (and `flow_memory_recall`/-/// `flow_memory_remember`'s own `trusted_flow_id`) accepts for-/// `scope: "flow"`/`"flows"`. Mirrors what `flows::ops::flows_run` scopes-/// around a real run.-///-/// `require_approval: false` matches a saved flow's default. It also means-/// this test's write can never park on approval even if some other test in-/// this shared binary has installed a global `ApprovalGate`:-/// `ApprovalGate::intercept_audited` allows a-/// `Workflow { require_approval: false }` origin unconditionally (see-/// `caps::gate_call_for_tier`'s doc comment) — so this test's outcome does-/// not depend on test execution order.-fn workflow_origin(flow_id: &str) -> AgentTurnOrigin {- AgentTurnOrigin::TrustedAutomation {- job_id: flow_id.to_string(),- source: TrustedAutomationSource::Workflow {- require_approval: false,- },- }-}--fn node(id: &str, kind: NodeKind, config: Value) -> Node {- Node {- id: id.to_string(),- kind,- type_version: 1,- name: id.to_string(),- config,- ports: Vec::new(),- position: None,- }-}--fn edge(from: &str, to: &str) -> Edge {- Edge {- from_node: from.to_string(),- from_port: "main".to_string(),- to_node: to.to_string(),- to_port: "main".to_string(),- }-}--/// A minimal `trigger -> memory` graph — the same two-node shape-/// `vendor/tinyflows/src/nodes/integration/memory.rs`'s own tests use, kept-/// identical here so any behavioral difference between running against-/// `MockMemory` and running against the real `OpenHumanMemory` adapter is-/// attributable to the adapter, not to graph-shape differences.-fn trigger_to_memory(config: Value) -> WorkflowGraph {- WorkflowGraph {- nodes: vec![- node("t", NodeKind::Trigger, Value::Null),- node("mem", NodeKind::Memory, config),- ],- edges: vec![edge("t", "mem")],- ..Default::default()- }-}--fn unique_flow_id(prefix: &str) -> String {- format!("{prefix}-{}", uuid::Uuid::new_v4())-}--// ── 1 & 2. flow-scope round-trip through the real engine, plus coherence-// with the sibling `flow_memory_recall` agent tool ─────────────────────────--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the adapter writes through the bound driver, so the round trip needs the real artifact"]-async fn memory_node_remember_then_recall_round_trips_through_the_real_engine_and_adapter() {- let _serial = lock_shared_memory().await;- let (_tmp, config) = full_autonomy_config();- let flow_id = unique_flow_id("e2e-roundtrip");- let caps = build_capabilities(config, format!("flow:{flow_id}"));-- // ── remember: a real graph, compiled by the real validator/compiler and- // run through the real engine, dispatching through the real- // OpenHumanMemory adapter (build_capabilities' `memory` slot). ──- let remember_graph = trigger_to_memory(json!({- "operation": "remember",- "scope": "flow",- "key": "item-42",- "value": "Digest already sent item-42 to subscribers"- }));- let compiled_remember =- tinyflows::compiler::compile(&remember_graph).expect("compile remember graph");-- let remember_outcome = turn_origin::with_origin(- workflow_origin(&flow_id),- tinyflows::engine::run(&compiled_remember, Value::Null, &caps),- )- .await- .expect("remember run should complete against the real store");-- assert!(- remember_outcome.pending_approvals.is_empty(),- "Full autonomy + require_approval:false must never park this write"- );- assert_eq!(- remember_outcome.output["nodes"]["mem"]["items"][0]["json"]["json"]["ok"],- json!(true),- "unexpected remember output shape: {}",- remember_outcome.output- );- assert_eq!(- remember_outcome.output["nodes"]["mem"]["items"][0]["json"]["json"]["key"],- json!("item-42")- );-- // ── recall: a SECOND compiled graph, a SECOND engine run, same flow_id- // — proving the write from the first run is durably visible via the real- // on-disk store, not merely echoed back within one call. ──- let recall_graph = trigger_to_memory(json!({- "operation": "recall",- "scope": "flow",- "query": "item-42"- }));- let compiled_recall =- tinyflows::compiler::compile(&recall_graph).expect("compile recall graph");-- let recall_outcome = turn_origin::with_origin(- workflow_origin(&flow_id),- tinyflows::engine::run(&compiled_recall, Value::Null, &caps),- )- .await- .expect("recall run should complete against the real store");-- assert!(recall_outcome.pending_approvals.is_empty());- let results = recall_outcome.output["nodes"]["mem"]["items"][0]["json"]["json"]["results"]- .as_array()- .cloned()- .unwrap_or_default();- assert!(- results- .iter()- .any(|hit| hit["text"].as_str().is_some_and(|t| t.contains("item-42"))),- "expected the remembered content back from the real flow_<id> namespace, got: {results:?}"- );-- // ── coherence (#5176): the SAME write is visible through the sibling- // `flow_memory_recall` agent tool for the same flow_id — proving one- // shared store, not two namespace conventions that happen to overlap by- // convention (see memory_adapter.rs's module doc). ──- // The tool resolves the bound driver itself now, so no handle is threaded- // in; `lock_shared_memory` still pins the workspace the driver binds to.- let recall_tool = FlowMemoryRecallTool::new();- let tool_result = turn_origin::with_origin(- workflow_origin(&flow_id),- recall_tool.execute(json!({ "query": "item-42", "flow_id": flow_id })),- )- .await- .expect("flow_memory_recall tool call should not error at the harness level");- assert!(- !tool_result.is_error,- "flow_memory_recall reported an error: {}",- tool_result.output()- );- assert!(- tool_result.output().contains("item-42"),- "expected the memory-node's write to be visible via flow_memory_recall \- (same underlying store), got: {}",- tool_result.output()- );-}--// ── 3. security invariant end-to-end: scope:"user" writes are rejected ─────--/// A `remember` node asking for `scope: "user"` is refused twice over.-///-/// This test used to assert a third thing: that the user's real-/// `GLOBAL_NAMESPACE` store held nothing under the key afterwards. That layer-/// needed `tinymemory_core::global::client_if_ready()` and-/// `tinycortex::memory::GLOBAL_NAMESPACE` — an in-process engine — and went-/// with it (openhuman#6161). It is not replaced here, and pretending otherwise-/// would be worse than saying so: the fake driver this crate now binds has no-/// user store to leave untouched, so an assertion against it would pass-/// whether or not the guard held.-///-/// The two layers that remain are the ones that do the refusing, and neither-/// needed an engine to begin with. Deleting them along with the third was the-/// mistake this restores.-#[tokio::test]-async fn memory_node_remember_user_scope_is_rejected_before_it_can_write() {- let _serial = lock_shared_memory().await;- let (_tmp, config) = full_autonomy_config();- let flow_id = unique_flow_id("e2e-security");- let caps = build_capabilities(config, format!("flow:{flow_id}"));- let forbidden_key = format!("forbidden-{}", uuid::Uuid::new_v4());-- // ── (a) validate-time rejection: tinyflows' own structural validator- // rejects a `remember`/`scope: "user"` node BEFORE compile ever succeeds,- // so a graph shaped this way can never reach a run. Nothing else in this- // crate asserts the compiler half. ──- let user_scope_graph = trigger_to_memory(json!({- "operation": "remember",- "scope": "user",- "key": forbidden_key,- "value": "must never be written to user memory"- }));- let compile_err = tinyflows::compiler::compile(&user_scope_graph)- .expect_err("scope: \"user\" on a remember node must be rejected at validate/compile time");- assert!(- compile_err.to_string().to_lowercase().contains("user"),- "expected the validator's scope:\"user\" rejection, got: {compile_err}"- );-- // ── (b) defense-in-depth: even bypassing tinyflows' validator entirely and- // calling straight through to the adapter `build_capabilities` wired — the- // exact instance a real run would dispatch to — `OpenHumanMemory::remember`- // independently refuses anything but scope: "flow".- //- // `memory_adapter_tests::remember_rejects_user_scope` covers the same- // refusal on a directly-constructed adapter. This one is not redundant with- // it: what is under test here is that the capability a real run receives is- // that adapter, rather than something assembled differently on the way. ──- let direct_err = turn_origin::with_origin(- workflow_origin(&flow_id),- caps.memory- .as_ref()- .expect("build_capabilities must wire a memory capability")- .remember("user", &forbidden_key, json!("must never be written")),- )- .await- .expect_err("the adapter itself must independently refuse scope: \"user\"");- assert!(direct_err- .to_string()- .contains("only supports scope \"flow\""));-}--// ── 4. dry_run_workflow still works with a memory node ─────────────────────--/// A graph containing a `memory` node dry-runs end to end against the mock-/// capabilities `DryRunWorkflowTool` wires, and comes back with `MockMemory`'s-/// shaped echo rather than store content.-///-/// The two assertions that read the real on-disk store before and after — "the-/// dry run never wrote there" — needed an in-process engine and went with it-/// (openhuman#6161). What survives still distinguishes the two paths, because-/// the echo is `MockMemory`'s and no real adapter produces it: a dry run that-/// had reached the real store would fail the `mem_1` assertion rather than-/// pass it quietly.-#[tokio::test]-async fn memory_node_dry_run_uses_mock_memory_end_to_end() {- let mock_caps = tinyflows::caps::mock::mock_capabilities();-- let remember_graph = trigger_to_memory(json!({- "operation": "remember",- "scope": "flow",- "key": "item-42",- "value": "should never reach the real store in a dry run"- }));- let compiled_remember =- tinyflows::compiler::compile(&remember_graph).expect("compile remember graph");- let remember_outcome = tinyflows::engine::run(&compiled_remember, Value::Null, &mock_caps)- .await- .expect("dry-run remember should succeed against MockMemory");- assert_eq!(- remember_outcome.output["nodes"]["mem"]["items"][0]["json"]["json"]["ok"],- json!(true)- );-- let recall_graph = trigger_to_memory(json!({- "operation": "recall",- "scope": "flow",- "query": "item-42"- }));- let compiled_recall =- tinyflows::compiler::compile(&recall_graph).expect("compile recall graph");- let recall_outcome = tinyflows::engine::run(&compiled_recall, Value::Null, &mock_caps)- .await- .expect("dry-run recall should succeed against MockMemory");- let results = recall_outcome.output["nodes"]["mem"]["items"][0]["json"]["json"]["results"]- .as_array()- .cloned()- .unwrap_or_default();- assert!(- results.iter().any(|hit| hit["id"] == json!("mem_1")),- "expected MockMemory's fixed shaped echo (not real-store content), got: {results:?}"- );-}diff --git a/examples/run_memory_doctor.rs b/examples/run_memory_doctor.rsdeleted file mode 100644index c64a6be25b..0000000000--- a/examples/run_memory_doctor.rs+++ /dev/null@@ -1,34 +0,0 @@-//! One-shot memory doctor over the active user's real workspace:-//!-//! cargo run --example run_memory_doctor-//!-//! Run it with NO `OPENHUMAN_WORKSPACE` override for a logged-in install —-//! the loader then resolves the active-user marker exactly like the app and-//! reads `users/<id>/config.toml`. Pointing the env var at a user-scoped-//! workspace instead synthesizes `users/<id>/.openhuman/config.toml`, which-//! does not exist, and the doctor silently reports a default (unconfigured)-//! config. The stderr probe line prints which config actually loaded so a-//! wrong verdict is visible as a wrong path.--#[tokio::main(flavor = "multi_thread")]-async fn main() -> anyhow::Result<()> {- let mut config = openhuman_core::config::Config::load_or_init()- .await- .unwrap_or_default();- config.apply_env_overrides();-- openhuman_core::memory::host::install_memory_event_sink();- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(std::sync::Arc::new(config.clone()));-- eprintln!(- "config_path={} embeddings_provider={:?} embedding_endpoint={:?}",- config.config_path.display(),- config.embeddings_provider,- config.memory_tree.embedding_endpoint,- );-- let report = openhuman_core::memory::tree::health::report::run_doctor(&config).await;- println!("{}", serde_json::to_string_pretty(&report)?);- Ok(())-}diff --git a/examples/run_memory_reconcile.rs b/examples/run_memory_reconcile.rsdeleted file mode 100644index b8c13e75d1..0000000000--- a/examples/run_memory_reconcile.rs+++ /dev/null@@ -1,59 +0,0 @@-//! Kick the sources coverage reconcile (report + execute) and stay alive-//! while the spawned summarise+ingest work drains. Same config-resolution-//! rules as run_memory_doctor: run with NO OPENHUMAN_WORKSPACE override.--#[tokio::main(flavor = "multi_thread")]-async fn main() -> anyhow::Result<()> {- let mut config = openhuman_core::config::Config::load_or_init()- .await- .unwrap_or_default();- config.apply_env_overrides();- eprintln!("config_path={}", config.config_path.display());-- openhuman_core::memory::host::install_memory_event_sink();- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(std::sync::Arc::new(config.clone()));-- let request = openhuman_core::memory::sources::rpc::ReconcileRequest {- source_id: None,- execute: true,- };- let outcome = openhuman_core::memory::sources::rpc::reconcile_rpc(request)- .await- .map_err(|e| anyhow::anyhow!(e))?;- println!("{}", serde_json::to_string_pretty(&outcome.value)?);-- // The execute arm spawns background summarise+ingest; exiting now would- // kill it. Hold the process until the pending count stops moving.- let mut last = u64::MAX;- for i in 0..60 {- tokio::time::sleep(std::time::Duration::from_secs(15)).await;- let report = openhuman_core::memory::sources::rpc::reconcile_rpc(- openhuman_core::memory::sources::rpc::ReconcileRequest {- source_id: None,- execute: false,- },- )- .await- .map_err(|e| anyhow::anyhow!(e))?;- let pending: u64 = serde_json::to_value(&report.value)?- .get("scopes")- .and_then(|s| s.as_array())- .map(|rows| {- rows.iter()- .filter_map(|r| r.get("pending").and_then(|p| p.as_u64()))- .sum()- })- .unwrap_or(0);- eprintln!("t+{}s pending={pending}", (i + 1) * 15);- if pending == 0 || pending == last {- if pending == 0 {- break;- }- // Two identical non-zero readings in a row: still draining or- // stalled — keep waiting either way, the cap bounds us.- }- last = pending;- }- Ok(())-}diff --git a/tests/in_process/memory_graph_roundtrip_e2e.rs b/tests/in_process/memory_graph_roundtrip_e2e.rsdeleted file mode 100644index d8c6f0929b..0000000000--- a/tests/in_process/memory_graph_roundtrip_e2e.rs+++ /dev/null@@ -1,435 +0,0 @@-//! Knowledge-graph relation round trip over the real JSON-RPC router.-//!-//! # Why this target exists-//!-//! `tests/memory_graph_sync_e2e.rs` was deleted in `cc99ba9c67` ("build(memory):-//! cut the engine out of the test build", 2026-09-09) along with seventeen other-//! test files, because it drove `tinymemory_core` directly and the engine left-//! `[dev-dependencies]` in that commit. The deletion was structural — nothing-//! decided the behaviour had stopped mattering — and nothing replaced it.-//! Matrix row 11.1.1 records the hole as "the former graph-sync E2E was removed".-//!-//! # What was and was not left behind-//!-//! Two things DO cover part of this ground, and this file deliberately does not-//! duplicate them:-//!-//! * `memory::ops::kv_graph_tests::graph_handlers_roundtrip_relation_rows` is a-//! unit test that upserts a relation and queries it back through a real-//! module-backed provider. It calls the `ops` functions **directly**, so it-//! proves the handler wiring but never touches JSON-RPC dispatch or the-//! `serde` layer that builds `GraphUpsertParams` / `GraphQueryParams` from a-//! wire payload.-//! * `tests/in_process/worker_c_modules_e2e.rs` names `openhuman.memory_graph_upsert` and-//! `openhuman.memory_graph_query` in a 68-method loop that calls each with-//! `json!({})` and asserts `assert_rpc_completed`. That helper tolerates an-//! error response as long as it is not `unknown method:`, which is the-//! strongest thing a probe with no arguments can honestly claim. It is a-//! registration check and cannot observe a graph that writes and never reads-//! back.-//!-//! So what has no coverage at all, and is what this file asserts:-//!-//! 1. The **wire path** — that a relation posted as JSON to `/rpc` survives-//! deserialisation, dispatch, the guard, the module and serialisation back-//! out. Both params structs take `namespace` as `#[serde(default)] Option`,-//! so a wire payload takes a different path through serde than a-//! hand-built struct literal does.-//! 2. **Namespace isolation** — that a relation stored under one namespace is-//! not returned when querying another.-//!-//! On (2): the deleted test asserted `all_rows.len() >= graph_rows.len()`, i.e.-//! that an unfiltered query is a superset of a namespace-scoped one. That-//! assertion is **weak on its own** — a driver that ignored the namespace filter-//! entirely would return everything for both queries and still satisfy it. This-//! file keeps the superset check because it pins the documented relationship,-//! and adds the isolation check that actually fails when the filter breaks.-//!-//! Deliberately NOT covered here: `memory_tree_graph_export`. Despite the name-//! it exports the summary-tree / contacts graph-//! (`memory::read_rpc::graph::graph_export_rpc`), not the relation triples-//! `graph_upsert` writes. It needs its own case.-//!-//! No network: the config points `api_url` at a closed port and disables-//! embeddings, and every assertion is local.-//!-//! # Running it-//!-//! ```text-//! cargo test -p openhuman-cli --features modules --test in_process_all-//! ```-//!-//! **`--features modules` is required.** `openhuman-cli`'s `modules` feature is-//! NOT in its `default` set (`crates/openhuman-cli/Cargo.toml:415`, `:423`), and-//! without it `modules::memory::set_modules_policy` is `#[cfg]`-compiled away —-//! so `ensure_memory_seams` becomes a silent no-op and every graph call answers-//! "the module host policy was never published". The memory driver is-//! module-backed, so there is no non-module path to assert against. The same-//! applies to the sibling `tests/memory_roundtrip_e2e.rs`, which does not say-//! so and fails 6/6 locally without the flag; that is environmental, not a-//! defect in either file. CI's `rust-e2e` lane supplies both the feature and a-//! built `TINYMEMORY_TEST_MODULE`.-//!-//! A large stack is also needed — `RUST_MIN_STACK=67108864` — because-//! publishing the policy touches deeply nested config types.--use crate::env_guard::env_lock;-use crate::env_guard::EnvVarGuard;-use crate::rpc_auth::ensure_rpc_auth;-use crate::rpc_harness::{ok, rpc};-use std::path::Path;-use std::sync::{Arc, OnceLock};--use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--use openhuman_rpc::server::build_core_http_router;--static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();-/// One tempdir shared by every test in this target.-///-/// `set_modules_policy` publishes a process-global policy exactly once, so the-/// workspace it names must be stable for the whole binary. A per-test tempdir-/// would leave tests 2..n writing through a policy that points at test 1's-/// directory. Test isolation comes from the unique namespace each test-/// generates instead.-static TEST_ROOT: OnceLock<TempDir> = OnceLock::new();--// ── Env isolation ────────────────────────────────────────────────────--fn test_root() -> &'static TempDir {- TEST_ROOT.get_or_init(|| tempdir().expect("memory graph roundtrip tempdir"))-}--/// Publish the module host policy the memory module is loaded through.-///-/// Without this every graph call answers "the module host policy was never-/// published, so module 'tinymemory' cannot be loaded" — the memory driver is-/// module-backed, and the HTTP router alone does not boot it. Mirrors-/// `tests/memory_roundtrip_e2e.rs::ensure_memory_seams`, including the larger-/// stack: publishing the policy touches deeply nested config types that-/// overflow the default 2 MiB test-thread stack.-fn ensure_memory_seams(workspace: &Path) {- MEMORY_SEAMS_INIT.get_or_init(|| {- let workspace = workspace.to_path_buf();- std::thread::Builder::new()- .name("memory-graph-roundtrip-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(move || {- let config = Arc::new(openhuman_core::config::Config {- workspace_dir: workspace.clone(),- action_dir: workspace.clone(),- config_path: workspace.join("config.toml"),- ..openhuman_core::config::Config::default()- });- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(config);- })- .expect("spawn memory graph seam installer")- .join()- .expect("memory graph seam installer panicked");- });-}--/// Config for a memory-backed core with no network reachability.-///-/// Note what is deliberately ABSENT: `[memory] provider = "none"`. Several-/// sibling suites set it, which binds the null driver — and the null driver-/// answers `graph_upsert` with "memory driver does not support the graph-/// family", so a suite that set it would assert nothing about a graph. The-/// default binding is the `tinymemory` module, which is what production uses-/// and what this file needs.-fn write_config(openhuman_dir: &Path) {- std::fs::create_dir_all(openhuman_dir).expect("create .openhuman");- let cfg = r#"api_url = "http://127.0.0.1:9"-default_model = "memory-graph-roundtrip-e2e-model"-default_temperature = 0.2--[secrets]-encrypt = false--[local_ai]-enabled = false--[memory_tree]-embedding_strict = false-"#;- std::fs::write(openhuman_dir.join("config.toml"), cfg).expect("write config.toml");- let _: openhuman_core::config::Config =- toml::from_str(cfg).expect("test config must match schema");-}--struct Harness {- rpc_base: String,- _guards: Vec<EnvVarGuard>,- join: tokio::task::JoinHandle<Result<(), std::io::Error>>,-}--impl Drop for Harness {- fn drop(&mut self) {- self.join.abort();- }-}--async fn setup() -> Harness {- ensure_rpc_auth();-- let tmp = test_root();- let home = tmp.path();- write_config(&home.join(".openhuman"));- let workspace = home.join("workspace");- std::fs::create_dir_all(&workspace).expect("create workspace dir");- ensure_memory_seams(&workspace);-- let guards = vec![- EnvVarGuard::set_to_path("HOME", home),- EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),- EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),- EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_ENDPOINT", ""),- EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_MODEL", ""),- ];-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind rpc listener");- let addr = listener.local_addr().expect("rpc listener addr");- let router = build_core_http_router(false);- let join = tokio::spawn(async move { axum::serve(listener, router).await });-- Harness {- rpc_base: format!("http://{addr}"),- _guards: guards,- join,- }-}--/// Controllers wrap their payload in `{data|result}`; unwrap one level if present.-fn payload<'a>(value: &'a Value, context: &str) -> &'a Value {- let outer = ok(value, context);- outer- .get("data")- .or_else(|| outer.get("result"))- .unwrap_or(outer)-}--fn rows<'a>(value: &'a Value, context: &str) -> &'a Vec<Value> {- payload(value, context)- .as_array()- .unwrap_or_else(|| panic!("{context}: expected an array of relation rows: {value}"))-}--/// A namespace unique per run, so a shared workspace cannot make one test-/// observe another's rows and call it a pass.-fn unique_namespace(prefix: &str) -> String {- format!(- "{prefix}-{}",- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .expect("clock")- .as_nanos()- )-}--fn relation_matches(row: &Value, subject: &str, predicate: &str, object: &str) -> bool {- let field = |name: &str| {- row.get(name)- .and_then(Value::as_str)- .unwrap_or_default()- .to_ascii_lowercase()- };- // Case-insensitive on purpose: entity-name casing is the driver's policy,- // not the contract's. TinyCortex upper-cases entity names, and pinning one- // engine's normalisation from the host would fail a second driver that- // preserved case — this test is about the wire path, not normalisation.- field("subject") == subject.to_ascii_lowercase()- && field("predicate") == predicate.to_ascii_lowercase()- && field("object") == object.to_ascii_lowercase()-}--// ── Tests ────────────────────────────────────────────────────────────--/// 11.1.1 — the relation survives the whole wire path and comes back.-///-/// The unit test in `kv_graph_tests.rs` builds `GraphUpsertParams` as a struct-/// literal. This one posts JSON, so it is the only thing that exercises the-/// `#[serde(default)] Option<String>` namespace field, the dispatch table entry-/// and the response serialisation.-#[tokio::test]-async fn graph_relation_survives_the_json_rpc_round_trip() {- let _lock = env_lock();- let harness = setup().await;- let namespace = unique_namespace("graph-rt");-- let upsert = rpc(- &harness.rpc_base,- 1,- "openhuman.memory_graph_upsert",- json!({- "namespace": namespace,- "subject": "ALICE",- "predicate": "WORKS_AT",- "object": "ACME_CORP",- "attrs": {"source": "memory-graph-roundtrip-e2e", "confidence": 0.9},- }),- )- .await;- assert_eq!(- payload(&upsert, "memory_graph_upsert"),- &json!(true),- "memory_graph_upsert should report the relation was written"- );-- let queried = rpc(- &harness.rpc_base,- 2,- "openhuman.memory_graph_query",- json!({ "namespace": namespace }),- )- .await;- let relations = rows(&queried, "memory_graph_query");-- assert!(- relations- .iter()- .any(|row| relation_matches(row, "ALICE", "WORKS_AT", "ACME_CORP")),- "memory_graph_query for namespace {namespace} should return the ALICE -[WORKS_AT]-> \- ACME_CORP relation that memory_graph_upsert just wrote, but returned {relations:?}"- );-}--/// 11.1.1 — a namespace-scoped query must not leak another namespace's rows.-///-/// This is the assertion the deleted `memory_graph_sync_e2e.rs` did NOT make.-/// It asserted only `graph_query_all >= graph_query_namespace`, which a driver-/// that ignored the namespace filter altogether would also satisfy — both-/// queries would return everything. Isolation is what actually breaks when the-/// filter breaks.-#[tokio::test]-async fn graph_query_does_not_leak_relations_across_namespaces() {- let _lock = env_lock();- let harness = setup().await;- let mine = unique_namespace("graph-mine");- let theirs = unique_namespace("graph-theirs");-- rpc(- &harness.rpc_base,- 1,- "openhuman.memory_graph_upsert",- json!({- "namespace": mine,- "subject": "ALICE",- "predicate": "WORKS_AT",- "object": "ACME_CORP",- "attrs": {},- }),- )- .await;- rpc(- &harness.rpc_base,- 2,- "openhuman.memory_graph_upsert",- json!({- "namespace": theirs,- "subject": "MALLORY",- "predicate": "WORKS_AT",- "object": "OTHER_CORP",- "attrs": {},- }),- )- .await;-- let scoped = rpc(- &harness.rpc_base,- 3,- "openhuman.memory_graph_query",- json!({ "namespace": mine }),- )- .await;- let scoped_rows = rows(&scoped, "memory_graph_query(mine)");-- assert!(- scoped_rows- .iter()- .any(|row| relation_matches(row, "ALICE", "WORKS_AT", "ACME_CORP")),- "the namespace-scoped query should still return its own relation — \- got {scoped_rows:?}"- );- assert!(- !scoped_rows- .iter()- .any(|row| relation_matches(row, "MALLORY", "WORKS_AT", "OTHER_CORP")),- "memory_graph_query scoped to {mine} leaked a relation stored under {theirs}; the \- namespace filter is not being applied — got {scoped_rows:?}"- );-}--/// 11.1.1 — the superset relationship the deleted suite pinned.-///-/// Kept because it is the documented relationship between a filtered and an-/// unfiltered query, and because it is the half that catches an unfiltered-/// query which silently scopes itself to something. On its own it is weak (see-/// the module docs); it is paired with the isolation test above, not a-/// substitute for it.-#[tokio::test]-async fn unfiltered_graph_query_is_a_superset_of_the_namespace_scoped_query() {- let _lock = env_lock();- let harness = setup().await;- let namespace = unique_namespace("graph-superset");-- rpc(- &harness.rpc_base,- 1,- "openhuman.memory_graph_upsert",- json!({- "namespace": namespace,- "subject": "ALICE",- "predicate": "OWNS",- "object": "ATLAS",- "attrs": {},- }),- )- .await;-- let scoped = rpc(- &harness.rpc_base,- 2,- "openhuman.memory_graph_query",- json!({ "namespace": namespace }),- )- .await;- let scoped_rows = rows(&scoped, "memory_graph_query(scoped)").clone();- assert!(- !scoped_rows.is_empty(),- "the namespace-scoped query returned nothing, so the superset assertion below would \- be vacuous — the upsert did not land"- );-- // `namespace` omitted entirely, which is the `#[serde(default)]` path.- let unfiltered = rpc(- &harness.rpc_base,- 3,- "openhuman.memory_graph_query",- json!({}),- )- .await;- let unfiltered_rows = rows(&unfiltered, "memory_graph_query(unfiltered)");-- assert!(- unfiltered_rows.len() >= scoped_rows.len(),- "an unfiltered memory_graph_query returned {} rows, fewer than the {} rows the query \- scoped to {namespace} returned — the unfiltered read is scoping itself to something",- unfiltered_rows.len(),- scoped_rows.len()- );- assert!(- unfiltered_rows- .iter()- .any(|row| relation_matches(row, "ALICE", "OWNS", "ATLAS")),- "the unfiltered query should contain the relation the scoped query found — \- got {unfiltered_rows:?}"- );-}diff --git a/tests/in_process/memory_sources_e2e.rs b/tests/in_process/memory_sources_e2e.rsdeleted file mode 100644index 514e4bf163..0000000000--- a/tests/in_process/memory_sources_e2e.rs+++ /dev/null@@ -1,1321 +0,0 @@-//! E2E tests for the memory_sources domain.-//!-//! Boots a real axum JSON-RPC server against an isolated workspace and-//! exercises the full user flow: add source → list → list_items →-//! read_item → ingest into memory tree → verify chunks indexed.-//!-//! Run with: `cargo test -p openhuman-cli --test in_process_all`--use crate::env_guard::env_lock;-use crate::env_guard::EnvVarGuard;-use crate::memory_rpc::{ok, serve, write_config};-use crate::rpc_auth::rpc_token;-use std::path::Path;-use std::sync::OnceLock;-use std::time::Duration;--use axum::http::header::AUTHORIZATION;-use serde_json::{json, Value};-use tempfile::tempdir;--static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();--fn test_home() -> &'static Path {- TEST_HOME- .get_or_init(|| tempdir().expect("memory sources tempdir"))- .path()-}--async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(30))- .build()- .expect("client");- let body = json!({- "jsonrpc": "2.0",- "id": id,- "method": method,- "params": params,- });- let url = format!("{}/rpc", base.trim_end_matches('/'));- let resp = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))- .json(&body)- .send()- .await- .unwrap_or_else(|e| panic!("POST {url}: {e}"));- assert!(- resp.status().is_success(),- "HTTP error {} for {method}",- resp.status(),- );- resp.json::<Value>()- .await- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))-}--// ── Tests ─────────────────────────────────────────────────────────--#[tokio::test]-async fn memory_sources_crud_and_folder_read_flow() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- // Create a folder with test markdown files.- let notes_dir = home.join("test-notes");- std::fs::create_dir_all(¬es_dir).expect("mkdir notes");- std::fs::write(- notes_dir.join("architecture.md"),- "# System Architecture\n\n\- The platform uses microservices with three core services.\n\n\- ## Auth Service\n\- Handles OAuth2 flows and JWT rotation. Contact: [email protected]\n\n\- ## Data Pipeline\n\- Event-driven pipeline using Kafka. Throughput: ~50k events/sec. \- Owner: [email protected]\n\n\- Last reviewed: 2025-12-15 by the platform team.",- )- .expect("write architecture.md");-- std::fs::write(- notes_dir.join("runbook.md"),- "# Incident Runbook\n\n\- ## P1: Database Connection Pool Exhaustion\n\- 1. Check connection count via pg_stat_activity\n\- 2. Scale read replicas if > 90% utilization\n\- 3. Escalate to [email protected] if write-primary affected\n\n\- Last updated: 2025-11-30",- )- .expect("write runbook.md");-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // ── Step 1: list sources (empty initially) ──-- let list0 = rpc(&rpc_base, 1, "openhuman.memory_sources_list", json!({})).await;- let list0_result = ok(&list0, "initial list");- let sources = list0_result- .get("sources")- .and_then(Value::as_array)- .expect("sources array");- assert!(sources.is_empty(), "should start with no sources");-- // ── Step 2: add a folder source ──-- let add = rpc(- &rpc_base,- 2,- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Test Research Notes",- "path": notes_dir.to_string_lossy(),- "glob": "**/*.md",- }),- )- .await;- let add_result = ok(&add, "add folder source");- let source = add_result.get("source").expect("source in add response");- let source_id = source.get("id").and_then(Value::as_str).expect("source id");- assert_eq!(source.get("kind").and_then(Value::as_str), Some("folder"));- assert_eq!(- source.get("label").and_then(Value::as_str),- Some("Test Research Notes")- );- assert_eq!(source.get("enabled"), Some(&json!(true)));-- // ── Step 3: list sources (now has 1) ──-- let list1 = rpc(&rpc_base, 3, "openhuman.memory_sources_list", json!({})).await;- let list1_result = ok(&list1, "list after add");- let sources = list1_result- .get("sources")- .and_then(Value::as_array)- .expect("sources array");- assert_eq!(sources.len(), 1);-- // ── Step 4: get source by id ──-- let get = rpc(- &rpc_base,- 4,- "openhuman.memory_sources_get",- json!({ "id": source_id }),- )- .await;- let get_result = ok(&get, "get source");- let fetched = get_result.get("source").expect("source");- assert_eq!(fetched.get("id").and_then(Value::as_str), Some(source_id));-- // ── Step 5: list items from the folder source ──-- let items_resp = rpc(- &rpc_base,- 5,- "openhuman.memory_sources_list_items",- json!({ "source_id": source_id }),- )- .await;- let items_result = ok(&items_resp, "list_items");- let items = items_result- .get("items")- .and_then(Value::as_array)- .expect("items array");- assert_eq!(items.len(), 2, "should list 2 markdown files");-- let item_ids: Vec<&str> = items- .iter()- .filter_map(|i| i.get("id").and_then(Value::as_str))- .collect();- assert!(item_ids.contains(&"architecture.md"));- assert!(item_ids.contains(&"runbook.md"));-- // ── Step 6: read one item's content ──-- let read = rpc(- &rpc_base,- 6,- "openhuman.memory_sources_read_item",- json!({- "source_id": source_id,- "item_id": "architecture.md",- }),- )- .await;- let read_result = ok(&read, "read_item");- let content = read_result.get("content").expect("content");- let body = content.get("body").and_then(Value::as_str).expect("body");- assert!(body.contains("System Architecture"));- assert!(body.contains("[email protected]"));- assert_eq!(- content.get("content_type").and_then(Value::as_str),- Some("markdown")- );-- // ── Step 7: ingest the content into the memory tree ──-- let ingest = rpc(- &rpc_base,- 7,- "openhuman.memory_tree_ingest",- json!({- "source_kind": "document",- "source_id": format!("memory_sources:{source_id}:architecture.md"),- "owner": "user",- "tags": ["memory_sources", "folder"],- "payload": {- "provider": "memory_sources",- "title": "System Architecture",- "body": body,- },- }),- )- .await;- let ingest_result = ok(&ingest, "memory_tree ingest");- let chunks_written = ingest_result- .get("chunks_written")- .and_then(Value::as_u64)- .unwrap_or(0);- assert!(- chunks_written >= 1,- "should ingest at least 1 chunk, got {chunks_written}; full result: {ingest_result}"- );-- // ── Step 8: verify chunks exist via list_sources ──-- let ls = rpc(- &rpc_base,- 8,- "openhuman.memory_tree_list_sources",- json!({}),- )- .await;- let ls_result = ok(&ls, "memory_tree list_sources");- // list_sources returns {sources: [...]} — but some RPCs wrap it differently.- let mem_sources = if let Some(arr) = ls_result.as_array() {- arr.clone()- } else if let Some(arr) = ls_result.get("sources").and_then(Value::as_array) {- arr.clone()- } else {- panic!("expected sources array in: {ls_result}");- };- assert!(- !mem_sources.is_empty(),- "memory tree should have at least one source after ingest"- );-- // ── Step 9: update source label ──-- let update = rpc(- &rpc_base,- 9,- "openhuman.memory_sources_update",- json!({- "id": source_id,- "label": "Renamed Notes",- }),- )- .await;- let update_result = ok(&update, "update source");- assert_eq!(- update_result- .get("source")- .and_then(|s| s.get("label"))- .and_then(Value::as_str),- Some("Renamed Notes")- );-- // ── Step 10: disable source ──-- let disable = rpc(- &rpc_base,- 10,- "openhuman.memory_sources_update",- json!({- "id": source_id,- "enabled": false,- }),- )- .await;- let disable_result = ok(&disable, "disable source");- assert_eq!(- disable_result.get("source").and_then(|s| s.get("enabled")),- Some(&json!(false))- );-- // ── Step 11: remove source ──-- let remove = rpc(- &rpc_base,- 11,- "openhuman.memory_sources_remove",- json!({ "id": source_id }),- )- .await;- let remove_result = ok(&remove, "remove source");- assert_eq!(remove_result.get("removed"), Some(&json!(true)));-- // Verify it's gone.- let list_final = rpc(&rpc_base, 12, "openhuman.memory_sources_list", json!({})).await;- let final_sources = ok(&list_final, "final list")- .get("sources")- .and_then(Value::as_array)- .expect("sources")- .len();- assert_eq!(final_sources, 0, "source should be removed");-- // ── Step 12: removing again is idempotent ──-- let remove_again = rpc(- &rpc_base,- 13,- "openhuman.memory_sources_remove",- json!({ "id": source_id }),- )- .await;- let remove_again_result = ok(&remove_again, "remove again");- assert_eq!(remove_again_result.get("removed"), Some(&json!(false)));-- rpc_join.abort();-}--#[tokio::test]-async fn memory_sources_validation_rejects_bad_input() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // Folder source without path → should error.- let bad_add = rpc(- &rpc_base,- 20,- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Missing path",- }),- )- .await;- assert!(- bad_add.get("error").is_some(),- "adding folder without path should fail: {bad_add}"- );-- // GitHub source without url → should error.- let bad_gh = rpc(- &rpc_base,- 21,- "openhuman.memory_sources_add",- json!({- "kind": "github_repo",- "label": "No URL",- }),- )- .await;- assert!(- bad_gh.get("error").is_some(),- "adding github_repo without url should fail: {bad_gh}"- );-- // list_items for nonexistent source → should error.- let bad_items = rpc(- &rpc_base,- 22,- "openhuman.memory_sources_list_items",- json!({ "source_id": "nonexistent" }),- )- .await;- assert!(- bad_items.get("error").is_some(),- "list_items for missing source should fail: {bad_items}"- );-- rpc_join.abort();-}--/// GitHub source E2E: add a public repo → list_items (commits/issues/PRs)-/// → read one commit and one issue → ingest into memory tree.-///-/// Requires network + `gh` CLI (or unauthenticated GitHub API access).-/// The test targets a small, stable public repo so API responses are-/// predictable. Kept out of the default run so CI without-/// outbound GitHub access doesn't fail on rate limits or transient-/// network blips. `#[ignore]`d so it reports as ignored rather than passing-/// without asserting. Run locally with:-/// cargo test -p openhuman-cli --test in_process_all \-/// memory_sources_github_repo_activity_flow -- --ignored-#[tokio::test]-#[ignore = "needs outbound network to GitHub (kelseyhightower/nocode via the gh CLI / GitHub API); not run in CI. Run: cargo test -p openhuman-cli --test in_process_all memory_sources_github_repo_activity_flow -- --ignored"]-async fn memory_sources_github_repo_activity_flow() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // ── Step 1: add a GitHub repo source ──-- let add = rpc(- &rpc_base,- 100,- "openhuman.memory_sources_add",- json!({- "kind": "github_repo",- "label": "kelseyhightower/nocode",- "url": "https://github.com/kelseyhightower/nocode",- }),- )- .await;- let add_result = ok(&add, "add github source");- let source = add_result.get("source").expect("source");- let source_id = source.get("id").and_then(Value::as_str).expect("id");- assert_eq!(- source.get("kind").and_then(Value::as_str),- Some("github_repo")- );-- // ── Step 2: list items — should return commits, issues, PRs ──-- let items_resp = rpc(- &rpc_base,- 101,- "openhuman.memory_sources_list_items",- json!({ "source_id": source_id }),- )- .await;- let items_result = ok(&items_resp, "github list_items");- let items = items_result- .get("items")- .and_then(Value::as_array)- .expect("items array");-- assert!(- !items.is_empty(),- "github repo should have at least some activity items"- );-- let has_commits = items.iter().any(|i| {- i.get("id")- .and_then(Value::as_str)- .unwrap_or("")- .starts_with("commit:")- });- assert!(has_commits, "should have commit items");-- // ── Step 3: read a commit ──-- let commit_item = items- .iter()- .find(|i| {- i.get("id")- .and_then(Value::as_str)- .unwrap_or("")- .starts_with("commit:")- })- .expect("at least one commit");- let commit_id = commit_item- .get("id")- .and_then(Value::as_str)- .expect("commit id");-- let read_commit = rpc(- &rpc_base,- 102,- "openhuman.memory_sources_read_item",- json!({- "source_id": source_id,- "item_id": commit_id,- }),- )- .await;- let commit_content = ok(&read_commit, "read commit");- let content = commit_content.get("content").expect("content");- let body = content.get("body").and_then(Value::as_str).expect("body");- assert!(body.contains("Commit:"), "commit body should have header");- assert!(body.contains("SHA:"), "commit body should have SHA");- assert_eq!(- content.get("content_type").and_then(Value::as_str),- Some("markdown")- );-- // ── Step 4: ingest the commit into memory tree ──-- let ingest = rpc(- &rpc_base,- 103,- "openhuman.memory_tree_ingest",- json!({- "source_kind": "document",- "source_id": format!("github:{source_id}:{commit_id}"),- "owner": "user",- "tags": ["memory_sources", "github", "commit"],- "payload": {- "provider": "github",- "title": commit_item.get("title").and_then(Value::as_str).unwrap_or("commit"),- "body": body,- },- }),- )- .await;- let ingest_result = ok(&ingest, "ingest github commit");- let chunks = ingest_result- .get("chunks_written")- .and_then(Value::as_u64)- .unwrap_or(0);- assert!(- chunks >= 1,- "should ingest at least 1 chunk from commit, got {chunks}"- );-- // ── Step 5: read an issue if one exists ──-- if let Some(issue_item) = items.iter().find(|i| {- i.get("id")- .and_then(Value::as_str)- .unwrap_or("")- .starts_with("issue:")- }) {- let issue_id = issue_item- .get("id")- .and_then(Value::as_str)- .expect("issue id");-- let read_issue = rpc(- &rpc_base,- 104,- "openhuman.memory_sources_read_item",- json!({- "source_id": source_id,- "item_id": issue_id,- }),- )- .await;- let issue_content = ok(&read_issue, "read issue");- let icontent = issue_content.get("content").expect("content");- let ibody = icontent.get("body").and_then(Value::as_str).expect("body");- assert!(ibody.contains("Issue #"), "issue body should have header");- assert!(ibody.contains("State:"), "issue body should have state");- }-- // ── Cleanup ──-- let remove = rpc(- &rpc_base,- 105,- "openhuman.memory_sources_remove",- json!({ "id": source_id }),- )- .await;- ok(&remove, "remove github source");-- rpc_join.abort();-}--/// Composio source E2E: add a composio source entry → verify it's in-/// the registry → list_items returns the connection as an item →-/// read_item returns a descriptive placeholder → remove.-///-/// Does NOT require an actual Composio connection — tests the registry-/// and reader behavior with synthetic config.-#[tokio::test]-async fn memory_sources_composio_registry_flow() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // ── Step 1: add a composio source ──-- let add = rpc(- &rpc_base,- 200,- "openhuman.memory_sources_add",- json!({- "kind": "composio",- "label": "Gmail · [email protected]",- "toolkit": "gmail",- "connection_id": "cmp_test_123",- }),- )- .await;- let add_result = ok(&add, "add composio source");- let source = add_result.get("source").expect("source");- let source_id = source.get("id").and_then(Value::as_str).expect("id");- assert_eq!(source.get("kind").and_then(Value::as_str), Some("composio"));- assert_eq!(source.get("toolkit").and_then(Value::as_str), Some("gmail"));- assert_eq!(- source.get("connection_id").and_then(Value::as_str),- Some("cmp_test_123")- );-- // ── Step 2: verify it shows up in list ──-- let list = rpc(&rpc_base, 201, "openhuman.memory_sources_list", json!({})).await;- let list_result = ok(&list, "list with composio");- let sources = list_result- .get("sources")- .and_then(Value::as_array)- .expect("sources");- assert_eq!(sources.len(), 1);- assert_eq!(- sources[0].get("toolkit").and_then(Value::as_str),- Some("gmail")- );-- // ── Step 3: list_items returns the connection as an item ──-- let items = rpc(- &rpc_base,- 202,- "openhuman.memory_sources_list_items",- json!({ "source_id": source_id }),- )- .await;- let items_result = ok(&items, "composio list_items");- let item_list = items_result- .get("items")- .and_then(Value::as_array)- .expect("items");- assert_eq!(item_list.len(), 1);- assert_eq!(- item_list[0].get("id").and_then(Value::as_str),- Some("cmp_test_123")- );-- // ── Step 4: read_item returns descriptive content ──-- let read = rpc(- &rpc_base,- 203,- "openhuman.memory_sources_read_item",- json!({- "source_id": source_id,- "item_id": "cmp_test_123",- }),- )- .await;- let read_result = ok(&read, "composio read_item");- let content = read_result.get("content").expect("content");- let body = content.get("body").and_then(Value::as_str).expect("body");- assert!(- body.contains("gmail"),- "composio read should mention the toolkit"- );-- // ── Step 5: add a second composio source (slack) ──-- let add2 = rpc(- &rpc_base,- 204,- "openhuman.memory_sources_add",- json!({- "kind": "composio",- "label": "Slack · workspace",- "toolkit": "slack",- "connection_id": "cmp_test_456",- }),- )- .await;- let add2_result = ok(&add2, "add slack composio source");- let slack_id = add2_result- .get("source")- .and_then(|s| s.get("id"))- .and_then(Value::as_str)- .expect("slack source id");-- // ── Step 6: list should have both ──-- let list2 = rpc(&rpc_base, 205, "openhuman.memory_sources_list", json!({})).await;- let sources2 = ok(&list2, "list with both")- .get("sources")- .and_then(Value::as_array)- .expect("sources")- .len();- assert_eq!(sources2, 2);-- // ── Step 7: disable gmail, verify it persists ──-- let disable = rpc(- &rpc_base,- 206,- "openhuman.memory_sources_update",- json!({- "id": source_id,- "enabled": false,- }),- )- .await;- let disabled = ok(&disable, "disable gmail");- assert_eq!(- disabled.get("source").and_then(|s| s.get("enabled")),- Some(&json!(false))- );-- // ── Step 8: remove both ──-- for (idx, sid) in [source_id, slack_id].iter().enumerate() {- let r = rpc(- &rpc_base,- 210 + idx as i64,- "openhuman.memory_sources_remove",- json!({ "id": sid }),- )- .await;- ok(&r, &format!("remove {sid}"));- }-- rpc_join.abort();-}--// ─── Relative folder-source paths (openhuman#5830, vendored via PR #5838) ────-//-// `FolderReader` was the only reader in `tinymemory-sources` that ignored the-// workspace it is handed: `PathBuf::from(base_path)` used the configured string-// verbatim, so a RELATIVE path resolved against the host process's current-// working directory. For the desktop app that is the Tauri build directory, so-// a source configured as `docs` looked in `…/crates/openhuman-app/docs`, found-// nothing, and failed on every sync cycle forever.-//-// `resolve_base` now anchors a relative path on the workspace (absolute paths-// are still taken verbatim, so every source configured before the fix resolves-// exactly where it did). The reader is linked into the host as-// `tinymemory_sources::readers::folder`, so this is reachable over the real-// `memory_sources_*` RPC surface.-//-// The pre-existing `memory_sources_crud_and_folder_read_flow` above passes an-// ABSOLUTE path, which is the branch the fix deliberately left alone — it-// cannot catch this.--/// A folder source configured with a RELATIVE path resolves against the-/// workspace, not the process CWD.-#[tokio::test]-async fn memory_sources_folder_relative_path_resolves_against_the_workspace() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- // An explicit workspace makes "the workspace, not the CWD" a decidable- // claim: the files exist only under this directory, and the test process's- // CWD (the crate root) has no `relative-notes` at all.- let workspace = home.join("relative-workspace");- std::fs::create_dir_all(&workspace).expect("mkdir workspace");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace);- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let notes_dir = workspace.join("relative-notes");- std::fs::create_dir_all(¬es_dir).expect("mkdir relative notes");- std::fs::write(- notes_dir.join("brief.md"),- "# Relative Brief\n\nAnchored on the workspace, not the process CWD.",- )- .expect("write brief.md");-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // Note the path: relative, exactly as openhuman#5830 was configured.- let add = rpc(- &rpc_base,- 900,- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Relative Notes",- "path": "relative-notes",- "glob": "**/*.md",- }),- )- .await;- let add_result = ok(&add, "add relative folder source");- let source_id = add_result- .get("source")- .and_then(|s| s.get("id"))- .and_then(Value::as_str)- .expect("source id")- .to_string();-- // THE assertion. Before the fix the reader looked under the CWD, found no- // `relative-notes`, and this call returned a "folder does not exist" error- // rather than an items array.- let items_resp = rpc(- &rpc_base,- 901,- "openhuman.memory_sources_list_items",- json!({ "source_id": source_id }),- )- .await;- let items_result = ok(&items_resp, "list_items for a relative folder source");- let items = items_result- .get("items")- .and_then(Value::as_array)- .expect("items array");- let item_ids: Vec<&str> = items- .iter()- .filter_map(|i| i.get("id").and_then(Value::as_str))- .collect();- assert!(- item_ids.contains(&"brief.md"),- "a relative folder path must resolve against the workspace; got {item_ids:?}"- );-- // And the content actually reads back through the same resolution.- let read = rpc(- &rpc_base,- 902,- "openhuman.memory_sources_read_item",- json!({ "source_id": source_id, "item_id": "brief.md" }),- )- .await;- let read_result = ok(&read, "read_item for a relative folder source");- let body = read_result- .get("content")- .and_then(|c| c.get("body"))- .and_then(Value::as_str)- .expect("body");- assert!(- body.contains("Anchored on the workspace"),- "the resolved file must be the workspace one; got {body:?}"- );-- rpc_join.abort();-}--/// A missing relative folder names **where the reader looked**, not just what-/// it was configured with — the second half of the fix. Reporting `docs` alone-/// is what made openhuman#5830 cost an `lsof` of the running process to-/// diagnose.-#[tokio::test]-async fn memory_sources_missing_relative_folder_reports_the_resolved_path() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let workspace = home.join("missing-folder-workspace");- std::fs::create_dir_all(&workspace).expect("mkdir workspace");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace);- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- let add = rpc(- &rpc_base,- 910,- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Absent",- "path": "no-such-folder",- "glob": "**/*.md",- }),- )- .await;- let source_id = ok(&add, "add absent folder source")- .get("source")- .and_then(|s| s.get("id"))- .and_then(Value::as_str)- .expect("source id")- .to_string();-- let items_resp = rpc(- &rpc_base,- 911,- "openhuman.memory_sources_list_items",- json!({ "source_id": source_id }),- )- .await;-- // The whole response is searched rather than a specific error field: the- // point is that the resolved root reaches the caller at all.- let serialized = items_resp.to_string();- assert!(- serialized.contains("no-such-folder"),- "the error must still name the configured path; got {items_resp}"- );- // The concrete resolved root, not just the phrase "resolved to". A reader- // that still joined on the process CWD, or that emitted something generic- // like "resolved to an unavailable location", would satisfy a phrase-only- // check while keeping the exact diagnostic gap this test exists to close.- let expected_resolved = workspace.join("no-such-folder");- let expected_resolved = expected_resolved.to_string_lossy();- assert!(- serialized.contains("resolved to"),- "a relative path's error must name where the reader looked; got {items_resp}"- );- assert!(- serialized.contains(expected_resolved.as_ref()),- "the resolved root must be the workspace one ({expected_resolved}); got {items_resp}"- );-- rpc_join.abort();-}--/// Regression for #5801, fixed by #5808: `MemorySourceSync::run_source_sync` is-/// a **defaulted** contract member whose default body answers-/// `Unsupported(SourceSync)`. `ModuleMemoryProvider` inherited that default-/// instead of bridging the call, so the user's "Sync now" button reported-/// `unsupported capability: source_sync` on a build whose module could sync-/// perfectly well — while the module's own scheduler, which never crosses this-/// bridge, kept syncing fine.-///-/// A defaulted member that was never bridged is indistinguishable from a-/// bridged one at compile time, which is exactly why the bug shipped. So this-/// asserts on the **runtime** answer.-///-/// The discriminator: `binding::build` binds `module_provider` — i.e.-/// `ModuleMemoryProvider` — whenever the `modules` feature is on, which it is by-/// default, so this RPC really does reach the bridged member. No module artifact-/// is installed in a test run, so a **bridged** member fails while trying to-/// reach the module (a transport/availability failure), whereas an **unbridged**-/// one refuses the capability outright before any transport is attempted. Those-/// two failures are distinguishable in the message, and only the second is the-/// regression.-///-/// Deliberately not asserted: that the sync *succeeds*. That would need a live-/// module artifact and a network fetch, which this lane must not depend on.-/// The bug was never "sync returns the wrong data" — it was "the call is-/// refused before it is attempted", and that is what this pins.-#[tokio::test]-async fn sources_sync_dispatches_to_the_module_rather_than_refusing_the_capability() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let notes_dir = home.join("sync-dispatch-notes");- std::fs::create_dir_all(¬es_dir).expect("mkdir sync-dispatch-notes");- std::fs::write(notes_dir.join("note.md"), "# Note\n\nBody.\n").expect("write note.md");-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- let add = rpc(- &rpc_base,- 901,- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Sync Dispatch Fixture",- "path": notes_dir.to_string_lossy(),- "glob": "**/*.md",- }),- )- .await;- let source = ok(&add, "add sync-dispatch source");- let source = source.get("source").expect("source in add response");- let source_id = source- .get("id")- .and_then(Value::as_str)- .expect("source id")- .to_string();- // The enabled gate in `sync_rpc` returns before the driver is ever asked, so- // a disabled source would make this test vacuous.- assert_eq!(- source.get("enabled"),- Some(&json!(true)),- "fixture must be enabled or sync_rpc short-circuits before reaching the driver"- );-- let sync = rpc(- &rpc_base,- 902,- "openhuman.memory_sources_sync",- json!({ "source_id": source_id }),- )- .await;-- let message = sync- .get("error")- .and_then(|e| e.get("message"))- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();-- assert!(- !message.contains("unsupported capability"),- "memory_sources_sync refused the capability instead of dispatching to the module \- — `run_source_sync` is inheriting its defaulted `Unsupported` body again (#5801). \- Got: {message}"- );- // Pin the specific family too, so a future unrelated `Unsupported` cannot- // satisfy the assertion above by accident.- assert!(- !message.contains("source_sync"),- "memory_sources_sync named the source_sync capability as unsupported (#5801). \- Got: {message}"- );- // The OTHER way the call can be refused before dispatch, and the one the two- // assertions above cannot see. `sync_rpc` resolves- // `binding.provider().as_source_sync()` and bails with- //- // the bound memory driver '<id>' does not serve source sync- //- // (`memory/sources/rpc_part_01.rs:560-564`) when the capability is absent.- // That string carries "source sync" with a SPACE — so it contains neither- // "unsupported capability" nor the underscored "source_sync", and both- // assertions above pass while `run_source_sync` was never reached. Codex- // caught this on #5973; without it the test is green for the exact- // regression it exists to catch, one layer up from the defaulted body.- assert!(- !message.contains("does not serve source sync"),- "memory_sources_sync was refused host-side: the bound provider does not expose \- SourceSync at all, so the bridged member was never reached. This is the same \- class of failure as #5801, one layer up. Got: {message}"- );-- // openhuman#6257: whatever the run's outcome, it leaves a Sync History row.- // A sync that reached the driver and recorded nothing is how Brain › Sync ›- // Sync History stayed empty after every manual sync.- //- // The host's run log is read directly, not only through the history RPC.- // The module can fault inside the sync itself (the call above then answers- // `ModuleUnavailable`), and a faulted driver cannot serve its own audit log- // either, so through the RPC alone the row would be unobservable in exactly- // the run that failed. `write_config` seeds the pre-login `users/local`- // directory, whose workspace this core resolves.- let run_log = openhuman_home- .join("users")- .join("local")- .join("workspace")- .join("state")- .join("memory_sync_runs.jsonl");- let run_log_text = std::fs::read_to_string(&run_log).unwrap_or_else(|e| {- panic!(- "a manual sync must write the host run log at {}: {e}. Sync answered: {sync}",- run_log.display()- )- });- let rows: Vec<Value> = run_log_text- .lines()- .filter_map(|line| serde_json::from_str::<Value>(line).ok())- .filter(|row| row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str()))- .collect();- // Exactly one: a run recorded twice would read as two syncs in the history.- let [row] = rows.as_slice() else {- panic!(- "one manual sync must leave exactly one run row for its source, success or \- failure; found {}. Sync answered: {sync}. Log: {run_log_text}",- rows.len()- );- };- assert_eq!(- row.get("success").and_then(Value::as_bool),- Some(sync.get("error").is_none()),- "the row must carry the run's outcome. Sync answered: {sync}. Row: {row}"- );-- // And through the RPC the panel reads, whenever the driver can serve its- // half. The host's half must always read: only the driver may refuse.- let history = rpc(- &rpc_base,- 904,- "openhuman.memory_sources_sync_audit_log",- json!({}),- )- .await;- match history.get("error") {- None => {- let history = ok(&history, "sync history after a manual sync");- let entries = history- .get("entries")- .and_then(Value::as_array)- .expect("entries array in the sync history");- let named = entries- .iter()- .filter(|row| {- row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str())- })- .count();- assert_eq!(- named, 1,- "the history must include the manual sync's row, once. History: {entries:?}"- );- }- Some(history_error) => {- let history_message = history_error- .get("message")- .and_then(Value::as_str)- .unwrap_or_default();- assert!(- history_message.contains("sync audit log:")- && !history_message.contains("sync run log:"),- "only the driver's audit log may be unreadable here; the host's run log \- must always read. Got: {history_error}"- );- }- }-- let _ = rpc(- &rpc_base,- 903,- "openhuman.memory_sources_remove",- json!({ "id": source_id }),- )- .await;-- rpc_join.abort();-}--/// #5725 routed `reset_tree` and `flush_now` through the `MemoryProvider`-/// contract (`Maintenance::reset_derived_index` / `flush_pending`) instead of-/// reaching into the engine. Nothing exercised either afterwards: in the-/// raw-coverage lane `"flush_now"` and `"reset_tree"` appear only as string-/// literals fed to `memory::schema::schemas(...)` — a schema lookup — and in-/// `worker_c_modules_e2e.rs` they sit in a 68-method loop whose helper-/// (`assert_rpc_completed`) passes on an error response. So both paths could-/// stop reaching a driver entirely and every lane would stay green.-///-/// This drives both RPCs for real and pins the routing: the bound driver must-/// SERVE Maintenance and the call must reach it.-///-/// What is asserted is the host-side refusal, not success. `reset_tree_rpc` and-/// `flush_now_rpc` each resolve `binding.provider().as_maintenance()` and bail-/// with `"driver '<id>' does not serve Maintenance"` when the capability is-/// absent — that message is produced *before* any driver call, so it is the one-/// failure that proves the contract hop did not happen. A driver-side failure-/// (no module artifact in this lane) is a different message and is fine here:-/// it means the call was dispatched, which is the thing under test.-///-/// Deliberately NOT asserted: that rows were deleted or a flush was enqueued.-/// Those need a live module artifact and a network fetch (see FINDING 1 in-/// W3-test-findings.md), and a lane that must not depend on the network cannot-/// honestly pin them.-#[tokio::test]-async fn tree_reset_and_flush_route_through_the_maintenance_contract() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- for (id, method) in [- (921_i64, "openhuman.memory_tree_flush_now"),- (922, "openhuman.memory_tree_reset_tree"),- ] {- let resp = rpc(&rpc_base, id, method, json!({})).await;- let message = resp- .get("error")- .and_then(|e| e.get("message"))- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();-- assert!(- !message.contains("does not serve Maintenance"),- "{method} never reached a driver: the bound provider does not serve the \- Maintenance capability, so the contract hop #5725 introduced is not happening. \- Got: {message}"- );- // A renamed or removed RPC must not read as success. The assertion above- // only excludes one string, so an unknown method — whose message is- // `unknown method: <name>` and contains no "does not serve Maintenance" —- // would satisfy it while nothing was dispatched at all (Codex, #5973).- assert!(- !message.contains("unknown method"),- "{method} is not a registered RPC any more, so this test was asserting \- against a method that no longer exists. Got: {message}"- );- // And the response has to be one of the two shapes a dispatched call can- // produce: a result, or a driver-side error. Anything else means the- // request did not complete.- assert!(- resp.get("result").is_some() || resp.get("error").is_some(),- "{method} returned neither a result nor an error, so nothing was dispatched: {resp}"- );- }-- rpc_join.abort();-}--// ── A2: `openhuman.memory_scheduler_override` ────────────────────────-//-// Gate controller `memory_scheduler_override` had zero references under-// `tests/` or `app/test/` before this test.-//-// The scheduler gate's pauses (`mode = off`, signed-out, battery) exist to stop-// background work the user did not ask for. This RPC is the sanctioned-// exception for work they explicitly did — "process my memory now" — so the-// bound on how long that exception lasts is the whole safety property-// (openhuman#5935). `memory/ops/sync.rs` clamps it host-side:-//-// let seconds = seconds.unwrap_or(600).min(3600);-//-// and the handler reports back the value it *granted*, not the one that was-// asked for. Two regressions are therefore invisible today: dropping the-// `.min(3600)` opens an unbounded background-work window, and reporting the-// requested rather than the granted value makes every surface that displays it-// lie about when maintenance stops.-//-// This goes over JSON-RPC rather than calling the handler directly, because-// with the `modules` feature on the call dispatches into the loaded tinymemory-// module — the same boundary the rest of this file exercises. If the module is-// unavailable the call fails loudly here rather than silently skipping.--/// The clamp is a safety bound, so each case pins the exact granted value.-///-/// `None` → the 600 s default; a value under the ceiling passes through-/// unchanged; a value over the ceiling is cut to 3600. The three expected-/// values are mutually distinct, so no single constant satisfies all three.-#[tokio::test]-async fn scheduler_override_clamps_its_window_and_reports_the_granted_value() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");-- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");-- write_config(&openhuman_home);-- let (rpc_base, _rpc_join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // (requested, granted) — `None` means the parameter is omitted entirely.- let cases: [(Option<u64>, u64); 4] = [- (None, 600), // default- (Some(120), 120), // under the ceiling: untouched- (Some(3600), 3600), // exactly the ceiling: untouched- (Some(99_999), 3600), // over the ceiling: clamped- ];-- for (index, (requested, granted)) in cases.into_iter().enumerate() {- let params = match requested {- Some(seconds) => json!({ "seconds": seconds }),- None => json!({}),- };- let response = rpc(- &rpc_base,- 920 + index as i64,- "openhuman.memory_scheduler_override",- params,- )- .await;- let result = ok(- &response,- &format!("memory_scheduler_override(requested={requested:?})"),- );-- // The gate was actually opened — without this the `seconds` assertion- // below could be satisfied by a handler that echoed a number and did- // nothing, which is precisely the shape of the bug it guards against.- assert_eq!(- result.get("overridden"),- Some(&json!(true)),- "override(requested={requested:?}) did not report overridden=true — got {result}"- );-- let reported = result- .get("seconds")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("no numeric `seconds` in {result}"));- assert_eq!(- reported, granted,- "override(requested={requested:?}) must grant {granted}s and report that granted \- value, not the requested one — got {reported}s. A ceiling that stops clamping \- opens an unbounded background-maintenance window (openhuman#5935)."- );- }-}diff --git a/tests/in_process/memory_tree_health_e2e.rs b/tests/in_process/memory_tree_health_e2e.rsdeleted file mode 100644index 78c381bc7d..0000000000--- a/tests/in_process/memory_tree_health_e2e.rs+++ /dev/null@@ -1,708 +0,0 @@-//! End-to-end cover for the `memory_tree` health and lifecycle controllers.-//!-//! # Why this target exists-//!-//! `memory_tree` reported **5/5, 100%** to-//! `scripts/check-domain-e2e-coverage.mjs` while carrying **31** dispatchable-//! controllers. Discovery read `const NAMESPACE` one file at a time, so it only-//! saw the five declared in `memory/tree/retrieval/schemas.rs` — the other 26-//! live in `memory/schema/{tree_operations,vault_and_pipeline}_schema.rs` and-//! reach their `const` through `use super::*`. A namespace nobody measures is-//! the same fail-open shape as a test filter that matches nothing, except this-//! one had a green tick on it. The gate fix in the same change makes the real-//! figure 24/31; the seven cases below are the gap it exposes.-//!-//! They live in their own target rather than under `tests/raw_coverage/`; the old-//! `memory_goals_people_e2e.rs` fixture that also drove `memory_tree_*` was-//! quarantined under #6382 and has been removed.-//!-//! # What is asserted, and what is not-//!-//! Every case here asserts a claim the handler makes about itself, not that a-//! call returns 200. Where a claim needs state this harness cannot produce —-//! a terminally failed job for `retry_failed` to requeue — the case asserts the-//! cross-method invariant that IS reachable and says so in a comment, rather-//! than asserting `0 == 0` and calling it coverage.--use crate::env_guard::env_lock;-use crate::env_guard::EnvVarGuard;-use crate::memory_rpc::{ok, serve, write_config};-use crate::rpc_auth::rpc_token;-use std::path::Path;-use std::sync::OnceLock;-use std::time::Duration;--use axum::http::header::AUTHORIZATION;-use serde_json::{json, Value};-use tempfile::tempdir;--static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();--fn test_home() -> &'static Path {- TEST_HOME- .get_or_init(|| tempdir().expect("memory tree health tempdir"))- .path()-}--async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(30))- .build()- .expect("client");- let body = json!({- "jsonrpc": "2.0",- "id": id,- "method": method,- "params": params,- });- let url = format!("{}/rpc", base.trim_end_matches('/'));- let resp = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))- .json(&body)- .send()- .await- .unwrap_or_else(|e| panic!("POST {url}: {e}"));- assert!(- resp.status().is_success(),- "HTTP error {} for {method}",- resp.status(),- );- resp.json::<Value>()- .await- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))-}--// ── Tests ──────────────────────────────────--/// Ingest one source under `home`, returning the chunk count written.-async fn ingest_source(base: &str, id: i64, source_id: &str, body: &str) -> u64 {- let response = rpc(- base,- id,- "openhuman.memory_tree_ingest",- json!({- "source_kind": "document",- "source_id": source_id,- "owner": "user",- "tags": ["memory_tree_health_e2e", "document"],- "payload": { "provider": "memory_tree_health_e2e", "title": source_id, "body": body },- }),- )- .await;- ok(&response, &format!("ingest {source_id}"))- .get("chunks_written")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("ingest {source_id} must report chunks_written: {response}"))-}--/// Enough prose that chunking produces at least one chunk per source.-fn body_for(source: &str) -> String {- format!(- "{source} is a durable note used by the memory tree health suite. \- It repeats enough distinct sentences that the chunker has real content to seal. \- The retention policy for {source} is tested by deleting it and observing that \- every other source survives untouched. Structural recall over {source} must \- continue to answer after its siblings are removed."- )-}--/// `memory_tree.doctor` must agree with itself.-///-/// The handler's own schema states the invariant: `healthy` is-/// "True when no stage is blocking (first_blocking_cause is null)". A doctor-/// whose verdict and evidence disagree is worse than no doctor — it is the-/// surface an operator trusts to decide whether memory is working, and the-/// failure mode worth catching is a rewrite that always answers `healthy: true`-/// while `first_blocking_cause` is populated. Asserting the two fields against-/// each other catches that in either direction without needing to force a fault.-#[tokio::test]-async fn memory_tree_doctor_verdict_agrees_with_its_own_evidence() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let response = rpc(&base, 500, "openhuman.memory_tree_doctor", json!({})).await;- let doctor = ok(&response, "memory_tree_doctor");-- let healthy = doctor- .get("healthy")- .and_then(Value::as_bool)- .unwrap_or_else(|| panic!("doctor must report `healthy`: {doctor}"));- // A healthy doctor OMITS the key rather than serialising `null`- // (`skip_serializing_if = "Option::is_none"`), so absent and null are the- // same statement — "nothing is blocking". Treating them differently made- // this case depend on whatever state the store happened to be in.- let blocking = doctor- .get("first_blocking_cause")- .cloned()- .unwrap_or(Value::Null);-- assert_eq!(- healthy,- blocking.is_null(),- "`healthy` is defined as `first_blocking_cause is null`; the two disagree: {doctor}"- );-- // The evidence must actually be there. An empty stage list would make the- // verdict above true by vacuity whatever the pipeline was doing.- let stages = doctor- .get("stages")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("doctor must report a `stages` array: {doctor}"));- assert!(- !stages.is_empty(),- "an empty `stages` array makes the verdict unfalsifiable: {doctor}"- );- for stage in stages {- assert!(- stage.get("stage").and_then(Value::as_str).is_some(),- "every stage row must name its stage: {stage}"- );- assert!(- stage.get("ok").and_then(Value::as_bool).is_some(),- "every stage row must carry a boolean `ok`: {stage}"- );- }-- // And a blocking cause, when present, must be typed rather than bare prose:- // the frontend routes remediation off `remediation_key`.- if !blocking.is_null() {- for field in ["code", "class", "remediation_key"] {- assert!(- blocking.get(field).is_some(),- "a blocking cause must be typed and carry `{field}`: {blocking}"- );- }- }-- // `counters` is what an operator reads next; a stage saying "not ok" with no- // counters is a dead end.- let counters = doctor- .get("counters")- .unwrap_or_else(|| panic!("doctor must report `counters`: {doctor}"));- for field in ["total_chunks", "jobs_ready", "jobs_running", "jobs_failed"] {- assert!(- counters.get(field).and_then(Value::as_u64).is_some(),- "counters must carry a numeric `{field}`: {counters}"- );- }-- rpc_join.abort();-}--/// `memory_tree.delete_source` must delete ONE source, not the neighbourhood.-///-/// Over-deletion is silent data loss: the call reports success either way, and-/// the only difference is the sibling that is no longer there. So the assertion-/// is on the survivor, not on the return value. Two sources are ingested, one is-/// deleted, and the other must still be listed with its chunks intact.-#[tokio::test]-async fn memory_tree_delete_source_removes_only_the_named_source() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let doomed = "memory_tree_health:doomed-source";- let survivor = "memory_tree_health:surviving-source";-- let doomed_chunks = ingest_source(&base, 510, doomed, &body_for(doomed)).await;- let survivor_chunks = ingest_source(&base, 511, survivor, &body_for(survivor)).await;- assert!(- doomed_chunks >= 1 && survivor_chunks >= 1,- "both fixtures must write at least one chunk, or the deletion proves nothing \- (doomed={doomed_chunks}, survivor={survivor_chunks})"- );-- let deleted = rpc(- &base,- 512,- "openhuman.memory_tree_delete_source",- json!({ "source_id": doomed }),- )- .await;- let deleted_result = ok(&deleted, "memory_tree_delete_source");- assert_eq!(- deleted_result.get("deleted").and_then(Value::as_bool),- Some(true),- "deleting a source that exists must report real work: {deleted_result}"- );- assert!(- deleted_result- .get("chunks_removed")- .and_then(Value::as_u64)- .is_some_and(|removed| removed >= 1),- "deleting a source with chunks must remove at least one: {deleted_result}"- );-- // THE POINT: the sibling survived.- let listed = rpc(&base, 513, "openhuman.memory_tree_list_sources", json!({})).await;- let sources = ok(&listed, "memory_tree_list_sources");- let rendered = sources.to_string();- assert!(- rendered.contains(survivor),- "deleting `{doomed}` must leave `{survivor}` in place; list was: {rendered}"- );- assert!(- !rendered.contains(doomed),- "the deleted source must be gone from list_sources; list was: {rendered}"- );-- // Deleting an id that does not exist must be honest about doing nothing,- // rather than reporting success and hiding a typo'd id from the caller.- let absent = rpc(- &base,- 514,- "openhuman.memory_tree_delete_source",- json!({ "source_id": "memory_tree_health:never-ingested" }),- )- .await;- let absent_result = ok(&absent, "memory_tree_delete_source (absent)");- assert_eq!(- absent_result.get("chunks_removed").and_then(Value::as_u64),- Some(0),- "deleting a source that was never ingested must remove nothing: {absent_result}"- );-- rpc_join.abort();-}--/// `vault_health_check` and `pipeline_status` must not contradict each other.-///-/// Two health surfaces over one pipeline. They are read by different callers —-/// onboarding reads the vault snapshot, the memory panel reads the pipeline —-/// and nothing today stops them drifting apart. The invariant asserted here is-/// the one an operator relies on: if `doctor` names a blocking cause, the-/// pipeline must not simultaneously present itself as unblocked.-#[tokio::test]-async fn memory_tree_vault_and_pipeline_health_surfaces_agree() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let vault = rpc(- &base,- 520,- "openhuman.memory_tree_vault_health_check",- json!({}),- )- .await;- let vault_result = ok(&vault, "memory_tree_vault_health_check");- assert!(- vault_result.is_object(),- "the vault snapshot must be an object, not a bare scalar: {vault_result}"- );-- let pipeline = rpc(- &base,- 521,- "openhuman.memory_tree_pipeline_status",- json!({}),- )- .await;- let pipeline_result = ok(&pipeline, "memory_tree_pipeline_status");- assert!(- pipeline_result.is_object(),- "the pipeline snapshot must be an object: {pipeline_result}"- );-- let doctor = ok(- &rpc(&base, 522, "openhuman.memory_tree_doctor", json!({})).await,- "memory_tree_doctor",- );- let blocked = !doctor- .get("first_blocking_cause")- .map(Value::is_null)- .unwrap_or(true);-- if blocked {- // A pipeline that calls itself healthy while the doctor is blocked is the- // drift this case exists to catch.- let pipeline_claims_health = pipeline_result- .get("healthy")- .and_then(Value::as_bool)- .unwrap_or(false);- assert!(- !pipeline_claims_health,- "doctor reports a blocking cause ({:?}) while pipeline_status reports healthy: {pipeline_result}",- doctor.get("first_blocking_cause")- );- }-- rpc_join.abort();-}--/// `memory_tree.retry_failed` must report what it requeued, and not invent work.-///-/// The honest limit of this case, stated rather than hidden: this harness has no-/// way to force a terminally failed `mem_tree_jobs` row, so it cannot prove the-/// requeue path moves a real job. What it CAN prove is the cross-method-/// invariant — `requeued` must never exceed the `jobs_failed` the doctor counted-/// a moment earlier, and a second call with nothing left to requeue must report-/// zero. A handler that returns an invented non-zero count, or that counts the-/// whole job table rather than the failed rows, fails both.-#[tokio::test]-async fn memory_tree_retry_failed_never_requeues_more_than_had_failed() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let before = ok(- &rpc(&base, 530, "openhuman.memory_tree_doctor", json!({})).await,- "memory_tree_doctor (before retry)",- );- let failed_before = before- .get("counters")- .and_then(|counters| counters.get("jobs_failed"))- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("doctor must count jobs_failed: {before}"));-- let retried = rpc(&base, 531, "openhuman.memory_tree_retry_failed", json!({})).await;- let retried_result = ok(&retried, "memory_tree_retry_failed");- let requeued = retried_result- .get("requeued")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("retry_failed must report `requeued`: {retried_result}"));-- assert!(- requeued <= failed_before,- "retry_failed requeued {requeued} jobs but the doctor counted only {failed_before} failed; \- it must requeue failed rows, not the whole job table"- );-- // Nothing is left failed after a requeue, so a second call must be a no-op.- // A handler that re-counts the same rows every time reports non-zero forever.- let again = rpc(&base, 532, "openhuman.memory_tree_retry_failed", json!({})).await;- assert_eq!(- ok(&again, "memory_tree_retry_failed (second call)")- .get("requeued")- .and_then(Value::as_u64),- Some(0),- "a second retry_failed with nothing left to requeue must report 0: {again}"- );-- rpc_join.abort();-}--/// `flush_source` must seal the scope it was given, and echo that scope back.-///-/// The echo is the assertable half: `tree_scope` is documented as "Echo of the-/// source scope", so a handler that flushes a different scope than it was asked-/// to — or silently falls back to a global flush — shows up as a mismatch.-#[tokio::test]-async fn memory_tree_flush_source_seals_only_the_scope_it_was_given() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let scope = "memory_tree_health:flush-scope";- let chunks = ingest_source(&base, 540, scope, &body_for(scope)).await;- assert!(- chunks >= 1,- "the fixture must write a chunk, or there is nothing to seal"- );-- let flushed = rpc(- &base,- 541,- "openhuman.memory_tree_flush_source",- json!({ "source_scope": scope }),- )- .await;- let flushed_result = ok(&flushed, "memory_tree_flush_source");-- assert_eq!(- flushed_result.get("tree_scope").and_then(Value::as_str),- Some(scope),- "flush_source must echo back the scope it sealed, not a different one: {flushed_result}"- );- assert!(- flushed_result- .get("seals_fired")- .and_then(Value::as_u64)- .is_some(),- "flush_source must report how many seal cascades fired: {flushed_result}"- );-- rpc_join.abort();-}--/// `backfill_connector_trees` with `dry_run` must not mutate.-///-/// A dry run that writes is the worst kind of defect in a backfill: the operator-/// ran it precisely to find out what WOULD happen. The chunk total before and-/// after is the observable that proves it, and it is read from `doctor.counters`-/// rather than from the backfill's own return value, so the check does not-/// depend on the code under test telling the truth about itself.-#[tokio::test]-async fn memory_tree_backfill_dry_run_reports_without_writing() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let source = "memory_tree_health:backfill-source";- assert!(- ingest_source(&base, 550, source, &body_for(source)).await >= 1,- "the fixture must write a chunk, or an unchanged total proves nothing"- );-- let chunks_of = |doctor: &Value| -> u64 {- doctor- .get("counters")- .and_then(|counters| counters.get("total_chunks"))- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("doctor must count total_chunks: {doctor}"))- };-- let before = chunks_of(&ok(- &rpc(&base, 551, "openhuman.memory_tree_doctor", json!({})).await,- "doctor (before dry run)",- ));- assert!(- before >= 1,- "the tree must hold at least one chunk before the dry run, or an unchanged \- total is unfalsifiable"- );-- let dry = rpc(- &base,- 552,- "openhuman.memory_tree_backfill_connector_trees",- json!({ "dry_run": true }),- )- .await;- ok(&dry, "memory_tree_backfill_connector_trees (dry run)");-- let after = chunks_of(&ok(- &rpc(&base, 553, "openhuman.memory_tree_doctor", json!({})).await,- "doctor (after dry run)",- ));- assert_eq!(- after, before,- "a dry run must not change the chunk total ({before} -> {after})"- );-- rpc_join.abort();-}--/// `smart_walk` must answer a query over content that was actually ingested.-///-/// The retrieval half of the tree. The assertion is that a query drawn from the-/// ingested body reaches a result set, and that the shape is the documented one-/// — not that a specific chunk ranks first, which would pin the ranker rather-/// than the contract.-#[tokio::test]-async fn memory_tree_smart_walk_answers_over_ingested_content() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- let source = "memory_tree_health:smart-walk-source";- assert!(- ingest_source(&base, 560, source, &body_for(source)).await >= 1,- "the fixture must write a chunk, or the walk has nothing to reach"- );-- let walked = rpc(- &base,- 561,- "openhuman.memory_tree_smart_walk",- json!({ "query": "retention policy", "limit": 5 }),- )- .await;- let result = ok(&walked, "memory_tree_smart_walk");- assert!(- result.is_object() || result.is_array(),- "smart_walk must return a structured result set: {result}"- );-- // `limit` is the caller's bound; a walk that ignores it can flood a prompt.- if let Some(items) = result- .get("results")- .or_else(|| result.get("chunks"))- .and_then(Value::as_array)- {- assert!(- items.len() <= 5,- "smart_walk returned {} items for limit=5: {result}",- items.len()- );- }-- rpc_join.abort();-}--/// `memory.namespace_summaries` — the total must equal the parts, and the parts-/// must be the counts that were actually written.-///-/// Its own description calls this "the verification surface for whether a sync's-/// items actually landed", which makes a wrong total worse than no total: it-/// vindicates a broken sync. `memory/ops/documents.rs` computes-/// `total_documents` as `namespaces.iter().map(|n| n.count).sum()`.-///-/// `total == sum` alone is too weak — an all-zero response satisfies it, and so-/// does a handler that echoes one row's count into every row. So this seeds two-/// namespaces with **different non-zero counts** and asserts each one exactly.-/// Two distinct values is what rules out the echo; a non-zero fixture is what-/// rules out the empty store. (Credit to the parallel `memory_roundtrip_e2e`-/// work for the distinct-counts argument.)-///-/// This is the **controller** test, over JSON-RPC. `tests/memory_roundtrip_e2e.rs`-/// covers the same ground one layer down by calling-/// `openhuman_core::memory::ops::memory_namespace_summaries` directly. Both are-/// worth having and only this one exercises dispatch, parameter decoding and the-/// `Outcome` envelope.-#[tokio::test]-async fn memory_namespace_summaries_counts_each_namespace_it_was_given() {- let _guard = env_lock();- let home = test_home();- let openhuman_home = home.join(".openhuman");- write_config(&openhuman_home);- let _home_guard = EnvVarGuard::set_to_path("HOME", home);- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let _backend = EnvVarGuard::unset("BACKEND_URL");- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");- let (base, rpc_join) = serve().await;-- // Distinct counts on purpose: 2 and 3, so a handler that reports one row's- // count for every row cannot pass.- let small = "memory_tree_health_summaries_small";- let large = "memory_tree_health_summaries_large";- let seeded: [(&str, usize); 2] = [(small, 2), (large, 3)];-- // Start from a known floor so a leftover store cannot make the assertions- // pass for the wrong reason.- for (namespace, _) in seeded {- rpc(- &base,- 580,- "openhuman.memory_clear_namespace",- json!({ "namespace": namespace }),- )- .await;- }-- let mut id = 581;- for (namespace, count) in seeded {- for index in 0..count {- let response = rpc(- &base,- id,- "openhuman.memory_doc_put",- json!({- "namespace": namespace,- "key": format!("{namespace}-doc-{index}"),- "title": format!("{namespace} document {index}"),- "content": format!(- "Document {index} of namespace {namespace}, written by the \- namespace-summaries e2e case so the counts below are ones \- this test put there itself."- ),- }),- )- .await;- ok(&response, &format!("memory_doc_put {namespace}#{index}"));- id += 1;- }- }-- let response = rpc(- &base,- 600,- "openhuman.memory_namespace_summaries",- json!({}),- )- .await;- let summaries = ok(&response, "memory_namespace_summaries");-- let namespaces = summaries- .get("namespaces")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("summaries must carry a `namespaces` array: {summaries}"))- .clone();- let total = summaries- .get("total_documents")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("summaries must carry `total_documents`: {summaries}"));-- let count_for = |wanted: &str| -> u64 {- namespaces- .iter()- .find(|entry| entry.get("namespace").and_then(Value::as_str) == Some(wanted))- .and_then(|entry| entry.get("count").and_then(Value::as_u64))- .unwrap_or_else(|| panic!("namespace `{wanted}` must appear with a count: {summaries}"))- };-- // Each namespace reports the count IT was given, not the other one's.- for (namespace, expected) in seeded {- assert_eq!(- count_for(namespace),- expected as u64,- "namespace `{namespace}` must report the {expected} documents written to it: {summaries}"- );- }-- // And the headline figure is the sum of the rows, not an independent tally- // that can drift from them.- let summed: u64 = namespaces- .iter()- .map(|entry| {- entry- .get("count")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("every namespace row must carry a count: {entry}"))- })- .sum();- assert_eq!(- total, summed,- "total_documents ({total}) must equal the sum of per-namespace counts ({summed}): {summaries}"- );- assert!(- total >= 5,- "the five seeded documents must be included in the total: {summaries}"- );-- rpc_join.abort();-}diff --git a/tests/in_process/tree_summarizer_e2e.rs b/tests/in_process/tree_summarizer_e2e.rsdeleted file mode 100644index ed8f045513..0000000000--- a/tests/in_process/tree_summarizer_e2e.rs+++ /dev/null@@ -1,236 +0,0 @@-//! E2E coverage for the `tree_summarizer` ingestion buffer.-//!-//! Gate controller `tree_summarizer_ingest` had zero references under `tests/`-//! or `app/test/` before this target.-//!-//! The claim under test is a **boundary contract**, which is why this is an RI-//! suite rather than a unit test. `memory/tree/tree_runtime/ops.rs` defaults the-//! timestamp host-side, deliberately, and says why:-//!-//! // Defaulted here rather than driver-side, exactly as before: the reply-//! // echoes the instant the content was filed under, and a timestamp the-//! // driver resolved would disagree with the one reported here by however-//! // long the call took to cross.-//!-//! If that defaulting ever migrates across the bus, the reply starts reporting-//! a different instant than the one the content was actually filed under. The-//! field stays present and stays plausible, so every downstream ordering or-//! dedupe decision keyed on that echo drifts silently. Nothing catches it-//! today.-//!-//! Run with: `cargo test -p openhuman-cli --test in_process_all`--use crate::env_guard::env_lock;-use crate::env_guard::EnvVarGuard;-use crate::memory_rpc::{serve, write_config};-use crate::rpc_auth::rpc_token;-use std::path::{Path, PathBuf};-use std::sync::OnceLock;-use std::time::Duration;--use axum::http::header::AUTHORIZATION;-use chrono::{DateTime, SecondsFormat, TimeZone, Utc};-use serde_json::{json, Value};-use tempfile::TempDir;--const NAMESPACE: &str = "tree-summarizer-e2e";--static TEST_HOME: OnceLock<TempDir> = OnceLock::new();--fn test_home() -> &'static Path {- TEST_HOME- .get_or_init(|| tempfile::tempdir().expect("tree summarizer tempdir"))- .path()-}--async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(30))- .build()- .expect("client");- let url = format!("{}/rpc", base.trim_end_matches('/'));- let resp = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))- .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))- .send()- .await- .unwrap_or_else(|e| panic!("POST {url}: {e}"));- assert!(- resp.status().is_success(),- "HTTP error {} for {method}",- resp.status()- );- resp.json::<Value>()- .await- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))-}--fn ok(v: &Value, ctx: &str) -> Value {- if let Some(err) = v.get("error") {- panic!("{ctx}: JSON-RPC error: {err}");- }- let outer = v- .get("result")- .unwrap_or_else(|| panic!("{ctx}: missing result: {v}"));- // Outcome wraps its payload under an inner "result" alongside "logs".- outer- .get("result")- .cloned()- .unwrap_or_else(|| outer.clone())-}--fn setup() -> (EnvVarGuard, EnvVarGuard, EnvVarGuard, EnvVarGuard, PathBuf) {- let home = test_home();- let openhuman_home = home.join(".openhuman");- let home_guard = EnvVarGuard::set_to_path("HOME", home);- let ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");- let backend = EnvVarGuard::unset("BACKEND_URL");- let vite = EnvVarGuard::unset("VITE_BACKEND_URL");- write_config(&openhuman_home);- (home_guard, ws, backend, vite, openhuman_home)-}--// ── Tests ────────────────────────────────────────────────────────────--/// An explicit `timestamp` is echoed back exactly, not replaced by `now()`.-///-/// The fixture instant is fixed and far in the past, so a handler that resolved-/// its own `now()` could not satisfy this by coincidence.-#[tokio::test]-async fn ingest_echoes_the_caller_supplied_timestamp() {- let _lock = env_lock();- let (_home, _ws, _backend, _vite, _oh) = setup();-- let (rpc_base, _join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // 2021-03-04T05:06:07Z — fixed, and years away from any plausible `now()`.- let fixed: DateTime<Utc> = Utc- .with_ymd_and_hms(2021, 3, 4, 5, 6, 7)- .single()- .expect("fixed fixture instant");- let fixed_rfc3339 = fixed.to_rfc3339_opts(SecondsFormat::Secs, true);-- let before = Utc::now();- let response = rpc(- &rpc_base,- 401,- "openhuman.tree_summarizer_ingest",- json!({- "namespace": NAMESPACE,- "content": "Engineering note filed under a caller-supplied instant.",- "timestamp": fixed_rfc3339,- }),- )- .await;- let result = ok(&response, "tree_summarizer_ingest with explicit timestamp");-- // Fixture guard: if the write did not happen there is nothing to assert- // about, and `buffered` is the handler's own statement that it did.- assert_eq!(- result.get("buffered"),- Some(&json!(true)),- "ingest did not report buffered=true — got {result}"- );-- let echoed = result- .get("timestamp")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("no `timestamp` in {result}"));- let echoed: DateTime<Utc> = DateTime::parse_from_rfc3339(echoed)- .unwrap_or_else(|e| panic!("unparseable timestamp {echoed:?}: {e}"))- .with_timezone(&Utc);-- assert_eq!(- echoed, fixed,- "ingest must echo the instant the caller filed the content under ({fixed}), not one it \- resolved itself. A driver-side default would disagree with the reply by however long the \- call took to cross (memory/tree/tree_runtime/ops.rs)."- );- // Stated separately so a regression that returns `now()` names itself,- // rather than only showing two timestamps that happen to differ.- assert!(- echoed < before,- "echoed timestamp {echoed} is not the fixture instant but a value at or after this \- test started ({before}) — the handler resolved its own clock"- );-- assert_eq!(- result.get("namespace"),- Some(&json!(NAMESPACE)),- "ingest must echo the namespace it filed under — got {result}"- );- assert_eq!(- result.get("has_metadata"),- Some(&json!(false)),- "no metadata was sent, so has_metadata must be false — got {result}"- );- let path = result- .get("path")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("no `path` in {result}"));- assert!(- !path.is_empty(),- "ingest must report the buffer path the driver wrote"- );-}--/// With no `timestamp`, the handler resolves one itself and it lands inside the-/// window this test brackets.-///-/// Bracketing both sides is what makes this non-vacuous: a handler returning a-/// constant, a zero instant or an unparseable string fails.-#[tokio::test]-async fn ingest_without_a_timestamp_files_under_the_host_clock() {- let _lock = env_lock();- let (_home, _ws, _backend, _vite, _oh) = setup();-- let (rpc_base, _join) = serve().await;- tokio::time::sleep(Duration::from_millis(100)).await;-- // One second of slack each side: the assertion is "the host clock", not a- // claim about RPC latency.- let before = Utc::now() - chrono::Duration::seconds(1);- let response = rpc(- &rpc_base,- 402,- "openhuman.tree_summarizer_ingest",- json!({- "namespace": NAMESPACE,- "content": "Engineering note filed without an explicit instant.",- "metadata": { "source": "tree-summarizer-e2e" },- }),- )- .await;- let after = Utc::now() + chrono::Duration::seconds(1);- let result = ok(&response, "tree_summarizer_ingest without timestamp");-- assert_eq!(- result.get("buffered"),- Some(&json!(true)),- "ingest did not report buffered=true — got {result}"- );-- let echoed = result- .get("timestamp")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("no `timestamp` in {result}"));- let echoed: DateTime<Utc> = DateTime::parse_from_rfc3339(echoed)- .unwrap_or_else(|e| panic!("unparseable timestamp {echoed:?}: {e}"))- .with_timezone(&Utc);-- assert!(- echoed >= before && echoed <= after,- "an omitted timestamp must be defaulted to the host clock; {echoed} is outside the \- window [{before}, {after}] this call was made in"- );-- // The metadata this call *did* send must be reflected, so the two tests- // together pin both branches of `has_metadata`.- assert_eq!(- result.get("has_metadata"),- Some(&json!(true)),- "metadata was sent, so has_metadata must be true — got {result}"- );-}diff --git a/tests/memory_engine_e2e.rs b/tests/memory_engine_e2e.rsdeleted file mode 100644index 26555e9078..0000000000--- a/tests/memory_engine_e2e.rs+++ /dev/null@@ -1,364 +0,0 @@-//! Memory-engine selection over JSON-RPC: list, get, set and validation, against-//! a hosted-CortexDB double (see `support/memory_engine_fixture.rs`). Migration-//! is in `memory_engine_migrate_e2e.rs`.-//!-//! ```text-//! RUST_MIN_STACK=67108864 cargo test -p openhuman-cli \-//! --features "$(bash scripts/ci/product-features.sh)" \-//! --test memory_engine_e2e-//! ```--#[path = "support/memory_engine_fixture.rs"]-mod fixture;--use std::sync::atomic::Ordering;--use fixture::*;-use serde_json::json;--#[test]-fn engines_list_and_get_report_the_module_by_default() {- run_on_big_stack("engines-list", || async {- let fx = Fixture::new().await;- let v = fx.call("openhuman.memory_engines_list", json!({})).await;- let list = result_of(&v, "engines_list");- let engines = list["engines"].as_array().expect("engines array");- let ids: Vec<&str> = engines.iter().filter_map(|e| e["id"].as_str()).collect();-- assert_eq!(ids[0], "tinymemory", "module first: {ids:?}");- assert_eq!(engines[0]["label"], "TinyCortex (local)");- for expected in [- "tinyhumans",- "supermemory",- "mem0",- "cognee",- "cortex",- "agentmemory",- ] {- assert!(ids.contains(&expected), "{expected} missing from {ids:?}");- }- assert!(!ids.contains(&"null"), "null must not be offered: {ids:?}");- assert!(- !ids.contains(&"tinycortex"),- "in-memory tinycortex must not be offered: {ids:?}"- );- assert_eq!(list["active"], "tinymemory");- let hosted = engines.iter().find(|e| e["id"] == "tinyhumans").unwrap();- assert_eq!(hosted["hosted"], true);- assert!(hosted["capabilities"]- .as_array()- .unwrap()- .iter()- .any(|c| c == "answer"));-- let state = fx.state().await;- assert_eq!(state["driver"], "tinymemory");- assert_eq!(state["class"], "module");- assert_eq!(state["has_credential"], false);- assert!(state["fell_back_from"].is_null());- assert!(state["last_error"].is_null());- });-}--#[test]-fn engine_set_binds_the_hosted_engine_without_a_restart_and_switches_back() {- run_on_big_stack("engine-set", || async {- let fx = Fixture::new().await;-- let v = fx- .call(- "openhuman.memory_engine_set",- json!({ "driver": "tinyhumans" }),- )- .await;- let state = result_of(&v, "engine_set tinyhumans");- assert_eq!(state["driver"], "tinyhumans", "{state}");- assert_eq!(state["class"], "external");- assert_eq!(- state["has_credential"], true,- "the live api key is the credential"- );- assert_eq!(state["endpoint"], fx.origin.as_str());- assert!(state["fell_back_from"].is_null(), "{state}");- assert!(- !state.to_string().contains(TEST_API_KEY),- "a secret leaked: {state}"- );-- // The switch persisted: a fresh `get` (new config load) sees it.- assert_eq!(fx.state().await["driver"], "tinyhumans");- let status = fx.call("openhuman.memory_provider_status", json!({})).await;- assert_eq!(- result_of(&status, "provider_status")["driver"],- "tinyhumans"- );-- // A write through the bound provider reaches the double under the- // session bearer, and reads back through the normal recall RPC.- let config = openhuman_core::config::load_config_with_timeout()- .await- .unwrap();- let binding = openhuman_core::memory::binding::for_config(&config).unwrap();- assert_eq!(binding.driver_id(), "tinyhumans");- binding- .provider()- .store(- NS,- "engine-note",- "the hosted engine stores this",- openhuman_core::memory::api::types::MemoryCategory::Core,- None,- openhuman_core::memory::api::types::MemoryTaint::Internal,- )- .await- .expect("store through the hosted engine");- assert!(- fx.hosted- .events- .lock()- .unwrap()- .iter()- .any(|e| e["content"]["text"]- .as_str()- .is_some_and(|t| t.contains("the hosted engine stores this"))),- "the write must land in the hosted double"- );- assert!(- fx.hosted- .bearers- .lock()- .unwrap()- .iter()- .all(|b| b == TEST_API_KEY),- "every hosted call carries the live credential"- );- // Reads through the mandatory recall family reach the hosted engine.- let recalled = binding- .provider()- .recall(- "hosted engine",- 5,- &openhuman_core::memory::api::recall::OwnedRecallOpts {- namespace: Some(NS.to_string()),- ..Default::default()- },- None,- )- .await- .expect("recall through the hosted engine");- assert!(- recalled- .iter()- .any(|e| e.content.contains("the hosted engine stores this")),- "recall must be served by the hosted engine: {recalled:?}"- );- // The core memory RPCs work on a remote engine through the mandatory- // families (engine-neutral fallbacks), and return the stored data.- let v = fx.call("openhuman.memory_list_namespaces", json!({})).await;- let namespaces = result_of(&v, "list_namespaces on hosted");- assert!(- namespaces.to_string().contains(NS),- "list_namespaces must report the hosted namespace: {namespaces}"- );- assert!(- namespaces.pointer("/data").is_some(),- "envelope data: {namespaces}"- );-- let v = fx- .call(- "openhuman.memory_recall_memories",- json!({ "namespace": NS, "limit": 5 }),- )- .await;- let recalled = result_of(&v, "recall_memories on hosted");- assert!(- recalled- .to_string()- .contains("the hosted engine stores this"),- "recall_memories must return the stored memory: {recalled}"- );-- let v = fx- .call(- "openhuman.memory_recall_context",- json!({ "namespace": NS, "limit": 5 }),- )- .await;- let context = result_of(&v, "recall_context on hosted");- assert!(- context- .to_string()- .contains("the hosted engine stores this"),- "recall_context must return the stored memory: {context}"- );-- let v = fx- .call(- "openhuman.memory_query_namespace",- json!({ "namespace": NS, "query": "hosted engine" }),- )- .await;- let queried = result_of(&v, "query_namespace on hosted");- assert!(- queried- .to_string()- .contains("the hosted engine stores this"),- "query_namespace must return the ranked hit: {queried}"- );-- let v = fx- .call("openhuman.memory_doc_list", json!({ "namespace": NS }))- .await;- let docs = result_of(&v, "doc_list on hosted");- assert!(- docs.to_string().contains("engine-note"),- "doc_list must list the stored entry: {docs}"- );-- // Graph stays capability-gated, with the stable recognisable error.- let v = fx- .call("openhuman.memory_graph_query", json!({ "namespace": NS }))- .await;- let message = error_message(&v, "graph_query on hosted");- assert!(- message.contains("does not support the graph family"),- "graph must be gated with the stable error: {message}"- );-- // The hosted engine serves documents (tinymemory's hosted-families- // spec): a titled document round-trips beside the stored note.- let doc = fx- .call(- "openhuman.memory_doc_put",- json!({- "namespace": NS, "key": "k", "title": "A title", "content": "c",- "source_type": "doc", "priority": "medium", "tags": [],- "metadata": null, "category": "core"- }),- )- .await;- result_of(&doc, "doc_put on the hosted engine");- let v = fx- .call("openhuman.memory_doc_list", json!({ "namespace": NS }))- .await;- let docs = result_of(&v, "doc_list after doc_put on hosted");- assert!(- docs.to_string().contains("A title") && docs.to_string().contains("engine-note"),- "doc_list must list the titled document and the stored note: {docs}"- );-- // And back to the module, live.- let v = fx- .call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;- let state = result_of(&v, "engine_set tinymemory");- assert_eq!(state["driver"], "tinymemory");- assert_eq!(state["class"], "module");- });-}--#[test]-fn engine_set_validates_and_never_stores_or_returns_a_key_in_config() {- run_on_big_stack("engine-set-validate", || async {- let fx = Fixture::new().await;-- for bad in ["not-an-engine", "null", ""] {- let v = fx- .call("openhuman.memory_engine_set", json!({ "driver": bad }))- .await;- let message = error_message(&v, &format!("engine_set {bad:?}"));- assert!(!message.is_empty());- }- let v = fx- .call(- "openhuman.memory_engine_set",- json!({ "driver": "supermemory", "endpoint": "ftp://nope" }),- )- .await;- assert!(error_message(&v, "bad endpoint").contains("http(s)"));- let v = fx- .call(- "openhuman.memory_engine_set",- json!({ "driver": "mem0", "deployment": "moon" }),- )- .await;- assert!(error_message(&v, "bad deployment").contains("deployment"));- assert_eq!(- fx.state().await["driver"],- "tinymemory",- "a rejected set changes nothing"- );-- let secret = "sm_secret_key_that_must_never_leak";- let v = fx- .call(- "openhuman.memory_engine_set",- json!({- "driver": "supermemory",- "endpoint": "https://api.supermemory.ai",- "api_key": secret- }),- )- .await;- let state = result_of(&v, "engine_set supermemory");- assert_eq!(state["driver"], "supermemory", "{state}");- assert_eq!(state["class"], "external");- assert_eq!(state["has_credential"], true);- assert!(- !state.to_string().contains(secret),- "key echoed in response: {state}"- );- let toml = std::fs::read_to_string(shared_config_path()).unwrap();- assert!(!toml.contains(secret), "key written to config.toml");- assert!(- toml.contains("keychain:memory-supermemory"),- "config should carry the ref: {toml}"- );- assert!(toml.contains("trust_state = \"trusted\""), "{toml}");-- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;- });-}--#[test]-fn hosted_failures_on_ordinary_memory_rpcs_use_the_engine_error_vocabulary() {- run_on_big_stack("engine-classify", || async {- let fx = Fixture::new().await;- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinyhumans" }),- )- .await;-- fx.hosted.force_status.store(402, Ordering::SeqCst);- let v = fx.call("openhuman.memory_list_namespaces", json!({})).await;- let message = error_message(&v, "list_namespaces on 402");- assert!(- message.starts_with("INSUFFICIENT_CREDITS:"),- "a hosted 402 must read INSUFFICIENT_CREDITS: {message}"- );-- fx.hosted.force_status.store(401, Ordering::SeqCst);- let v = fx.call("openhuman.memory_list_namespaces", json!({})).await;- let message = error_message(&v, "list_namespaces on 401");- assert!(- message.starts_with("SESSION_EXPIRED:"),- "a hosted 401 must read SESSION_EXPIRED: {message}"- );-- fx.hosted.force_status.store(0, Ordering::SeqCst);- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;- });-}diff --git a/tests/memory_engine_migrate_e2e.rs b/tests/memory_engine_migrate_e2e.rsdeleted file mode 100644index 8890bd829f..0000000000--- a/tests/memory_engine_migrate_e2e.rs+++ /dev/null@@ -1,233 +0,0 @@-//! Memory-engine selection over JSON-RPC: migration, cancel, credits and config safety, against-//! a hosted-CortexDB double (see `support/memory_engine_fixture.rs`). List/get/set-//! are in `memory_engine_e2e.rs`.-//!-//! ```text-//! RUST_MIN_STACK=67108864 cargo test -p openhuman-cli \-//! --features "$(bash scripts/ci/product-features.sh)" \-//! --test memory_engine_migrate_e2e-//! ```--#[path = "support/memory_engine_fixture.rs"]-mod fixture;--use std::sync::atomic::Ordering;-use std::time::Duration;--use fixture::*;-use serde_json::json;--#[test]-fn engine_migrate_copies_the_module_into_the_hosted_engine_then_switches() {- run_on_big_stack("engine-migrate", || async {- let fx = Fixture::new().await;- fx.put_doc("migrate-canary", "canary fact carried across engines")- .await;-- let v = fx- .call(- "openhuman.memory_engine_migrate",- json!({ "to": { "driver": "tinyhumans" } }),- )- .await;- let job_id = result_of(&v, "engine_migrate")["job_id"]- .as_str()- .expect("job_id")- .to_string();- let status = fx.wait_job(&job_id).await;- assert_eq!(status["state"], "done", "{status}");- assert!(status["error"].is_null());- assert!(status["copied"].as_u64().unwrap_or(0) >= 1, "{status}");-- assert!(- fx.hosted- .events- .lock()- .unwrap()- .iter()- .any(|e| e["content"]["text"]- .as_str()- .is_some_and(|t| t.contains("canary fact carried across engines"))),- "the migrated record must exist in the hosted engine"- );- // Past the keyed records, every step reports, in order, and none- // fails.- let steps = status["steps"].as_array().expect("steps");- let names: Vec<&str> = steps.iter().filter_map(|s| s["step"].as_str()).collect();- assert_eq!(- names,- ["documents", "goals", "profile", "episodic", "content"],- "{status}"- );- for step in steps {- assert_eq!(step["failed"], 0, "{step}");- }- // The pinned module serves `EpisodicPortability` and hosted memory- // takes it, so the conversation history step runs over the bus rather- // than being skipped.- let episodic = &steps[3];- assert!(- episodic["skipped_because"].is_null(),- "the conversation history step must run: {episodic}"- );- let documents = &steps[0];- assert!(documents["skipped_because"].is_null(), "{documents}");- assert!(- documents["written"].as_u64().unwrap_or(0) >= 1,- "the canary's title and source type are not the defaults, so its details move: {documents}"- );- assert!(- fx.hosted.events.lock().unwrap().iter().any(|e| {- e["scope"]- .as_str()- .is_some_and(|scope| scope.starts_with("tmi:documents"))- && e["content"]["text"]- .as_str()- .is_some_and(|t| t.contains("migrate-canary"))- }),- "the canary's details must be recorded in hosted memory"- );-- let state = fx.state().await;- assert_eq!(- state["driver"], "tinyhumans",- "the switch commits after the copy: {state}"- );-- let unknown = fx- .call(- "openhuman.memory_engine_migrate_status",- json!({ "job_id": "nope" }),- )- .await;- assert!(error_message(&unknown, "unknown job").contains("unknown"));-- // Migrating to the engine already in use is refused.- let again = fx- .call(- "openhuman.memory_engine_migrate",- json!({ "to": { "driver": "tinyhumans" } }),- )- .await;- assert!(error_message(&again, "same engine").contains("already"));-- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;- });-}--#[test]-fn insufficient_credits_fails_the_migration_and_keeps_the_active_engine() {- run_on_big_stack("engine-migrate-402", || async {- let fx = Fixture::new().await;- fx.put_doc("credits-canary", "record that cannot be copied")- .await;- fx.hosted.force_status.store(402, Ordering::SeqCst);-- let v = fx- .call(- "openhuman.memory_engine_migrate",- json!({ "to": { "driver": "tinyhumans" } }),- )- .await;- let job_id = result_of(&v, "engine_migrate")["job_id"]- .as_str()- .unwrap()- .to_string();- let status = fx.wait_job(&job_id).await;- assert_eq!(status["state"], "failed", "{status}");- let message = status["error"].as_str().expect("failure reason");- assert!(- message.starts_with("INSUFFICIENT_CREDITS:"),- "402 must map to INSUFFICIENT_CREDITS: {message}"- );-- let state = fx.state().await;- assert_eq!(- state["driver"], "tinymemory",- "a failed migration must not switch: {state}"- );- assert_eq!(state["class"], "module");- });-}--/// Seed enough records that a delayed hosted write keeps a migration running.-async fn seed_and_start_slow_migration(fx: &Fixture) -> String {- for i in 0..3 {- fx.put_doc(&format!("slow-{i}"), &format!("slow record {i}"))- .await;- }- fx.hosted.delay_ms.store(700, Ordering::SeqCst);- let v = fx- .call(- "openhuman.memory_engine_migrate",- json!({ "to": { "driver": "tinyhumans" } }),- )- .await;- result_of(&v, "engine_migrate")["job_id"]- .as_str()- .expect("job_id")- .to_string()-}--#[test]-fn cancel_stops_a_running_migration_and_keeps_the_active_engine() {- run_on_big_stack("engine-migrate-cancel", || async {- let fx = Fixture::new().await;- let job_id = seed_and_start_slow_migration(&fx).await;- tokio::time::sleep(Duration::from_millis(150)).await;-- let v = fx- .call(- "openhuman.memory_engine_migrate_cancel",- json!({ "job_id": job_id }),- )- .await;- assert_eq!(result_of(&v, "cancel")["cancelled"], true);- let status = fx.wait_job(&job_id).await;- assert_eq!(status["state"], "cancelled", "{status}");- assert_eq!(- fx.state().await["driver"],- "tinymemory",- "a cancelled job must not switch"- );- fx.hosted.delay_ms.store(0, Ordering::SeqCst);- });-}--#[test]-fn a_config_edited_during_the_copy_survives_the_switch() {- run_on_big_stack("engine-migrate-stale-config", || async {- let fx = Fixture::new().await;- let job_id = seed_and_start_slow_migration(&fx).await;-- // Edit an unrelated setting on disk while the copy runs. The commit must- // reload the config and patch only `[subsystems.memory]`, not write back- // the snapshot taken when the RPC started.- let path = shared_config_path();- let mut toml = std::fs::read_to_string(&path).unwrap();- toml = toml.replace(- "default_model = \"e2e-mock-model\"",- "default_model = \"edited-during-copy\"",- );- std::fs::write(&path, &toml).unwrap();-- let status = fx.wait_job(&job_id).await;- assert_eq!(status["state"], "done", "{status}");- let after = std::fs::read_to_string(&path).unwrap();- assert!(- after.contains("edited-during-copy"),- "the commit clobbered a concurrent edit:\n{after}"- );- assert!(after.contains("driver = \"tinyhumans\""), "{after}");- fx.hosted.delay_ms.store(0, Ordering::SeqCst);- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;- });-}diff --git a/tests/memory_hosted_surface_e2e.rs b/tests/memory_hosted_surface_e2e.rsdeleted file mode 100644index 94b9e2af4a..0000000000--- a/tests/memory_hosted_surface_e2e.rs+++ /dev/null@@ -1,445 +0,0 @@-//! The memory surface on the hosted engine (openhuman#6718), against the same-//! hosted-CortexDB double as `memory_engine_e2e.rs`.-//!-//! The four memory suites (`memory_roundtrip_e2e`, `memory_sources_e2e`,-//! `memory_graph_roundtrip_e2e`, `memory_tree_health_e2e`) run on the local-//! module, whose engine serves every family. The hosted engine serves the-//! mandatory families, ingestion and answers, and goals, tool rules, documents,-//! the source sink, maintenance, retrieval, ingest, profile, episodic memory,-//! scoring and a tree drawn from the server's understanding (tinymemory's-//! hosted-families spec); local sources are synced by the host through its-//! sink. This suite holds it to what that means for a user: what it serves-//! works, what it does not serve answers a clean refusal rather than failing-//! some other way, auto-recall reaches the notes a user saved, a refused lookup-//! says why, the Brain graph draws what the server understood, and a synced-//! folder reaches hosted memory.-//!-//! ```text-//! RUST_MIN_STACK=67108864 cargo test -p openhuman-cli \-//! --features "$(bash scripts/ci/product-features.sh)" \-//! --test memory_hosted_surface_e2e-//! ```--#[path = "support/memory_engine_fixture.rs"]-mod fixture;--use std::sync::atomic::Ordering;--use fixture::*;-use openhuman_core::memory::api::types::{MemoryCategory, MemoryTaint};-use openhuman_core::memory::auto_recall::{AutoRecall, AUTO_RECALL_NOTES_NAMESPACE};-use serde_json::json;--/// A question the auto-recall gate opens for. The double's recall matches by-/// substring, so the note that should answer it quotes it.-const QUESTION: &str = "who is my idol and why?";--async fn bind_hosted(- fx: &Fixture,-) -> std::sync::Arc<openhuman_core::memory::binding::MemoryBinding> {- let v = fx- .call(- "openhuman.memory_engine_set",- json!({ "driver": "tinyhumans" }),- )- .await;- assert_eq!(- result_of(&v, "engine_set tinyhumans")["driver"],- "tinyhumans"- );- let config = openhuman_core::config::load_config_with_timeout()- .await- .unwrap();- let binding = openhuman_core::memory::binding::for_config(&config).unwrap();- assert_eq!(binding.driver_id(), "tinyhumans");- binding-}--async fn unbind(fx: &Fixture) {- fx.hosted.force_status.store(0, Ordering::SeqCst);- fx.call(- "openhuman.memory_engine_set",- json!({ "driver": "tinymemory" }),- )- .await;-}--#[test]-fn auto_recall_reaches_a_saved_note_on_the_hosted_engine() {- run_on_big_stack("hosted-auto-recall", || async {- let fx = Fixture::new().await;- let binding = bind_hosted(&fx).await;- binding- .provider()- .store(- AUTO_RECALL_NOTES_NAMESPACE,- "idol",- &format!("{QUESTION} The user's idol is Virat Kohli, for his discipline."),- MemoryCategory::Core,- None,- MemoryTaint::Internal,- )- .await- .expect("store the note");-- // Hosted recall carries no score: the note reads 0.0, which the scored- // floor would drop. The lane keeps the engine's order instead.- let lane = AutoRecall::from_guard(binding.guard());- assert!(lane.enabled());- let block = lane.block_for(QUESTION).await.expect("a block");- assert!(block.contains("Virat Kohli"), "{block}");-- // Out of credits: the block says so instead of reading as "nothing- // stored".- fx.hosted.force_status.store(402, Ordering::SeqCst);- let block = lane.block_for(QUESTION).await.expect("a refusal block");- assert!(block.contains("out of credits"), "{block}");- assert!(!block.contains("Virat Kohli"), "{block}");-- unbind(&fx).await;- });-}--#[test]-fn a_refused_credential_and_an_outage_have_their_own_names() {- run_on_big_stack("hosted-vocabulary", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;-- // A 403 is a valid credential refused (an API key without the memory- // scope). It must not read SESSION_EXPIRED, which signs the user out.- fx.hosted.force_status.store(403, Ordering::SeqCst);- let v = fx.call("openhuman.memory_list_namespaces", json!({})).await;- let message = error_message(&v, "list_namespaces on 403");- assert!(message.starts_with("MEMORY_FORBIDDEN:"), "{message}");- assert!(!message.contains("SESSION_EXPIRED"), "{message}");-- // A 503 that outlasts the retries is the engine being unavailable.- fx.hosted.force_status.store(503, Ordering::SeqCst);- let v = fx.call("openhuman.memory_list_namespaces", json!({})).await;- let message = error_message(&v, "list_namespaces on 503");- assert!(message.starts_with("MEMORY_UNREACHABLE:"), "{message}");-- unbind(&fx).await;- });-}--/// The handler answers from the host log when the driver keeps no run log:-/// hosted memory serves the `Sources` sink without owning pipelines-/// (`SourceSync` is absent), so its `memory_sources.*` methods are registered-/// and Sync History reads what the host recorded.-#[test]-fn sync_history_answers_from_the_host_log_on_an_engine_without_one() {- run_on_big_stack("hosted-sync-history", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;- let v = fx- .call("openhuman.memory_sources_sync_audit_log", json!({}))- .await;- let history = result_of(&v, "sync_audit_log on hosted");- assert!(history["entries"].is_array(), "{history}");- unbind(&fx).await;- });-}--/// The Brain graph on hosted memory is the server's understanding: a fact it-/// derived from the user's notes is a node labelled by what it says, under-/// the namespace it came from, named for what that holds.-#[test]-fn the_hosted_engine_draws_the_brain_graph_from_its_understanding() {- run_on_big_stack("hosted-graph", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;- fx.hosted.layers.lock().unwrap().insert(- ("facts".to_string(), "tm:global".to_string()),- vec![json!({- "id": "fact_tea",- "scope": "tm:global",- "subject": { "type": "entity", "id": "ent_user", "name": "User" },- "predicate": "prefers",- "object": { "type": "literal", "datatype": "string", "value": "oolong tea" },- "supports": [],- "confidence": 0.9,- "valid_from": "2026-09-01T00:00:00Z",- "recorded_from": "2026-09-01T00:00:00Z",- })],- );- let v = fx- .call(- "openhuman.memory_tree_graph_export",- json!({ "mode": "tree" }),- )- .await;- let graph = result_of(&v, "graph export on hosted");- let labels: Vec<&str> = graph["nodes"]- .as_array()- .expect("nodes")- .iter()- .filter_map(|node| node["label"].as_str())- .collect();- assert!(labels.contains(&"User prefers oolong tea"), "{graph}");- assert!(- labels.contains(&"Memory"),- "the global namespace reads as what it holds: {graph}"- );- unbind(&fx).await;- });-}--/// A folder source on hosted memory is read by the host and sent through the-/// engine's sink, and the run lands in Sync History like any other.-#[test]-fn a_local_folder_syncs_into_hosted_memory() {- run_on_big_stack("hosted-folder-sync", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;- let folder = fx._tmp.path().join("notes");- std::fs::create_dir_all(&folder).expect("folder");- std::fs::write(folder.join("tea.md"), "# Tea\n\nOolong, always.").expect("note");- let v = fx- .call(- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Notes",- "enabled": true,- "path": folder.to_string_lossy(),- }),- )- .await;- let source_id = result_of(&v, "add a folder source")["source"]["id"]- .as_str()- .expect("a source id")- .to_string();- let v = fx- .call(- "openhuman.memory_sources_sync",- json!({ "source_id": source_id }),- )- .await;- result_of(&v, "sync a folder on hosted");- let synced = fx.hosted.events.lock().unwrap().iter().any(|event| {- event["scope"] == "tm:sources/tm:documents"- && event["content"]["text"]- .as_str()- .is_some_and(|text| text.contains("Oolong, always."))- });- assert!(synced, "the note reaches the hosted documents namespace");- let v = fx- .call("openhuman.memory_sources_sync_audit_log", json!({}))- .await;- let history = result_of(&v, "sync history after a hosted folder sync");- assert!(- history["entries"].to_string().contains(&source_id),- "{history}"- );- unbind(&fx).await;- });-}--/// Adds `folder` as a folder source and answers its id.-async fn add_folder(fx: &Fixture, folder: &std::path::Path) -> String {- let v = fx- .call(- "openhuman.memory_sources_add",- json!({- "kind": "folder",- "label": "Notes",- "enabled": true,- "path": folder.to_string_lossy(),- }),- )- .await;- result_of(&v, "add a folder source")["source"]["id"]- .as_str()- .expect("a source id")- .to_string()-}--/// Whether the hosted double holds an event whose text contains `needle`.-fn hosted_holds(fx: &Fixture, needle: &str) -> bool {- fx.hosted.events.lock().unwrap().iter().any(|event| {- event["content"]["text"]- .as_str()- .is_some_and(|text| text.contains(needle))- })-}--/// A file deleted from a host-synced folder is forgotten from hosted memory-/// on the next sync, by the id the sink answered for it. A walk that finds-/// the folder empty forgets nothing and keeps the record, so a later walk-/// still can.-#[test]-fn a_file_deleted_from_a_synced_folder_is_forgotten_from_hosted_memory() {- run_on_big_stack("hosted-folder-delete", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;- let folder = fx._tmp.path().join("deletes");- std::fs::create_dir_all(&folder).expect("folder");- std::fs::write(folder.join("tea.md"), "# Tea\n\nOolong, always.").expect("tea");- std::fs::write(folder.join("coffee.md"), "# Coffee\n\nNever before noon.").expect("coffee");- let source_id = add_folder(&fx, &folder).await;- let sync = || {- fx.call(- "openhuman.memory_sources_sync",- json!({ "source_id": source_id }),- )- };- result_of(&sync().await, "first sync");- assert!(hosted_holds(&fx, "Never before noon."), "coffee is synced");-- let tea = std::fs::read_to_string(folder.join("tea.md")).expect("read tea");- std::fs::remove_file(folder.join("tea.md")).expect("hide tea");- std::fs::remove_file(folder.join("coffee.md")).expect("delete coffee");- result_of(&sync().await, "sync over an empty folder");- assert!(- hosted_holds(&fx, "Never before noon."),- "an empty walk forgets nothing"- );-- std::fs::write(folder.join("tea.md"), tea).expect("tea is back");- result_of(&sync().await, "sync after the delete");- assert!(- !hosted_holds(&fx, "Never before noon."),- "the deleted file is forgotten by its stored id"- );- assert!(- hosted_holds(&fx, "Oolong, always."),- "the file still there stays"- );- unbind(&fx).await;- });-}--/// The first `documentId` anywhere in `value`.-fn document_id(value: &serde_json::Value) -> Option<String> {- match value {- serde_json::Value::Object(map) => map- .get("documentId")- .and_then(serde_json::Value::as_str)- .map(str::to_string)- .or_else(|| map.values().find_map(document_id)),- serde_json::Value::Array(items) => items.iter().find_map(document_id),- _ => None,- }-}--/// The families hosted memory serves beyond the mandatory ones, through the-/// app's RPCs: documents and tool rules round-trip.-#[test]-fn the_hosted_engine_serves_documents_and_tool_rules() {- run_on_big_stack("hosted-families", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;-- let v = fx- .call(- "openhuman.memory_doc_put",- json!({- "namespace": NS, "key": "tea", "title": "Tea",- "content": "The user drinks oolong.", "source_type": "doc",- "priority": "medium", "tags": [], "metadata": null,- "category": "core"- }),- )- .await;- result_of(&v, "doc_put on hosted");- let v = fx- .call("openhuman.memory_doc_list", json!({ "namespace": NS }))- .await;- let listed = result_of(&v, "doc_list on hosted").clone();- assert!(listed.to_string().contains("Tea"), "{listed}");- let id = document_id(&listed).unwrap_or_else(|| panic!("no document id: {listed}"));- let v = fx- .call(- "openhuman.memory_doc_delete",- json!({ "namespace": NS, "document_id": id }),- )- .await;- let deleted = result_of(&v, "doc_delete on hosted");- assert!(- deleted.to_string().contains("\"deleted\":true"),- "{deleted}"- );-- let v = fx- .call(- "openhuman.memory_tool_rule_put",- json!({ "tool_name": "shell", "rule": "quote every path" }),- )- .await;- result_of(&v, "tool_rule_put on hosted");- let v = fx- .call(- "openhuman.memory_tool_rule_list",- json!({ "tool_name": "shell" }),- )- .await;- let rules = result_of(&v, "tool_rule_list on hosted");- assert!(rules.to_string().contains("quote every path"), "{rules}");-- unbind(&fx).await;- });-}--/// What the hosted engine does not serve answers cleanly: the RPCs that need-/// a missing family name it, and the tree health reads degrade to an empty or-/// unhealthy answer rather than an error.-#[test]-fn what_the_hosted_engine_does_not_serve_is_refused_cleanly() {- run_on_big_stack("hosted-refusals", || async {- let fx = Fixture::new().await;- bind_hosted(&fx).await;- let refused = [- // memory_graph_roundtrip_e2e- (- "openhuman.memory_graph_upsert",- json!({ "namespace": NS, "subject": "a", "predicate": "knows", "object": "b" }),- ),- ("openhuman.memory_graph_query", json!({ "namespace": NS })),- ];- // Collected rather than asserted one by one, so a run names every- // method that answers some other way.- let mut offenders = Vec::new();- for (method, params) in refused {- let v = fx.call(method, params).await;- let message = v- .pointer("/error/message")- .and_then(serde_json::Value::as_str)- .unwrap_or_default();- if !(message.contains("does not support the ") && message.contains(" family")) {- offenders.push(format!("{method}: {v}"));- }- }- assert!(- offenders.is_empty(),- "each must name the family the hosted engine lacks:\n{}",- offenders.join("\n")- );-- // memory_tree_health_e2e: the health reads answer from the host and- // say what is missing, rather than failing.- let v = fx- .call("openhuman.memory_tree_list_sources", json!({}))- .await;- assert_eq!(result_of(&v, "tree list_sources on hosted"), &json!([]));- // Hosted memory serves Maintenance: the doctor answers from the- // service's health probe rather than naming a missing family.- let v = fx.call("openhuman.memory_tree_doctor", json!({})).await;- let doctor = result_of(&v, "tree doctor on hosted");- assert_eq!(doctor["healthy"], true, "{doctor}");- assert!(- doctor.to_string().contains("\"service\""),- "the doctor reports the hosted service stage: {doctor}"- );- let v = fx- .call("openhuman.memory_tree_pipeline_status", json!({}))- .await;- assert_eq!(- result_of(&v, "tree pipeline_status on hosted")["total_chunks"],- 0- );-- unbind(&fx).await;- });-}diff --git a/tests/memory_roundtrip_e2e.rs b/tests/memory_roundtrip_e2e.rsdeleted file mode 100644index 45cc157acd..0000000000--- a/tests/memory_roundtrip_e2e.rs+++ /dev/null@@ -1,376 +0,0 @@-//! Memory subsystem round-trip integration test (#773 PR-A).-//!-//! Validates the full doc_put → recall_memories → clear_namespace lifecycle-//! against a real local memory client backed by the workspace store under a-//! per-test temp `OPENHUMAN_WORKSPACE`.-//!-//! Counterpart to `app/test/e2e/specs/memory-roundtrip.spec.ts` which exercises-//! the same flow over JSON-RPC. This Rust test verifies the Rust contract in-//! isolation; the WDIO spec proves the UI⇄Tauri⇄sidecar wiring.-//!-//! # Running this target-//!-//! ```text-//! RUST_MIN_STACK=67108864 cargo test -p openhuman-cli \-//! --features "$(bash scripts/ci/product-features.sh)" \-//! --test memory_roundtrip_e2e-//! ```-//!-//! Both parts are load-bearing and both fail in ways that look like product-//! bugs rather than invocation mistakes:-//!-//! * **`--features`.** `openhuman-cli`'s own `modules` flag is NOT in its-//! `default` set, even though `openhuman-core/modules` is switched on-//! transitively. A `#[cfg(feature = "modules")]` block inside an integration-//! test is evaluated against **openhuman-cli**'s features, so without this-//! the `set_modules_policy` call in `ensure_memory_seams` below compiles to-//! nothing and every module-backed call fails with "the module host policy-//! was never published, so module 'tinymemory' cannot be loaded". The seam-//! becoming a silent no-op is the worst shape for that trap: the only hint is-//! an `unused variable: config` warning. (Diagnosed by the W6/`tinyhuman-a8`-//! pass, 2026-09-24.)-//! * **`RUST_MIN_STACK`.** Without it the namespace-summaries test overflows its-//! stack and SIGABRTs before reaching an assertion — the #5021 class, and the-//! value the rust-gates-off lane already sets.-//!-//! `scripts/test-rust-e2e.sh` supplies both; a bare-//! `cargo test --test memory_roundtrip_e2e` supplies neither.--#[path = "support/env_guard.rs"]-mod env_guard;-use env_guard::EnvVarGuard;-use std::path::Path;-use std::sync::{Arc, Mutex, OnceLock};--use tempfile::tempdir;--use openhuman_core::memory::ops::{- clear_namespace, doc_put, memory_namespace_summaries, memory_recall_context,- memory_recall_memories, ClearNamespaceParams, PutDocParams,-};-use openhuman_core::memory::rpc_models::{RecallContextRequest, RecallMemoriesRequest};--// ── Env isolation ────────────────────────────────────────────────────--/// Serialises tests: `HOME` + `OPENHUMAN_WORKSPACE` are process-global.-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();-static TEST_ROOT: OnceLock<tempfile::TempDir> = OnceLock::new();--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {- Ok(guard) => guard,- Err(poisoned) => poisoned.into_inner(),- }-}--/// This integration target calls memory operations without constructing a core-/// runtime, so it supplies the seams that normal startup installs first.-fn test_root() -> &'static tempfile::TempDir {- TEST_ROOT.get_or_init(|| tempdir().expect("memory roundtrip tempdir"))-}--fn ensure_memory_seams(workspace: &Path) {- MEMORY_SEAMS_INIT.get_or_init(|| {- let workspace = workspace.to_path_buf();- std::thread::Builder::new()- .name("memory-roundtrip-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(move || {- let config = Arc::new(openhuman_core::config::Config {- workspace_dir: workspace.clone(),- action_dir: workspace.clone(),- config_path: workspace.join("config.toml"),- ..openhuman_core::config::Config::default()- });- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(config);- })- .expect("spawn memory roundtrip seam installer")- .join()- .expect("memory roundtrip seam installer panicked");- });-}--const NS: &str = "memory-roundtrip-e2e-773";-const KEY: &str = "roundtrip-canary-key";-const TITLE: &str = "Memory roundtrip canary";-const CONTENT: &str = "OpenHuman memory roundtrip canary fact #773";--fn put_params() -> PutDocParams {- PutDocParams {- namespace: NS.to_string(),- key: KEY.to_string(),- title: TITLE.to_string(),- content: CONTENT.to_string(),- source_type: "doc".to_string(),- priority: "medium".to_string(),- tags: Vec::new(),- metadata: serde_json::Value::Null,- category: "core".to_string(),- session_id: None,- document_id: None,- }-}--fn recall_request() -> RecallMemoriesRequest {- RecallMemoriesRequest {- namespace: NS.to_string(),- min_retention: None,- as_of: None,- limit: Some(10),- max_chunks: None,- top_k: None,- }-}--fn recall_context_request() -> RecallContextRequest {- RecallContextRequest {- namespace: NS.to_string(),- include_references: Some(true),- limit: Some(10),- max_chunks: None,- }-}--// ── Tests ────────────────────────────────────────────────────────────--/// 8.1.1 store + 8.1.2 recall — the happy-path round-trip.-#[tokio::test]-async fn doc_put_then_recall_memories_returns_canary() {- let _lock = env_lock();- let tmp = test_root();- let _home = EnvVarGuard::set_to_path("HOME", tmp.path());- let workspace_path = tmp.path().join("workspace");- std::fs::create_dir_all(&workspace_path).expect("create workspace dir");- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace_path);- ensure_memory_seams(&workspace_path);-- // Store the canary document.- let put_outcome = doc_put(put_params()).await.expect("doc_put rpc");- assert!(- !put_outcome.value.document_id.is_empty(),- "doc_put should return a non-empty document_id"- );-- // Recall the namespace and assert the canary surface.- let recall_outcome = memory_recall_memories(recall_request())- .await- .expect("memory_recall_memories rpc");- let serialised =- serde_json::to_string(&recall_outcome.value).expect("serialise recall envelope");- assert!(- serialised.contains(CONTENT) || serialised.contains(KEY),- "recall payload should reference the canary content/key — got {serialised}"- );-}--/// `recall_context` should surface the same document as an LLM-ready prompt-/// block, not only in the raw memory list view.-#[tokio::test]-async fn doc_put_then_recall_context_renders_llm_context_message() {- let _lock = env_lock();- let tmp = test_root();- let _home = EnvVarGuard::set_to_path("HOME", tmp.path());- let workspace_path = tmp.path().join("workspace");- std::fs::create_dir_all(&workspace_path).expect("create workspace dir");- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace_path);- ensure_memory_seams(&workspace_path);-- doc_put(put_params()).await.expect("doc_put rpc");-- let recall_outcome = memory_recall_context(recall_context_request())- .await- .expect("memory_recall_context rpc");- let llm_context = recall_outcome- .value- .data- .as_ref()- .and_then(|data| data.llm_context_message.as_ref())- .cloned()- .unwrap_or_default();- assert!(- llm_context.contains(CONTENT) || llm_context.contains(KEY),- "llm context should reference the canary content/key — got {llm_context}"- );-}--/// 8.1.3 forget — clear_namespace must scrub the namespace so subsequent-/// recalls do not see the canary content. Failure-path / edge-case assertion-/// required by gitbooks/developing/testing-strategy.md.-#[tokio::test]-async fn clear_namespace_removes_canary_from_recall() {- let _lock = env_lock();- let tmp = test_root();- let _home = EnvVarGuard::set_to_path("HOME", tmp.path());- let workspace_path = tmp.path().join("workspace");- std::fs::create_dir_all(&workspace_path).expect("create workspace dir");- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace_path);- ensure_memory_seams(&workspace_path);-- // Seed the namespace.- doc_put(put_params()).await.expect("seed doc_put");-- // Pre-clear sanity: canary visible.- let pre = memory_recall_memories(recall_request())- .await- .expect("pre-clear recall");- let pre_blob = serde_json::to_string(&pre.value).expect("serialise pre");- assert!(- pre_blob.contains(CONTENT) || pre_blob.contains(KEY),- "canary must be visible before clear — got {pre_blob}"- );-- // Clear the namespace.- let clear_outcome = clear_namespace(ClearNamespaceParams {- namespace: NS.to_string(),- })- .await- .expect("clear_namespace rpc");- assert!(- clear_outcome.value.cleared,- "clear_namespace must report cleared=true"- );- assert_eq!(clear_outcome.value.namespace, NS);-- // Post-clear: canary must no longer surface in recall.- let post = memory_recall_memories(recall_request())- .await- .expect("post-clear recall");- let post_blob = serde_json::to_string(&post.value).expect("serialise post");- assert!(- !post_blob.contains(CONTENT),- "canary content must be absent after clear — got {post_blob}"- );- assert!(- !post_blob.contains(KEY),- "canary key must be absent after clear — got {post_blob}"- );-}--// ── A1: `openhuman.memory_namespace_summaries` ───────────────────────-//-// Gate controller `memory_namespace_summaries` had zero references under-// `tests/` or `app/test/` before this test.-//-// The handler (`memory/ops/documents.rs`) resolves `active_memory_guard()` and-// calls `MemoryCore::namespaces()`, which crosses tinybus into the downloaded-// tinymemory cdylib. That boundary is the reason this lives at the RI layer: a-// unit or renderer test would assert the shape of a response the host itself-// assembled and would prove nothing about the engine that produced the counts.-//-// The counts are the point, not the shape. The handler's own doc comment names-// the field finding it exists to serve (#5932): "a Gmail source that stored-// 1,120 documents should be checkable as exactly that number". A regression-// that returns an empty namespace list, or counts that are silently zero, is-// worse than an error because the number stays plausible.--/// Seed `count` distinct documents into `namespace` under one shared key-/// prefix. Distinct keys, because `doc_put` upserts on key — reusing one would-/// store a single document and make a count assertion pass for the wrong-/// reason.-async fn seed_namespace(namespace: &str, count: usize) {- for i in 0..count {- let params = PutDocParams {- namespace: namespace.to_string(),- key: format!("summaries-seed-{i}"),- title: format!("Namespace summary seed {i}"),- content: format!("Namespace summary seed body {i}"),- source_type: "doc".to_string(),- priority: "medium".to_string(),- tags: Vec::new(),- metadata: serde_json::Value::Null,- category: "core".to_string(),- session_id: None,- document_id: None,- };- doc_put(params).await.expect("seed doc_put for summaries");- }-}--// ── A8: the ingest queue drains at a size that actually queues ───────────────-//-// Matrix 8.2.3 "Memory Scaling" is 🟡: ingestion moved into the tinymemory-// module, and the host kept no test that a batch large enough to queue is-// actually DRAINED rather than silently dropped at the bus boundary. 8.2.2-// covers ingest-reflected-by-status, but at a size that never queues, so the-// path where documents are accepted and then lost has no coverage at all.-//-// This is deliberately a bounded scale check and not a soak. A soak belongs in-// a lane that can afford minutes; what is missing here is cheap and specific:-// does the count still reconcile once the write is big enough to be batched?-// Losing documents silently is the failure mode that a small-N test cannot see,-// because a queue that drops its tail still looks correct at N = 3.-//-// If this proves slow in CI, lower `SCALE_DOCS` rather than deleting the test —-// the assertion is the reconciliation, not the number.--/// Ingesting a batch large enough to queue leaves an exact, reconciled count.-#[tokio::test]-async fn namespace_summaries_reconcile_after_a_batch_large_enough_to_queue() {- let _lock = env_lock();- let tmp = test_root();- let _home = EnvVarGuard::set_to_path("HOME", tmp.path());- let workspace_path = tmp.path().join("workspace");- std::fs::create_dir_all(&workspace_path).expect("create workspace dir");- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace_path);- ensure_memory_seams(&workspace_path);-- const NS_SCALE: &str = "memory-summaries-e2e-scale";- const SCALE_DOCS: usize = 60;-- clear_namespace(ClearNamespaceParams {- namespace: NS_SCALE.to_string(),- })- .await- .expect("pre-clear scale namespace");-- // Fixture guard: prove the namespace really is empty before the batch, so- // a count of SCALE_DOCS afterwards cannot be inherited from a sibling test- // that used the same name.- let before = memory_namespace_summaries()- .await- .expect("summaries before scale ingest");- let before_count = before- .value- .namespaces- .iter()- .find(|row| row.namespace == NS_SCALE)- .map(|row| row.count)- .unwrap_or(0);- assert_eq!(- before_count, 0,- "scale namespace must start empty; found {before_count} documents"- );-- seed_namespace(NS_SCALE, SCALE_DOCS).await;-- let after = memory_namespace_summaries()- .await- .expect("summaries after scale ingest");- let row = after- .value- .namespaces- .iter()- .find(|row| row.namespace == NS_SCALE)- .unwrap_or_else(|| {- panic!(- "scale namespace vanished from summaries after ingesting {SCALE_DOCS} documents \- — got {:?}",- after- .value- .namespaces- .iter()- .map(|r| (&r.namespace, r.count))- .collect::<Vec<_>>()- )- });-- assert_eq!(- row.count, SCALE_DOCS,- "ingested {SCALE_DOCS} documents but the namespace reports {}. A batch that queues must \- still reconcile exactly; a short count here means writes were accepted and then dropped \- between the host and the module, which is invisible at the sizes 8.2.2 exercises.",- row.count- );-}diff --git a/tests/raw_coverage/learning_facets_e2e.rs b/tests/raw_coverage/learning_facets_e2e.rsdeleted file mode 100644index dd3d84e082..0000000000--- a/tests/raw_coverage/learning_facets_e2e.rs+++ /dev/null@@ -1,872 +0,0 @@-//! JSON-RPC E2E coverage for the `learning` namespace — the eleven controllers-//! behind the user-profile facet cache.-//!-//! The arc these cases walk is the production one: real observations are pushed-//! into `learning::candidate::global()` (the same buffer-//! `learning::extract::heuristics`, `extract::signature` and-//! `learning::reflection` push into), `learning.rebuild_cache` runs the-//! stability detector over them, and every read/mutate controller is then driven-//! over the actual axum JSON-RPC router. Nothing is written to the facet store-//! behind the RPC surface's back.-//!-//! This file is a **module** of the aggregated `raw_coverage_all` target, not a-//! target of its own — `build.rs` globs `tests/raw_coverage/` and generates the-//! `mod` list. Run with:-//! `~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \-//! --features "$(bash scripts/ci/product-features.sh)" -- learning_facets`-//!-//! ## Two hazards this file is written around-//!-//! 1. **One process, ~77 suites.** The env lock is the crate-wide-//! `SHARED_ENV_LOCK`; a lock private to this module would isolate nothing.-//! The RPC bearer is read back from `core::auth::get_rpc_token()` rather than-//! assumed, because that token is a process-global `OnceLock` and a sibling-//! suite may have seeded it first.-//!-//! 2. **The facet store is shared.** The memory module host captures one-//! workspace per process, so these cases key everything on a unique-//! `E2E_KEY_*` slug and assert on *their own* rows — never on a global count.-//! `cache_stats` is asserted as "at least mine", and `reset_cache` is checked-//! by what happened to this suite's two facets, not by the totals.--use crate::env_guard::EnvVarGuard;-use std::net::SocketAddr;-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};-use std::time::{Duration, SystemTime, UNIX_EPOCH};--use axum::http::header::AUTHORIZATION;-use reqwest::StatusCode;-use serde_json::{json, Value};-use tempfile::TempDir;--use openhuman_core::agent::learning::candidate::{- self, CueFamily, EvidenceRef, FacetClass, LearningCandidate,-};-use openhuman_core::config::Config;-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};-use openhuman_rpc::server::build_core_http_router;--/// Preferred bearer. Only the real one if this module wins the process-global-/// `OnceLock` race — send [`rpc_bearer`], never this.-const PREFERRED_RPC_TOKEN: &str = "learning-facets-e2e-token";--/// Facet keys this suite owns. Distinctive enough that a sibling suite (or a-/// leftover row in the shared store) can never be mistaken for one of them.-const PINNED_KEY: &str = "e2e_learning_pinned_slug";-const VOLATILE_KEY: &str = "e2e_learning_volatile_slug";--static AUTH_INIT: OnceLock<()> = OnceLock::new();-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();--/// The crate-wide env lock — see the module docs.-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())-}--// ── Env isolation ─────────────────────────────────────────────────────────--// ── Shared memory workspace ───────────────────────────────────────────────--/// The transport-only JSON-RPC router builds no core runtime context, so a-/// memory-backed route has no seams unless they are installed explicitly.-fn ensure_memory_seams() {- MEMORY_SEAMS_INIT.get_or_init(|| {- std::thread::Builder::new()- .name("learning-facets-e2e-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(|| {- let config = Arc::new(shared_config_at(learning_workspace()));- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(config);- })- .expect("spawn learning facets seam installer")- .join()- .expect("learning facets seam installer panicked");- });-}--/// The one memory workspace every case in this module shares.-///-/// The module host captures a workspace **once per process** — the loaded-/// artifact takes its `workspace_dir` at load time and later policy calls are-/// ignored — while a per-case `TempDir` would be deleted the moment its case-/// returned, leaving every later read answering from a dead store. So this is-/// one leaked directory, published once, and every case points both its config-/// and `OPENHUMAN_WORKSPACE` at it. The path ends in `workspace` so-/// `resolve_config_dir_for_workspace` treats it as the workspace itself rather-/// than appending another segment.-fn learning_workspace() -> &'static Path {- static WORKSPACE: OnceLock<PathBuf> = OnceLock::new();- WORKSPACE.get_or_init(|| {- let dir = TempDir::new().expect("learning workspace tempdir");- let path = dir.path().join("workspace");- std::fs::create_dir_all(&path).expect("create learning workspace");- // Leaked on purpose: the module keeps this path for the process lifetime.- std::mem::forget(dir);- path- })-}--/// A config whose workspace **and** config path are the shared ones.-///-/// `config_path` matters as much as `workspace_dir`: `Config::default()` names-/// the developer's real `~/.openhuman/config.toml`, and pointing it beside the-/// shared workspace is where `Config::load_or_init` resolves it from-/// `OPENHUMAN_WORKSPACE` too — so env-driven and config-driven paths agree.-fn shared_config_at(workspace: &Path) -> Config {- let mut config = Config::default();- config.workspace_dir = workspace.to_path_buf();- config.config_path = workspace- .parent()- .expect("shared workspace has a parent")- .join("config.toml");- config.embeddings_provider = Some("none".into());- config-}--fn write_min_config(config_path: &Path) {- if let Some(parent) = config_path.parent() {- std::fs::create_dir_all(parent).expect("create config dir");- }- let cfg = r#"api_url = "http://127.0.0.1:9"-default_model = "e2e-model"-default_temperature = 0.2--[secrets]-encrypt = false--[local_ai]-enabled = false--[memory_tree]-embedding_strict = false-"#;- std::fs::write(config_path, cfg).expect("write config.toml");- let _: Config = toml::from_str(cfg).expect("test config must match schema");-}--// ── Harness ───────────────────────────────────────────────────────────────--fn ensure_rpc_auth() {- AUTH_INIT.get_or_init(|| {- std::env::set_var(CORE_TOKEN_ENV_VAR, PREFERRED_RPC_TOKEN);- let token_dir = std::env::temp_dir().join("openhuman-learning-facets-e2e-auth");- init_rpc_token(&token_dir).expect("init rpc auth token");- });-}--/// The bearer the running process actually validates — see the module docs.-fn rpc_bearer() -> &'static str {- ensure_rpc_auth();- openhuman_core::core::auth::get_rpc_token()- .expect("the RPC token must be initialised before a request is signed")-}--struct Harness {- _guards: Vec<EnvVarGuard>,- workspace: PathBuf,- rpc_base: String,- join: tokio::task::JoinHandle<Result<(), std::io::Error>>,-}--async fn serve_rpc() -> (- SocketAddr,- tokio::task::JoinHandle<Result<(), std::io::Error>>,-) {- ensure_rpc_auth();- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind rpc listener");- let addr = listener.local_addr().expect("rpc listener addr");- let join =- tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });- (addr, join)-}--async fn setup() -> Harness {- ensure_memory_seams();- let workspace = learning_workspace().to_path_buf();- let config_path = workspace- .parent()- .expect("shared workspace has a parent")- .join("config.toml");- write_min_config(&config_path);-- let guards = vec![- EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),- EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),- ];-- let (addr, join) = serve_rpc().await;- Harness {- _guards: guards,- workspace,- rpc_base: format!("http://{addr}"),- join,- }-}--async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(60))- .build()- .expect("client");- let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));- let response = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))- .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))- .send()- .await- .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));- assert_eq!(- response.status(),- StatusCode::OK,- "HTTP transport should accept {method}"- );- response- .json::<Value>()- .await- .unwrap_or_else(|err| panic!("json for {method}: {err}"))-}--/// The payload of a successful dispatch, unwrapping the `Outcome`-/// `{ result, logs }` envelope when the handler produced one.-fn payload(value: &Value, context: &str) -> Value {- if let Some(error) = value.get("error") {- panic!("{context}: unexpected JSON-RPC error: {error}");- }- let outer = value- .get("result")- .unwrap_or_else(|| panic!("{context}: missing result: {value}"));- match outer.get("result") {- Some(inner) => inner.clone(),- None => outer.clone(),- }-}--fn error_message(value: &Value, context: &str) -> String {- value- .get("error")- .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))- .get("message")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("{context}: error object has no message: {value}"))- .to_string()-}--// ── Candidate seeding ─────────────────────────────────────────────────────--fn now_secs() -> f64 {- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_secs_f64()-}--/// Push `repeats` observations of one (class, key, value) into the global-/// candidate buffer — the same buffer the production extractors push into.-///-/// `Explicit` and a recent `observed_at` are chosen deliberately: the stability-/// formula is `Σ(weight × exp(-Δt/half_life) × ln(1 + evidence_count))` with a-/// ×2.0 multiplier for an explicit cue, so several fresh explicit observations-/// clear `TAU_PROMOTE` (1.5) and enter as `Active`. Anything weaker would enter-/// as `Provisional` or `Candidate` and the assertions below would be about the-/// thresholds rather than about the controllers.-fn seed_candidate(class: FacetClass, key: &str, value: &str, repeats: i64) {- let buffer = candidate::global();- for i in 0..repeats {- buffer.push(LearningCandidate {- class,- key: key.to_string(),- value: value.to_string(),- cue_family: CueFamily::Explicit,- evidence: EvidenceRef::Episodic { episodic_id: i + 1 },- initial_confidence: 0.9,- observed_at: now_secs(),- });- }-}--/// Find one facet by its full `class/key` in a `list_facets` / `cache_stats`-/// style array.-fn find_facet<'a>(facets: &'a [Value], full_key: &str) -> Option<&'a Value> {- facets- .iter()- .find(|f| f.get("key").and_then(Value::as_str) == Some(full_key))-}--fn facets_of(payload: &Value, context: &str) -> Vec<Value> {- payload- .get("facets")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("{context}: expected a facets array: {payload}"))- .clone()-}--// ── Tests ─────────────────────────────────────────────────────────────────--/// The full facet lifecycle over RPC: rebuild from observations → list → get →-/// update → pin → unpin → cache_stats → forget → reset.-///-/// One case rather than nine, because these controllers share one durable row-/// and splitting them would either re-seed nine times or make each case depend-/// on the previous one's leftovers — the state-leak the wave brief forbids.-#[tokio::test]-async fn learning_facet_lifecycle_from_rebuild_to_reset() {- let _lock = env_lock();- let harness = setup().await;-- // Drain anything a sibling suite left, so `rebuild` scores only these.- let _ = candidate::global().drain();- seed_candidate(FacetClass::Style, PINNED_KEY, "terse", 6);- seed_candidate(FacetClass::Tooling, VOLATILE_KEY, "pnpm", 6);-- let pinned_full = format!("style/{PINNED_KEY}");- let volatile_full = format!("tooling/{VOLATILE_KEY}");-- // ── rebuild_cache: the detector promotes both observations ──- let rebuilt = rpc(- &harness.rpc_base,- 40_001,- "openhuman.learning_rebuild_cache",- json!({}),- )- .await;- let rebuilt = payload(&rebuilt, "learning_rebuild_cache");- for field in ["added", "evicted", "kept", "total_size"] {- assert!(- rebuilt.get(field).and_then(Value::as_u64).is_some(),- "rebuild_cache must report {field}: {rebuilt}"- );- }- assert!(- rebuilt.get("added").and_then(Value::as_u64).unwrap_or(0) >= 2,- "both seeded observations must be added as facets: {rebuilt}"- );- assert!(- rebuilt- .get("total_size")- .and_then(Value::as_u64)- .unwrap_or(0)- >= 2,- "the cache must hold at least the two seeded facets: {rebuilt}"- );-- // ── list_facets: both are visible, with the value they were seeded with ──- let listed = rpc(- &harness.rpc_base,- 40_002,- "openhuman.learning_list_facets",- json!({}),- )- .await;- let listed = payload(&listed, "learning_list_facets");- let facets = facets_of(&listed, "learning_list_facets");- assert_eq!(- listed.get("count").and_then(Value::as_u64),- Some(facets.len() as u64),- "count must agree with the array it summarises: {listed}"- );- let seeded = find_facet(&facets, &pinned_full)- .unwrap_or_else(|| panic!("the seeded style facet must be listed: {listed}"));- assert_eq!(seeded.get("value").and_then(Value::as_str), Some("terse"));- assert_eq!(- seeded.get("state").and_then(Value::as_str),- Some("active"),- "six fresh explicit cues clear TAU_PROMOTE: {seeded}"- );- assert_eq!(seeded.get("class").and_then(Value::as_str), Some("style"));- assert!(- seeded- .get("stability")- .and_then(Value::as_f64)- .unwrap_or(0.0)- > 0.0,- "a promoted facet carries a positive stability: {seeded}"- );- assert!(- find_facet(&facets, &volatile_full).is_some(),- "the seeded tooling facet must be listed too: {listed}"- );-- // ── list_facets(class=…): the filter narrows to one class ──- let styled = rpc(- &harness.rpc_base,- 40_003,- "openhuman.learning_list_facets",- json!({ "class": "style" }),- )- .await;- let styled = payload(&styled, "learning_list_facets style");- let styled_facets = facets_of(&styled, "learning_list_facets style");- assert!(- find_facet(&styled_facets, &pinned_full).is_some(),- "the style facet survives its own class filter: {styled}"- );- assert!(- find_facet(&styled_facets, &volatile_full).is_none(),- "a tooling facet must not appear under class=style: {styled}"- );-- // ── get_facet: found, with the same value list reported ──- let got = rpc(- &harness.rpc_base,- 40_004,- "openhuman.learning_get_facet",- json!({ "class": "style", "key": PINNED_KEY }),- )- .await;- let got = payload(&got, "learning_get_facet");- assert_eq!(got.get("found").and_then(Value::as_bool), Some(true));- assert_eq!(- got.get("facet")- .and_then(|f| f.get("value"))- .and_then(Value::as_str),- Some("terse")- );-- // ── update_facet: writes the new value AND pins, so it survives rebuilds ──- let updated = rpc(- &harness.rpc_base,- 40_005,- "openhuman.learning_update_facet",- json!({ "class": "style", "key": PINNED_KEY, "value": "exhaustive" }),- )- .await;- let updated = payload(&updated, "learning_update_facet");- let updated_facet = updated- .get("facet")- .unwrap_or_else(|| panic!("update_facet returns the facet: {updated}"));- assert_eq!(- updated_facet.get("value").and_then(Value::as_str),- Some("exhaustive"),- "the new value must be persisted, not echoed: {updated}"- );- assert_eq!(- updated_facet.get("user_state").and_then(Value::as_str),- Some("pinned"),- "an edit pins the facet so a later rebuild cannot revert it: {updated}"- );-- // Re-read through a different controller to prove it was written, not echoed.- let reread = rpc(- &harness.rpc_base,- 40_006,- "openhuman.learning_get_facet",- json!({ "class": "style", "key": PINNED_KEY }),- )- .await;- assert_eq!(- payload(&reread, "learning_get_facet after update")- .get("facet")- .and_then(|f| f.get("value"))- .and_then(Value::as_str),- Some("exhaustive")- );-- // ── unpin then pin: user_state round-trips on the volatile facet ──- let pinned = rpc(- &harness.rpc_base,- 40_007,- "openhuman.learning_pin_facet",- json!({ "class": "tooling", "key": VOLATILE_KEY }),- )- .await;- assert_eq!(- payload(&pinned, "learning_pin_facet")- .get("facet")- .and_then(|f| f.get("user_state"))- .and_then(Value::as_str),- Some("pinned")- );-- let unpinned = rpc(- &harness.rpc_base,- 40_008,- "openhuman.learning_unpin_facet",- json!({ "class": "tooling", "key": VOLATILE_KEY }),- )- .await;- assert_eq!(- payload(&unpinned, "learning_unpin_facet")- .get("facet")- .and_then(|f| f.get("user_state"))- .and_then(Value::as_str),- Some("auto"),- "unpin returns the facet to automatic lifecycle management"- );-- // ── cache_stats: the aggregate sees this suite's rows ──- let stats = rpc(- &harness.rpc_base,- 40_009,- "openhuman.learning_cache_stats",- json!({}),- )- .await;- let stats = payload(&stats, "learning_cache_stats");- let total = stats- .get("total")- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("cache_stats must report a total: {stats}"));- let by_state: u64 = ["active", "provisional", "candidate", "dropped"]- .iter()- .map(|k| stats.get(*k).and_then(Value::as_u64).unwrap_or(0))- .sum();- assert_eq!(- total, by_state,- "the per-state counts must partition the total: {stats}"- );- assert!(total >= 2, "both seeded facets are counted: {stats}");- assert!(- stats- .get("by_class")- .and_then(|c| c.get("style"))- .and_then(Value::as_u64)- .unwrap_or(0)- >= 1,- "by_class must attribute the style facet: {stats}"- );-- // ── forget_facet: drops the volatile one out of the visible list ──- let forgotten = rpc(- &harness.rpc_base,- 40_010,- "openhuman.learning_forget_facet",- json!({ "class": "tooling", "key": VOLATILE_KEY }),- )- .await;- let forgotten = payload(&forgotten, "learning_forget_facet");- let forgotten_facet = forgotten- .get("facet")- .unwrap_or_else(|| panic!("forget_facet returns the facet: {forgotten}"));- assert_eq!(- forgotten_facet.get("state").and_then(Value::as_str),- Some("dropped")- );- assert_eq!(- forgotten_facet.get("user_state").and_then(Value::as_str),- Some("forgotten"),- "forget must record the user's intent so a rebuild cannot resurface it"- );-- let after_forget = rpc(- &harness.rpc_base,- 40_011,- "openhuman.learning_list_facets",- json!({}),- )- .await;- let after_forget = facets_of(- &payload(&after_forget, "learning_list_facets after forget"),- "list after forget",- );- assert!(- find_facet(&after_forget, &volatile_full).is_none(),- "a dropped facet must leave the user-visible list"- );- assert!(- find_facet(&after_forget, &pinned_full).is_some(),- "forgetting one facet must not touch the other"- );-- // ── reset_cache: clears non-pinned rows, preserves pinned ones ──- let reset = rpc(- &harness.rpc_base,- 40_012,- "openhuman.learning_reset_cache",- json!({}),- )- .await;- let reset = payload(&reset, "learning_reset_cache");- assert!(- reset.get("deleted").and_then(Value::as_u64).is_some(),- "reset_cache must report a delete count: {reset}"- );- assert!(- reset- .get("pinned_preserved")- .and_then(Value::as_u64)- .unwrap_or(0)- >= 1,- "the pinned facet must be counted as preserved: {reset}"- );-- let survivor = rpc(- &harness.rpc_base,- 40_013,- "openhuman.learning_get_facet",- json!({ "class": "style", "key": PINNED_KEY }),- )- .await;- let survivor = payload(&survivor, "learning_get_facet after reset");- assert_eq!(- survivor.get("found").and_then(Value::as_bool),- Some(true),- "reset_cache must not delete a pinned facet: {survivor}"- );- assert_eq!(- survivor- .get("facet")- .and_then(|f| f.get("value"))- .and_then(Value::as_str),- Some("exhaustive"),- "and it must survive with the value the user set"- );-- harness.join.abort();-}--/// Failure paths across the facet controllers: missing params are refused by-/// name, and a key with no row is refused rather than silently created.-///-/// The wording asserted here is **`core::all::validate_params`'**, not the-/// handlers'. Every dispatch is schema-validated for required-presence, unknown-/// params and declared types *before* the handler body runs-/// (`crates/openhuman-core/src/core/all.rs:1334`), so the handlers' own-/// ``missing required `class` `` strings are unreachable over RPC. Asserting the-/// handler's wording would pass only if that uniform gate were removed.-#[tokio::test]-async fn learning_facet_controllers_refuse_bad_input_and_absent_keys() {- let _lock = env_lock();- let harness = setup().await;-- // `get_facet` needs both halves of the key.- let no_class = rpc(- &harness.rpc_base,- 40_101,- "openhuman.learning_get_facet",- json!({ "key": "verbosity" }),- )- .await;- assert!(- error_message(&no_class, "get_facet without class")- .contains("missing required param 'class'"),- "the refusal must name the param: {no_class}"- );-- let no_key = rpc(- &harness.rpc_base,- 40_102,- "openhuman.learning_get_facet",- json!({ "class": "style" }),- )- .await;- assert!(- error_message(&no_key, "get_facet without key").contains("missing required param 'key'"),- "the refusal must name the param: {no_key}"- );-- // `update_facet` needs a value on top of the key.- let no_value = rpc(- &harness.rpc_base,- 40_103,- "openhuman.learning_update_facet",- json!({ "class": "style", "key": "verbosity" }),- )- .await;- assert!(- error_message(&no_value, "update_facet without value")- .contains("missing required param 'value'"),- "the refusal must name the param: {no_value}"- );-- // A key with no row: `get` reports absence, the mutators refuse.- let absent = "e2e_learning_key_that_was_never_observed";- let missing = rpc(- &harness.rpc_base,- 40_104,- "openhuman.learning_get_facet",- json!({ "class": "style", "key": absent }),- )- .await;- let missing = payload(&missing, "get_facet absent");- assert_eq!(- missing.get("found").and_then(Value::as_bool),- Some(false),- "absence is a clean `found: false` on the read path: {missing}"- );- assert_eq!(- missing.get("facet"),- Some(&Value::Null),- "and it carries no facet: {missing}"- );-- for (id, method, context) in [- (40_105_i64, "openhuman.learning_update_facet", "update"),- (40_106, "openhuman.learning_pin_facet", "pin"),- (40_107, "openhuman.learning_unpin_facet", "unpin"),- ] {- let mut params = json!({ "class": "style", "key": absent });- if method.ends_with("update_facet") {- params- .as_object_mut()- .expect("params object")- .insert("value".into(), json!("anything"));- }- let response = rpc(&harness.rpc_base, id, method, params).await;- let message = error_message(&response, context);- assert!(- message.contains("facet not found") && message.contains(absent),- "{context} on an absent key must refuse and name it, got: {message}"- );- }-- // `forget_facet` is the odd one out and this pins the behaviour as it is,- // not as it should be: it answers `Ok` with a null facet for a key that was- // never observed, while its three sibling mutators refuse. The log line it- // emits says `state=dropped user_state=forgotten` for a row that does not- // exist, so a caller reading the log cannot tell a real forget from a typo.- // See `~/tinyhuman/bugs/e2e-wave-learning-forget-facet-succeeds-on-absent-key.md`.- let forgotten_nothing = rpc(- &harness.rpc_base,- 40_108,- "openhuman.learning_forget_facet",- json!({ "class": "style", "key": absent }),- )- .await;- let forgotten_nothing = payload(&forgotten_nothing, "forget_facet absent");- assert_eq!(- forgotten_nothing.get("facet"),- Some(&Value::Null),- "forget on an absent key reports success with no facet: {forgotten_nothing}"- );-- harness.join.abort();-}--/// `learning.save_profile` writes `PROFILE.md` into the active workspace, and-/// refuses a call with no body.-///-/// `summarize` is left at its default `false`: with it on the handler routes the-/// body through the LLM compressor, which needs a provider this hermetic suite-/// deliberately does not have.-#[tokio::test]-async fn learning_save_profile_writes_the_workspace_file() {- let _lock = env_lock();- let harness = setup().await;-- let body = "# E2E Profile\n\n- Prefers terse answers\n- Uses pnpm\n";- let saved = rpc(- &harness.rpc_base,- 40_201,- "openhuman.learning_save_profile",- json!({ "markdown": body }),- )- .await;- let saved = payload(&saved, "learning_save_profile");- assert_eq!(- saved.get("bytes").and_then(Value::as_u64),- Some(body.len() as u64),- "the reported byte count is the body's, not a rounded estimate: {saved}"- );- let reported = saved- .get("path")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("save_profile must report the path it wrote: {saved}"));-- let expected = harness.workspace.join("PROFILE.md");- assert_eq!(- std::fs::read_to_string(&expected).expect("PROFILE.md must exist on disk"),- body,- "the file content must be the markdown handed in"- );- assert!(- reported.ends_with("PROFILE.md"),- "the reported path must name the file: {reported}"- );-- // A second save replaces rather than appends.- let shorter = "# Replaced\n";- let replaced = rpc(- &harness.rpc_base,- 40_202,- "openhuman.learning_save_profile",- json!({ "markdown": shorter }),- )- .await;- assert_eq!(- payload(&replaced, "learning_save_profile replace")- .get("bytes")- .and_then(Value::as_u64),- Some(shorter.len() as u64)- );- assert_eq!(- std::fs::read_to_string(&expected).expect("PROFILE.md must still exist"),- shorter,- "save_profile truncates — a stale tail would corrupt the profile"- );-- // Failure path: no body at all.- let empty = rpc(- &harness.rpc_base,- 40_203,- "openhuman.learning_save_profile",- json!({}),- )- .await;- assert!(- error_message(&empty, "save_profile without markdown")- .contains("missing required param 'markdown'"),- "the refusal must name the param: {empty}"- );-- harness.join.abort();-}--/// `learning.linkedin_enrichment` runs a network pipeline (Gmail search → Apify-/// scrape → memory write). With `api_url` pointed at a closed port it must-/// surface a *pipeline* failure — not panic, not hang, and not report success-/// with an empty result.-#[tokio::test]-async fn learning_linkedin_enrichment_fails_loudly_without_a_backend() {- let _lock = env_lock();- let harness = setup().await;-- let response = rpc(- &harness.rpc_base,- 40_301,- "openhuman.learning_linkedin_enrichment",- json!({ "profile_url": "https://www.linkedin.com/in/e2e-nobody" }),- )- .await;-- // Either shape is a correct contract here, and both are asserted rather- // than one being assumed: the pipeline may refuse outright (no backend- // reachable) or complete with an empty, honestly-reported log. What it must- // never do is claim it scraped a profile it could not reach.- match response.get("error") {- Some(_) => {- let message = error_message(&response, "learning_linkedin_enrichment");- assert!(- !message.is_empty(),- "a refusal must carry a message: {response}"- );- }- None => {- let body = payload(&response, "learning_linkedin_enrichment");- assert!(- body.get("log").and_then(Value::as_array).is_some(),- "the pipeline always reports its stages: {body}"- );- assert_eq!(- body.get("profile_data"),- Some(&Value::Null),- "no backend means no scraped profile: {body}"- );- }- }-- harness.join.abort();-}diff --git a/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rs b/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rsdeleted file mode 100644index 5c454ff29d..0000000000--- a/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rs+++ /dev/null@@ -1,62 +0,0 @@-//! Raw integration coverage for the `flush_source_tree` re-entrancy latch-//! (#5779).-//!-//! `flush_source_tree_rpc` keeps a process-global `ACTIVE` set so a second-//! concurrent call for the same scope is answered "already running" instead of-//! being run twice. The version this replaced removed the scope from that set-//! only after a *successful* flush, so any failing call left its scope latched-//! for the life of the process: the retry a caller would naturally make came-//! back "already running" forever, and that source could never be flushed-//! again without a restart. #5779 made the release an RAII guard that drops on-//! every exit, error paths included.-//!-//! The test drives a failing flush and then retries the same scope. What is-//! asserted is that the retry is *attempted* — it must come back as a failure-//! from the driver lookup again, never as the latch's "already running"-//! success. Nothing here asserts which error the driver gives, only that the-//! second call got as far as asking.--use openhuman_core::config::Config;-use openhuman_core::memory::read_rpc;-use tempfile::TempDir;--const SCOPE: &str = "memory_flush_latch_raw_coverage_e2e::retry-after-failure";--/// A flush that fails must not latch its scope out of every later attempt.-///-/// Both calls are expected to fail: an integration test has no memory module-/// bound, so the handler cannot reach a driver serving `Tree`. That is exactly-/// the shape the bug needed — a flush that does not reach a successful return.-/// With the pre-#5779 latch the first failure would leave `SCOPE` in `ACTIVE`,-/// and the second call would short-circuit to `Ok` before touching the driver.-#[tokio::test]-async fn a_failed_flush_source_tree_can_be_retried_for_the_same_scope() {- let workspace = TempDir::new().expect("workspace tempdir");- let mut config = Config::default();- config.workspace_dir = workspace.path().to_path_buf();- config.subsystems.memory.driver = "null".into();-- let first = read_rpc::flush_source_tree_rpc(&config, SCOPE).await;- assert!(- first.is_err(),- "this test needs a flush that does not succeed, so the latch release is \- exercised on an error path; got {first:?}"- );-- let second = read_rpc::flush_source_tree_rpc(&config, SCOPE).await;-- // The failure mode being pinned: `Ok` here is the latch answering- // "already running" for a flush that is not running, which is what the- // pre-#5779 handler did for every scope whose first flush failed.- assert!(- second.is_err(),- "a retry after a failed flush must reach the driver again, not be \- short-circuited by the re-entrancy latch; got {second:?}"- );- assert_eq!(- format!("{first:?}"),- format!("{second:?}"),- "the retry must fail the same way the first attempt did — a different \- answer means it took a different path"- );-}diff --git a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rsdeleted file mode 100644index 221ea5afa1..0000000000--- a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs+++ /dev/null@@ -1,145 +0,0 @@-//! Round 23 raw coverage focused on memory_sync gaps.-//!-//! Local-only: temp workspaces and no real provider network. Run-//! single-threaded because HOME, OPENHUMAN_WORKSPACE, and config loading are-//! process globals.-//!-//! # What this file used to cover, and what happened to it-//!-//! tinymemory v1.13.4 deleted the in-process Composio pipeline outright (72-//! files, ~18.3k lines) — see-//! `crate::integrations::composio::providers`'s module docs for the-//! full account. This file originally instantiated the deleted engine's-//! `SlackProvider` / `NotionProvider` / `GmailProvider` directly against a-//! loopback HTTP router standing in for the Composio execute API, and-//! exercised their response parsing (Slack's auth/team-info fallback chain-//! when the `users:read.email` scope is missing, Notion's cursor pagination-//! into the memory tree, Gmail's nested-payload flattening and raw-HTML-//! opt-out).-//!-//! That parsing did not move anywhere reachable from this crate: it lives-//! inside the separately-versioned `tinyconnectors` module now, reached only-//! over the module bus via `openhuman.composio_get_user_profile` /-//! `run_sync_pass` (`integrations::composio::ops`). Driving that path for-//! real means a live loaded module — a network download of a pinned-//! release artifact plus a `dlopen`, which is exactly what this file's own-//! "no real provider network" design rules out, and which the CLAUDE.md-//! module-testing note says to run `#[ignore]`d with `OPENHUMAN_MODULE_PATH`-//! instead of in the default suite. So the three provider-specific tests-//! (`slack_profile_falls_back_to_auth_and_team_info_without_email_scope`,-//! `notion_profile_prefers_bot_owner_and_sync_paginates_into_memory_tree`,-//! `gmail_post_process_handles_nested_payloads_and_raw_html_opt_out`) test a-//! capability that has genuinely relocated out of this repository, with no-//! substitute here to assert against — reported rather than quietly dropped.-//! `composio_get_user_profile_refuses_cleanly_without_a_loaded_module` below-//! is what remains honestly testable of that call path from here: the-//! module-load gate the deleted providers used to sit behind.-//!-//! What genuinely stayed in this crate — persisting a fetched profile as-//! identity facets, loading them back, rendering them, and deleting them on-//! disconnect — is `integrations::composio::identity_store`, this host's own-//! port of the deleted engine's `sync::composio::providers::profile`-//! (see that module's doc comment for exactly what carried over and what did-//! not). `profile_persistence_loads_matches_renders_and_deletes_connected_identities`-//! below is that same test, updated onto the new (async, `&Config`-taking)-//! API. One piece of it could not be preserved: the deleted engine's-//! per-toolkit `is_self_identity(prefix, kind, value)` has no replacement-//! anywhere in `tinymemory-core` any more — only the cross-toolkit-//! `is_self_identity_any_toolkit` survived (it backs the memory tree's entity-//! matcher and was never toolkit-scoped to begin with). The toolkit-scoped-//! assertions are gone from this test as a result; see the src-side gap note-//! in the migration report.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::sync::{Mutex, OnceLock};--use tempfile::TempDir;--use openhuman_core::config::Config;-use openhuman_core::integrations::composio::ops::composio_get_user_profile;-use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,-};--static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();--fn ensure_memory_seams() {- crate::tinyhumans_boot::boot();- MEMORY_SEAMS_INIT.get_or_init(|| {- std::thread::Builder::new()- .name("memory-sync-round23-raw-coverage-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(|| {})- .expect("spawn round23 memory sync seam installer")- .join()- .expect("round23 memory sync seam installer panicked");- });-}--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|e| e.into_inner())-}--fn config_in(tmp: &TempDir) -> Config {- ensure_memory_seams();- let mut config = Config {- config_path: tmp.path().join("config.toml"),- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- ..Config::default()- };- config.secrets.encrypt = false;- config.memory_tree.embedding_endpoint = None;- config.memory_tree.embedding_model = None;- config.memory_tree.embedding_strict = false;- config-}--async fn persist_config(config: &Config) {- std::fs::create_dir_all(&config.workspace_dir).expect("workspace dir");- config.save().await.expect("save config");-}--fn store_session(config: &Config) {- AuthService::from_config(config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "round23-session-token",- HashMap::new(),- true,- )- .expect("store app session token");-}--/// `composio_get_user_profile` resolves the connection's toolkit through the-/// `tinyconnectors` module before it can fetch anything, so a build with-/// `modules.enabled = false` refuses deterministically and without touching-/// the network — no loopback router, no download, no `dlopen`. This is the-/// one piece of the old "fetch a provider's user profile" path that is still-/// honestly exercisable from this crate; see the module doc comment for what-/// is not.-#[tokio::test]-async fn composio_get_user_profile_refuses_cleanly_without_a_loaded_module() {- let _guard = env_lock();- let tmp = TempDir::new().expect("tempdir");- let _workspace = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());- let _home = EnvVarGuard::set_path("HOME", tmp.path());-- let mut config = config_in(&tmp);- config.modules.enabled = false;- persist_config(&config).await;- store_session(&config);-- let result = composio_get_user_profile(&config, "conn-slack-23").await;- let error = result.expect_err("profile fetch must refuse without a loaded connectors module");- assert!(- error.contains("modules are disabled in configuration"),- "unexpected error: {error}"- );-}diff --git a/tests/support/memory_engine_fixture.rs b/tests/support/memory_engine_fixture.rsdeleted file mode 100644index 44729d83ff..0000000000--- a/tests/support/memory_engine_fixture.rs+++ /dev/null@@ -1,645 +0,0 @@-//! Shared harness for the memory-engine e2e suites: a hosted-CortexDB double,-//! env isolation, and a `Fixture` that boots the JSON-RPC router with the-//! module loaded and a backend API key stored.-//!-//! Include with `#[path = "support/memory_engine_fixture.rs"] mod fixture;`.--#![allow(dead_code, clippy::await_holding_lock)]--#[path = "memory_module.rs"]-pub mod memory_module;-#[path = "tinyhumans_boot.rs"]-pub mod tinyhumans_boot;--use std::collections::HashSet;-use std::net::SocketAddr;-use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};-use std::sync::{Arc, Mutex, OnceLock};-use std::time::Duration;--use axum::extract::{Path as UrlPath, Query, State};-use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};-use axum::routing::{get, post};-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::tempdir;--use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};-use openhuman_rpc::server::build_core_http_router;--pub const TEST_RPC_TOKEN: &str = "memory-engine-e2e-token";-pub const TEST_API_KEY: &str = "tiny_live_memory_engine_e2e";-pub const NS: &str = "engine-e2e";--// ── Hosted CortexDB double ──────────────────────────────────────────────────--#[derive(Default)]-pub struct HostedState {- pub events: Mutex<Vec<Value>>,- pub idempotency: Mutex<std::collections::BTreeMap<String, (String, String)>>,- pub claims: Mutex<HashSet<String>>,- pub bearers: Mutex<Vec<String>>,- pub next_id: Mutex<u64>,- /// When non-zero every `/memory/*` call fails with this status.- pub force_status: AtomicU16,- /// Milliseconds every `experience` write is delayed by (0 = none).- pub delay_ms: AtomicU64,- /// What `GET /memory/{facts,beliefs,understanding}` answers, by- /// `(layer, scope)`.- pub layers: Mutex<std::collections::HashMap<(String, String), Vec<Value>>>,-}--pub type Hosted = Arc<HostedState>;--pub fn err(status: u16, code: &str) -> (StatusCode, Json<Value>) {- (- StatusCode::from_u16(status).unwrap(),- Json(json!({ "success": false, "error": format!("failed: {code}"), "errorCode": code })),- )-}--pub fn ok(data: Value) -> (StatusCode, Json<Value>) {- (- StatusCode::OK,- Json(json!({ "success": true, "data": data })),- )-}--pub fn gate(state: &Hosted, headers: &HeaderMap) -> Option<(StatusCode, Json<Value>)> {- let token = headers- .get(AUTHORIZATION)- .and_then(|v| v.to_str().ok())- .and_then(|v| v.strip_prefix("Bearer "))- .unwrap_or_default()- .to_string();- state.bearers.lock().unwrap().push(token.clone());- if token.is_empty() {- return Some(err(401, "UNAUTHORIZED"));- }- match state.force_status.load(Ordering::SeqCst) {- 0 => None,- 401 => Some(err(401, "UNAUTHORIZED")),- 402 => Some(err(402, "USER_INSUFFICIENT_CREDITS")),- other => Some(err(other, "UPSTREAM_ERROR")),- }-}--pub async fn experience(- State(state): State<Hosted>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let delay = state.delay_ms.load(Ordering::SeqCst);- if delay > 0 {- tokio::time::sleep(Duration::from_millis(delay)).await;- }- if let Some(claim) = headers.get("idempotency-key").and_then(|v| v.to_str().ok()) {- if !state.claims.lock().unwrap().insert(claim.to_string()) {- return err(409, "CONFLICT");- }- }- let key = body["idempotency_key"]- .as_str()- .unwrap_or_default()- .to_string();- let text = body["content"]["text"]- .as_str()- .unwrap_or_default()- .to_string();- if let Some((seen, id)) = state.idempotency.lock().unwrap().get(&key) {- return if seen == &text {- ok(json!({ "event_id": id, "replayed_from_idempotency": true }))- } else {- err(409, "IDEMPOTENCY_CONFLICT")- };- }- let id = {- let mut next = state.next_id.lock().unwrap();- *next += 1;- format!("evt_{}", *next)- };- let offset = state.events.lock().unwrap().len() as u64 * 2 + 2;- state- .idempotency- .lock()- .unwrap()- .insert(key, (text, id.clone()));- // The engine keeps the caller's context (labels, `observed_at`) and stamps- // its own `recorded_at`; the hosted families look records up by label.- let mut context = body["context"].clone();- if !context.is_object() {- context = json!({});- }- context["recorded_at"] = json!("2026-09-02T00:00:00Z");- let mut event = json!({- "id": id,- "scope": body["scope"],- "modality": body["modality"],- "wal_offset": offset,- "content": body["content"],- "context": context,- });- if !body["directives"].is_null() {- event["directives"] = body["directives"].clone();- }- state.events.lock().unwrap().push(event);- ok(json!({ "event_id": id, "status": "captured", "replayed_from_idempotency": false }))-}--pub async fn events(- State(state): State<Hosted>,- headers: HeaderMap,- Query(params): Query<std::collections::BTreeMap<String, String>>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let scope = params.get("scope").cloned().unwrap_or_default();- let cursor: usize = params- .get("cursor")- .and_then(|v| v.parse().ok())- .unwrap_or(0);- let limit: usize = params- .get("limit")- .and_then(|v| v.parse().ok())- .unwrap_or(50);- // The engine splits its label filter on commas and keeps an event carrying- // any one of the pieces.- let wanted: Vec<String> = params- .get("labels")- .map(|labels| labels.split(',').map(|l| l.trim().to_string()).collect())- .unwrap_or_default();- let labelled = |event: &Value| {- wanted.is_empty()- || event["context"]["labels"].as_array().is_some_and(|labels| {- labels- .iter()- .filter_map(Value::as_str)- .any(|label| wanted.iter().any(|w| w == label))- })- };- let mut stream = Vec::new();- for event in state.events.lock().unwrap().iter().rev() {- if event["scope"].as_str() == Some(scope.as_str()) && labelled(event) {- stream.push(event.clone());- stream.push(event.clone());- }- }- let page: Vec<Value> = stream.iter().skip(cursor).take(limit).cloned().collect();- let next = cursor + page.len();- ok(json!({ "items": page, "has_more": next < stream.len(), "next_cursor": next.to_string() }))-}--pub async fn recall(- State(state): State<Hosted>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let scope = body["scope"].as_str().unwrap_or_default();- let query = body["query"].as_str().unwrap_or_default().to_lowercase();- // `descend` recalls the scope and everything under it.- let descend = body["view"].as_str() == Some("descend");- // A metadata label filter keeps an event carrying any one of the labels.- let wanted: Vec<&str> = body- .pointer("/filters/metadata/labels")- .and_then(Value::as_array)- .map(|labels| labels.iter().filter_map(Value::as_str).collect())- .unwrap_or_default();- let budget = body- .pointer("/budgets/per_layer_limits/events")- .and_then(Value::as_u64)- .map_or(usize::MAX, |limit| limit as usize);- let hits: Vec<Value> = state- .events- .lock()- .unwrap()- .iter()- .filter(|e| {- e["scope"].as_str().is_some_and(|held| {- held == scope || (descend && held.starts_with(&format!("{scope}/")))- })- })- .filter(|e| {- wanted.is_empty()- || e["context"]["labels"].as_array().is_some_and(|labels| {- labels- .iter()- .filter_map(Value::as_str)- .any(|label| wanted.contains(&label))- })- })- .filter(|e| {- query.is_empty()- || e["content"]["text"]- .as_str()- .is_some_and(|t| t.to_lowercase().contains(&query))- })- .map(|e| {- let mut hit = e.clone();- if let Some(text) = e["content"]["text"].as_str() {- hit["content"]["text"] = json!(format!("[user] {text}"));- }- hit- })- .take(budget)- .collect();- ok(json!({ "pack_id": "pack_test", "layers": { "events": hits } }))-}--pub async fn scopes(- State(state): State<Hosted>,- headers: HeaderMap,- Query(params): Query<std::collections::HashMap<String, String>>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let limit: usize = params- .get("limit")- .and_then(|v| v.parse().ok())- .unwrap_or(50);- // A prefix names a scope and everything under it.- let prefix = params.get("prefix").cloned();- let mut paths: Vec<String> = state- .events- .lock()- .unwrap()- .iter()- .filter_map(|e| e["scope"].as_str().map(str::to_string))- .filter(|path| {- prefix- .as_deref()- .is_none_or(|p| path == p || path.starts_with(&format!("{p}/")))- })- .collect();- paths.sort();- paths.dedup();- paths.truncate(limit);- ok(json!({ "items": paths.into_iter().map(|p| json!({ "path": p })).collect::<Vec<_>>() }))-}--pub async fn event_by_id(- State(state): State<Hosted>,- headers: HeaderMap,- UrlPath(id): UrlPath<String>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let found = state- .events- .lock()- .unwrap()- .iter()- .find(|e| e["id"].as_str() == Some(id.as_str()))- .cloned();- match found {- Some(event) => ok(event),- None => err(404, "NOT_FOUND"),- }-}--pub async fn forget(- State(state): State<Hosted>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let ids: Vec<String> = body["selector"]["memory_ids"]- .as_array()- .map(|a| {- a.iter()- .filter_map(|v| v.as_str().map(str::to_string))- .collect()- })- .unwrap_or_default();- let before = state.events.lock().unwrap().len();- state- .events- .lock()- .unwrap()- .retain(|e| !ids.contains(&e["id"].as_str().unwrap_or_default().to_string()));- let deleted = before - state.events.lock().unwrap().len();- ok(json!({ "deleted": { "events": deleted }, "requested": ids.len(), "matched": deleted }))-}--/// One page of a derived layer: everything seeded for the scope, in one page.-pub async fn layer(- State(state): State<Hosted>,- headers: HeaderMap,- uri: axum::http::Uri,- Query(params): Query<std::collections::BTreeMap<String, String>>,-) -> (StatusCode, Json<Value>) {- if let Some(early) = gate(&state, &headers) {- return early;- }- let name = uri- .path()- .rsplit('/')- .next()- .unwrap_or_default()- .to_string();- let scope = params.get("scope").cloned().unwrap_or_default();- let items = state- .layers- .lock()- .unwrap()- .get(&(name, scope))- .cloned()- .unwrap_or_default();- ok(json!({ "items": items, "has_more": false }))-}--pub async fn start_hosted() -> (String, Hosted) {- let state: Hosted = Arc::new(HostedState::default());- let app = Router::new()- .route("/memory/experience", post(experience))- .route("/memory/events", get(events))- .route("/memory/events/{id}", get(event_by_id))- .route("/memory/recall", post(recall))- .route("/memory/forget", post(forget))- .route("/memory/scopes", get(scopes))- .route("/memory/facts", get(layer))- .route("/memory/beliefs", get(layer))- .route("/memory/understanding", get(layer))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr: SocketAddr = listener.local_addr().unwrap();- tokio::spawn(async move { axum::serve(listener, app).await });- (format!("http://{addr}"), state)-}--// ── Harness ─────────────────────────────────────────────────────────────────--pub struct EnvVarGuard {- key: &'static str,- old: Option<String>,-}--impl EnvVarGuard {- pub fn set_to_path(key: &'static str, path: &Path) -> Self {- let old = std::env::var(key).ok();- std::env::set_var(key, path.as_os_str());- Self { key, old }- }- pub fn unset(key: &'static str) -> Self {- let old = std::env::var(key).ok();- std::env::remove_var(key);- Self { key, old }- }-}--impl Drop for EnvVarGuard {- fn drop(&mut self) {- match &self.old {- Some(v) => std::env::set_var(self.key, v),- None => std::env::remove_var(self.key),- }- }-}--pub static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();-pub static KEYRING_INIT: OnceLock<()> = OnceLock::new();-pub static AUTH_INIT: OnceLock<()> = OnceLock::new();-pub static SEAMS_INIT: OnceLock<()> = OnceLock::new();--pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {- KEYRING_INIT.get_or_init(|| unsafe {- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");- });- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {- Ok(guard) => guard,- Err(poisoned) => poisoned.into_inner(),- }-}--/// The one workspace the process's memory module and every case share.-pub fn shared_workspace() -> &'static Path {- static SHARED: OnceLock<PathBuf> = OnceLock::new();- SHARED.get_or_init(|| {- let tmp = tempdir().expect("shared workspace tempdir");- let path = tmp.path().join("workspace");- std::fs::create_dir_all(&path).expect("shared workspace dir");- std::mem::forget(tmp);- path- })-}--/// The config file that workspace resolves to (legacy sibling layout).-pub fn shared_config_path() -> PathBuf {- shared_workspace()- .parent()- .expect("workspace parent")- .join(".openhuman")- .join("config.toml")-}--pub fn ensure_seams() {- SEAMS_INIT.get_or_init(|| {- std::thread::Builder::new()- .name("memory-engine-e2e-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(|| {- let config = Arc::new(openhuman_core::config::Config {- workspace_dir: shared_workspace().to_path_buf(),- ..openhuman_core::config::Config::default()- });- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(config);- #[cfg(not(feature = "modules"))]- let _ = config;- })- .expect("spawn seam installer")- .join()- .expect("seam installer panicked");- });-}--pub fn ensure_rpc_auth() {- AUTH_INIT.get_or_init(|| {- tinyhumans_boot::boot();- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };- let dir = std::env::temp_dir().join("openhuman-memory-engine-e2e-auth");- init_rpc_token(&dir).expect("init rpc token");- });-}--pub fn run_on_big_stack<F, Fut>(name: &str, factory: F)-where- F: FnOnce() -> Fut + Send + 'static,- Fut: std::future::Future<Output = ()> + 'static,-{- std::thread::Builder::new()- .name(name.to_string())- .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)- .spawn(move || {- let rt = tokio::runtime::Builder::new_multi_thread()- .worker_threads(2)- .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)- .enable_all()- .build()- .expect("runtime");- rt.block_on(factory());- })- .expect("spawn")- .join()- .expect("test body panicked");-}--pub async fn rpc(base: &str, method: &str, params: Value) -> Value {- let resp = reqwest::Client::builder()- .timeout(Duration::from_secs(120))- .build()- .unwrap()- .post(format!("{base}/rpc"))- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))- .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params }))- .send()- .await- .unwrap_or_else(|e| panic!("POST {method}: {e}"));- assert!(- resp.status().is_success(),- "HTTP {} for {method}",- resp.status()- );- resp.json().await.expect("json body")-}--pub fn result_of<'a>(v: &'a Value, ctx: &str) -> &'a Value {- if let Some(e) = v.get("error") {- panic!("{ctx}: JSON-RPC error: {e}");- }- let r = v- .get("result")- .unwrap_or_else(|| panic!("{ctx}: no result: {v}"));- if r.get("logs").is_some() {- r.get("result").unwrap_or(r)- } else {- r- }-}--pub fn error_message(v: &Value, ctx: &str) -> String {- v.pointer("/error/message")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("{ctx}: expected a JSON-RPC error, got {v}"))- .to_string()-}--/// Everything a case needs: the hosted double, the RPC base URL and the env.-pub struct Fixture {- pub _lock: std::sync::MutexGuard<'static, ()>,- pub _guards: Vec<EnvVarGuard>,- pub _tmp: tempfile::TempDir,- pub hosted: Hosted,- pub origin: String,- pub base: String,- pub join: tokio::task::JoinHandle<Result<(), std::io::Error>>,-}--impl Fixture {- pub async fn new() -> Self {- let lock = env_lock();- let tmp = tempdir().expect("home tempdir");- let guards = vec![- EnvVarGuard::set_to_path("HOME", tmp.path()),- EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", shared_workspace()),- EnvVarGuard::unset("OPENHUMAN_MEMORY_DRIVER"),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_BACKEND_API_KEY"),- ];- ensure_rpc_auth();- ensure_seams();- let (origin, hosted) = start_hosted().await;-- // A fresh config every case: the previous case's committed engine must- // not leak into this one.- let config_path = shared_config_path();- std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();- std::fs::write(- &config_path,- format!(- "api_url = \"{origin}\"\ndefault_model = \"e2e-mock-model\"\n\n[secrets]\nencrypt = false\n"- ),- )- .unwrap();-- memory_module::settle().await;- let config = openhuman_core::config::load_config_with_timeout()- .await- .expect("load config");- openhuman_core::security::credentials::api_key::store_api_key(&config, TEST_API_KEY)- .expect("store the backend api key");-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- let app = build_core_http_router(false);- let join = tokio::spawn(async move { axum::serve(listener, app).await });- Self {- _lock: lock,- _guards: guards,- _tmp: tmp,- hosted,- origin,- base: format!("http://{addr}"),- join,- }- }-- pub async fn call(&self, method: &str, params: Value) -> Value {- rpc(&self.base, method, params).await- }-- pub async fn state(&self) -> Value {- let v = self.call("openhuman.memory_engine_get", json!({})).await;- result_of(&v, "engine_get").clone()- }-- /// Poll a migration job to a terminal state.- pub async fn wait_job(&self, job_id: &str) -> Value {- for _ in 0..200 {- let v = self- .call(- "openhuman.memory_engine_migrate_status",- json!({ "job_id": job_id }),- )- .await;- let status = result_of(&v, "engine_migrate_status").clone();- if status["state"] != "running" {- return status;- }- tokio::time::sleep(Duration::from_millis(50)).await;- }- panic!("migration job {job_id} did not finish");- }-- pub async fn put_doc(&self, key: &str, content: &str) {- let v = self- .call(- "openhuman.memory_doc_put",- json!({- "namespace": NS, "key": key, "title": key, "content": content,- "source_type": "doc", "priority": "medium", "tags": [],- "metadata": null, "category": "core"- }),- )- .await;- result_of(&v, "doc_put");- }-}--impl Drop for Fixture {- fn drop(&mut self) {- self.join.abort();- }-}diff --git a/tests/support/memory_module.rs b/tests/support/memory_module.rsdeleted file mode 100644index 29d3c939ab..0000000000--- a/tests/support/memory_module.rs+++ /dev/null@@ -1,39 +0,0 @@-//! Wait out the memory module's load in a suite that boots the core in-process.-//!-//! The module is loaded once per process, by whichever caller asks first, and-//! for the whole of that load a memory call that reaches the driver answers-//! "memory is still starting ... try again in a moment". A test sharing its-//! process with earlier memory tests usually finds the module already loaded;-//! one running in its own process (cargo nextest) always asks during the load.-//! Call [`settle`] after the test's workspace env is in place and before its-//! first memory call. This is the in-crate `memory::test_support::-//! settle_memory_module` for suites outside the core.-//!-//! Include with `#[path = "support/memory_module.rs"] mod memory_module;`.--#![allow(dead_code)]--use std::time::Duration;--/// Load the memory module for the core's current config, waiting up to 60 s.-///-/// A load that fails is left for the test to observe through its own calls;-/// only a load still running after the bound panics, because every assertion-/// after it would race that load.-pub async fn settle() {- let config = openhuman_core::config::load_config_with_timeout()- .await- .expect("load config to settle the memory module");- match openhuman_core::modules::ops::ensure_loaded_within(- &config,- openhuman_core::memory::binding::MODULE_ID,- Some(Duration::from_secs(60)),- )- .await- {- Ok(()) | Err(openhuman_core::modules::ops::LoadError::Failed(_)) => {}- Err(openhuman_core::modules::ops::LoadError::StillLoading) => {- panic!("the memory module did not finish loading within 60s")- }- }-}diff --git a/tests/support/memory_rpc.rs b/tests/support/memory_rpc.rsdeleted file mode 100644index 64bed26f0d..0000000000--- a/tests/support/memory_rpc.rs+++ /dev/null@@ -1,92 +0,0 @@-//! Boilerplate shared by the memory RPC suites that serve the core router-//! in-process (`memory_sources_e2e`, `memory_tree_health_e2e`,-//! `tree_summarizer_e2e`): the memory-module policy seam, a minimal workspace-//! config, a served router with the memory module settled, and the-//! `Outcome`-unwrapping `ok`.-//!-//! Declare it at the root of an aggregated target next to `rpc_auth` and-//! `memory_module`.--#![allow(dead_code)]--use std::path::Path;-use std::sync::{Arc, OnceLock};--use openhuman_rpc::server::build_core_http_router;-use serde_json::Value;--use crate::memory_module;-use crate::rpc_auth::ensure_rpc_auth;--static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();--/// Install the memory module's policy once per process, on a thread with a-/// stack deep enough for the policy build (a default test stack overflows).-pub fn ensure_memory_seams() {- MEMORY_SEAMS_INIT.get_or_init(|| {- std::thread::Builder::new()- .name("memory-e2e-seams".to_string())- .stack_size(8 * 1024 * 1024)- .spawn(|| {- let config = Arc::new(openhuman_core::config::Config::default());- #[cfg(feature = "modules")]- openhuman_core::modules::memory::set_modules_policy(config);- })- .expect("spawn memory seam installer")- .join()- .expect("memory seam installer panicked");- });-}--/// Write the minimal workspace config (plus the `users/local` copy) under `dir`.-pub fn write_config(dir: &Path) {- std::fs::create_dir_all(dir).expect("mkdir");- let cfg = r#"-default_model = "e2e-mock-model"-default_temperature = 0.7--[secrets]-encrypt = false--[memory_tree]-embedding_strict = false-"#;- std::fs::write(dir.join("config.toml"), cfg).expect("write config");-- let user_dir = dir.join("users").join("local");- std::fs::create_dir_all(&user_dir).expect("mkdir user dir");- std::fs::write(user_dir.join("config.toml"), cfg).expect("write user config");-}--/// Serve the core router with the memory module loaded; returns the base URL.-///-/// Every flow reaches the memory module, so wait out its load: a test running-/// in its own process would otherwise race it (see `memory_module`).-pub async fn serve() -> (String, tokio::task::JoinHandle<Result<(), std::io::Error>>) {- ensure_memory_seams();- ensure_rpc_auth();- memory_module::settle().await;- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind");- let addr = listener.local_addr().expect("addr");- let handle =- tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });- (format!("http://{addr}"), handle)-}--/// The envelope's payload: `result.result` when the `Outcome` wraps one next to-/// its `logs`, else `result`. Panics with `ctx` on a JSON-RPC error.-pub fn ok(v: &Value, ctx: &str) -> Value {- if let Some(err) = v.get("error") {- panic!("{ctx}: JSON-RPC error: {err}");- }- let outer = v- .get("result")- .unwrap_or_else(|| panic!("{ctx}: missing result: {v}"));- if let Some(inner) = outer.get("result") {- inner.clone()- } else {- outer.clone()- }-}