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
test(memory): restore host coverage for three RPC handlers
Shanue0de0a62c306
diff --git a/src/openhuman/memory/sources/rpc_tests.rs b/src/openhuman/memory/sources/rpc_tests.rsindex 04f71bacca..23b33bbd1f 100644--- a/src/openhuman/memory/sources/rpc_tests.rs+++ b/src/openhuman/memory/sources/rpc_tests.rs@@ -163,3 +163,126 @@ fn composio_rows_dispatch_to_the_connector_and_everything_else_to_the_driver() {"the refusal must name the row and say what to do about it, got: {error}");}++// ── what `add_rpc` owns ─────────────────────────────────────────────────────+//+// The handler generates the source id, maps the request into a+// `MemorySourceEntry`, and applies conservative per-kind caps before the+// registry sees it. Only the first two are its own code; the third is+// `tinymemory-sources`' `apply_kind_defaults`, and what belongs here is that+// this handler *calls* it — an add whose caps the user left unset must not+// reach the registry uncapped.+//+// Covered only by `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs`+// before now, which went with the engine (#6161) although none of this is the+// engine's (#6172).++/// Pins `OPENHUMAN_WORKSPACE` for the duration, holding the crate's env lock so+/// concurrent tests cannot observe the change. `add_rpc` writes through+/// `registry::add_source`, which resolves its config with+/// `load_config_with_timeout` — process-global, so the workspace has to be+/// pinned rather than passed.+struct WorkspaceEnvGuard {+ _env_lock: std::sync::MutexGuard<'static, ()>,+ previous: Option<std::ffi::OsString>,+}++impl WorkspaceEnvGuard {+ fn pin(workspace: &std::path::Path) -> Self {+ let env_lock = crate::openhuman::config::TEST_ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ std::env::set_var("OPENHUMAN_WORKSPACE", workspace);+ Self {+ _env_lock: env_lock,+ previous,+ }+ }+}++impl Drop for WorkspaceEnvGuard {+ fn drop(&mut self) {+ match self.previous.take() {+ Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),+ None => std::env::remove_var("OPENHUMAN_WORKSPACE"),+ }+ }+}++fn github_add_request() -> AddRequest {+ AddRequest {+ kind: tinymemory_sources::types::SourceKind::GithubRepo,+ label: "A repository".into(),+ enabled: true,+ toolkit: None,+ connection_id: None,+ path: None,+ glob: None,+ url: Some("https://github.invalid/owner/repo".into()),+ branch: None,+ paths: Vec::new(),+ // The three the caller left unset, which is the whole point.+ max_commits: None,+ max_issues: None,+ max_prs: None,+ query: None,+ since_days: None,+ max_items: None,+ selector: None,+ max_tokens_per_sync: None,+ max_cost_per_sync_usd: None,+ sync_depth_days: None,+ }+}++#[tokio::test]+async fn add_generates_an_id_and_caps_a_request_that_left_its_limits_unset() {+ let tmp = tempfile::TempDir::new().expect("tempdir");+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace dir");+ let _env = WorkspaceEnvGuard::pin(&workspace);++ let added = add_rpc(github_add_request())+ .await+ .expect("add_rpc")+ .value+ .source;++ // ── the id is the handler's ─────────────────────────────────────────────+ //+ // The caller never supplies one; a request that could name its own id would+ // let two sources collide by construction.+ assert!(+ added.id.starts_with("src_") && added.id.len() == "src_".len() + 32,+ "the handler must mint a `src_<uuid simple>` id, got {:?}",+ added.id+ );++ // ── the caps came from somewhere ────────────────────────────────────────+ //+ // Asserted as "no longer None" plus the concrete GitHub values, because the+ // two say different things: the first is that this handler applies defaults+ // at all, the second that it applied *these* — a handler that filled them+ // with zeros would satisfy the first and cap every sync at nothing.+ assert_eq!(added.max_prs, Some(10), "per-kind PR cap");+ assert_eq!(added.max_issues, Some(10), "per-kind issue cap");+ assert_eq!(added.max_commits, Some(50), "per-kind commit cap");++ // ── and it reached the registry ─────────────────────────────────────────+ //+ // The response alone would be satisfied by a handler that shaped an entry+ // and dropped it.+ let fetched = get_rpc(GetRequest {+ id: added.id.clone(),+ })+ .await+ .expect("get_rpc")+ .value+ .source;+ assert_eq!(+ fetched.map(|s| s.id),+ Some(added.id.clone()),+ "the added source is not readable back from the registry"+ );+}diff --git a/src/openhuman/memory/sync/composio/providers/slack/rpc_tests.rs b/src/openhuman/memory/sync/composio/providers/slack/rpc_tests.rsindex f051d6fdcb..dd72bbb6a3 100644--- a/src/openhuman/memory/sync/composio/providers/slack/rpc_tests.rs+++ b/src/openhuman/memory/sync/composio/providers/slack/rpc_tests.rs@@ -93,3 +93,101 @@ async fn list_slack_connections_resolves_direct_variant_when_mode_is_direct() {// a valid empty envelope), that's also acceptable — the// factory still routed correctly.}++// ── the status surface's degraded shape ─────────────────────────────────────+//+// `sync_status_rpc` does two things nothing asserted: it filters the connection+// list to slack rows that are ACTIVE, and it answers a fixed zero-value shape+// because per-connection sync detail is no longer readable — the connector+// module keeps its cursor internally.+//+// The deleted `slack_sync_status_rpc_reports_the_degraded_zero_value_shape`+// covered exactly this, in `tests/raw_coverage/memory_sync_tree_round21_*`,+// which went with the engine (#6161) although the assertion was never about the+// engine. Restored here against a local mock backend (#6172).++#[tokio::test]+async fn status_filters_to_active_slack_and_reports_the_degraded_zero_value_shape() {+ use crate::openhuman::security::credentials::{+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,+ };+ use serde_json::json;+ use std::collections::HashMap;+ use wiremock::matchers::{method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/agent-integrations/composio/connections"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": { "connections": [+ // The one row that must survive both filters.+ { "id": "conn-slack-active", "toolkit": "slack", "status": "ACTIVE" },+ // Dropped by the status filter…+ { "id": "conn-slack-pending", "toolkit": "slack", "status": "PENDING" },+ // …and this one by the toolkit filter.+ { "id": "conn-gmail-active", "toolkit": "gmail", "status": "ACTIVE" },+ ] }+ })))+ .mount(&server)+ .await;++ let tmp = tempfile::tempdir().expect("tempdir");+ 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.api_url = Some(server.uri());+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace dir");+ AuthService::from_config(&config)+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ "test-session-token",+ HashMap::new(),+ true,+ )+ .expect("store app session token");++ let outcome = sync_status_rpc(&config, SyncStatusRequest::default())+ .await+ .expect("status rpc");++ // ── the filter ──────────────────────────────────────────────────────────+ assert_eq!(+ outcome.value.connections.len(),+ 1,+ "only the ACTIVE slack connection qualifies; got {:?}",+ outcome.value.connections+ );+ let row = &outcome.value.connections[0];+ assert_eq!(row.connection_id, "conn-slack-active");++ // ── the degraded shape ──────────────────────────────────────────────────+ //+ // Four fixed zero values, asserted individually rather than as a struct+ // comparison: each one is a separate promise to the status table, and a+ // struct literal would hide which of them a future change broke.+ assert_eq!(row.per_channel_cursors, "{}");+ assert_eq!(row.synced_ids_count, 0);+ assert_eq!(row.requests_used_today, 0);+ assert_eq!(row.daily_request_limit, 0);++ // ── and the log that explains it ────────────────────────────────────────+ //+ // The zeros are indistinguishable from "a connection that has synced+ // nothing yet", so the log line is what tells an operator the detail is+ // gone rather than empty. Without it the shape above is a silent lie.+ assert!(+ outcome+ .logs+ .iter()+ .any(|line| line.contains("connections=1") && line.contains("no longer available")),+ "the status log must explain the degraded read: {:?}",+ outcome.logs+ );+}diff --git a/src/openhuman/memory/sync/sync_status/rpc_tests.rs b/src/openhuman/memory/sync/sync_status/rpc_tests.rsindex c24d47601d..5c2329ed91 100644--- a/src/openhuman/memory/sync/sync_status/rpc_tests.rs+++ b/src/openhuman/memory/sync/sync_status/rpc_tests.rs@@ -10,3 +10,243 @@ fn response_keeps_top_level_statuses_array() {.get("statuses").is_some_and(serde_json::Value::is_array));}++// ── the degradation contract ────────────────────────────────────────────────+//+// `status_list_rpc` answers `Ok` with an empty list on **every** failure path:+// the binding failing to resolve, the bound driver not serving `SourceSync`,+// and the driver's own call returning an error. Its comment says this is+// inherited behaviour kept deliberately — "this surface renders a status table,+// and every caller of it today treats 'no rows' as 'nothing syncing'" — and+// that tightening it belongs with whoever owns that screen.+//+// Nothing asserted any of the three. They were covered only by+// `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs`, a 4,800-line target+// that drove forty subjects through an in-process engine and went with it+// (#6161). A later "tighten this into an RPC error" would turn a polled status+// table into a visible failure, and no test would have objected (#6172).++use crate::openhuman::config::Config;+use crate::openhuman::memory::api::provider::MemoryProvider;+use crate::openhuman::memory::binding;+use std::sync::Arc;+use tempfile::TempDir;+use tinymemory_api::null::NullMemoryProvider;++fn degradation_config() -> (TempDir, Config) {+ let tmp = TempDir::new().expect("tempdir");+ let mut cfg = Config::default();+ cfg.workspace_dir = tmp.path().to_path_buf();+ cfg.config_path = tmp.path().join("config.toml");+ (tmp, cfg)+}++/// A driver that serves `SourceSync` and fails the call — the third path, which+/// neither the null driver nor a healthy one can produce.+#[derive(Debug, Default)]+struct FailingSourceSync {+ /// Proves the handler reached this driver. An empty list is also what an+ /// *unreached* driver yields, so the assertion below would pass without it+ /// even if the binding never resolved here.+ calls: std::sync::Mutex<usize>,+}++#[async_trait::async_trait]+impl tinymemory_api::provider::MemorySourceSync for FailingSourceSync {+ async fn sync_statuses(+ &self,+ ) -> Result<Vec<tinymemory_api::provider::SourceSyncStatus>, tinymemory_api::error::MemoryError>+ {+ *self.calls.lock().expect("calls lock") += 1;+ Err(tinymemory_api::error::MemoryError::Backend(+ "the backend is unreachable".into(),+ ))+ }++ async fn source_sync_state(+ &self,+ _toolkit: &str,+ _connection_id: &str,+ ) -> Result<Option<tinymemory_api::provider::SourceSyncState>, tinymemory_api::error::MemoryError>+ {+ Ok(None)+ }++ async fn run_connection_sync(+ &self,+ _toolkit: &str,+ _connection_id: &str,+ ) -> Result<tinymemory_api::provider::SyncRunOutcome, tinymemory_api::error::MemoryError> {+ Ok(tinymemory_api::provider::SyncRunOutcome::default())+ }++ async fn sync_audit_log(+ &self,+ _limit: Option<usize>,+ ) -> Result<Vec<tinymemory_api::provider::SyncAuditEntry>, tinymemory_api::error::MemoryError>+ {+ Ok(Vec::new())+ }++ async fn estimate_sync_cost_usd(+ &self,+ _input_tokens: u64,+ _output_tokens: u64,+ ) -> Result<f64, tinymemory_api::error::MemoryError> {+ Ok(0.0)+ }++ async fn raw_archive_coverage(+ &self,+ _tree_scope: &str,+ _archive_source_id: &str,+ ) -> Result<tinymemory_api::provider::RawArchiveCoverage, tinymemory_api::error::MemoryError>+ {+ Ok(tinymemory_api::provider::RawArchiveCoverage::default())+ }++ async fn rebuild_from_raw_archive(+ &self,+ _tree_scope: &str,+ _archive_source_id: &str,+ ) -> Result<tinymemory_api::provider::RawRebuildOutcome, tinymemory_api::error::MemoryError>+ {+ Ok(tinymemory_api::provider::RawRebuildOutcome::default())+ }+}++#[async_trait::async_trait]+impl tinymemory_api::provider::MemoryCore for FailingSourceSync {+ async fn store(+ &self,+ _namespace: &str,+ _key: &str,+ _content: &str,+ _category: tinymemory_api::types::MemoryCategory,+ _session_id: Option<&str>,+ _taint: tinymemory_api::types::MemoryTaint,+ ) -> Result<(), tinymemory_api::error::MemoryError> {+ Ok(())+ }+ async fn get(+ &self,+ _namespace: &str,+ _key: &str,+ ) -> Result<Option<tinymemory_api::types::MemoryEntry>, tinymemory_api::error::MemoryError>+ {+ Ok(None)+ }+ async fn forget(+ &self,+ _namespace: &str,+ _key: &str,+ ) -> Result<bool, tinymemory_api::error::MemoryError> {+ Ok(false)+ }+ async fn namespaces(+ &self,+ ) -> Result<Vec<tinymemory_api::types::NamespaceSummary>, tinymemory_api::error::MemoryError>+ {+ Ok(Vec::new())+ }+ async fn list(+ &self,+ _namespace: Option<&str>,+ _category: Option<&tinymemory_api::types::MemoryCategory>,+ _session_id: Option<&str>,+ ) -> Result<Vec<tinymemory_api::types::MemoryEntry>, tinymemory_api::error::MemoryError> {+ Ok(Vec::new())+ }+}++#[async_trait::async_trait]+impl tinymemory_api::provider::MemoryRecall for FailingSourceSync {+ async fn recall(+ &self,+ _query: &str,+ _limit: usize,+ _opts: &tinymemory_api::recall::OwnedRecallOpts,+ _scope: Option<&tinymemory_api::provider::SourceScope>,+ ) -> Result<Vec<tinymemory_api::types::MemoryEntry>, tinymemory_api::error::MemoryError> {+ Ok(Vec::new())+ }+}++#[async_trait::async_trait]+impl tinymemory_api::provider::MemoryPortability for FailingSourceSync {+ async fn export_page(+ &self,+ _cursor: Option<&str>,+ _limit: usize,+ ) -> Result<tinymemory_api::provider::ExportPage, tinymemory_api::error::MemoryError> {+ Ok(tinymemory_api::provider::ExportPage::default())+ }+ async fn import_records(+ &self,+ _records: Vec<tinymemory_api::provider::ExportRecord>,+ ) -> Result<tinymemory_api::provider::ImportOutcome, tinymemory_api::error::MemoryError> {+ Ok(tinymemory_api::provider::ImportOutcome::default())+ }+}++#[async_trait::async_trait]+impl MemoryProvider for FailingSourceSync {+ fn driver_id(&self) -> &str {+ "failing-source-sync-test-driver"+ }+ fn capabilities(&self) -> tinymemory_api::capabilities::Capabilities {+ tinymemory_api::capabilities::Capabilities::mandatory()+ }+ async fn health(&self) -> tinymemory_api::health::MemoryHealth {+ tinymemory_api::health::MemoryHealth::Ready+ }+ fn as_source_sync(&self) -> Option<&dyn tinymemory_api::provider::MemorySourceSync> {+ Some(self)+ }+}++/// Path two: the driver is bound and does not serve `SourceSync`.+#[tokio::test]+async fn a_driver_without_the_family_reports_an_empty_table_rather_than_an_error() {+ let (_tmp, cfg) = degradation_config();+ binding::install_for_test(+ &cfg.workspace_dir,+ &cfg.subsystems.memory,+ Arc::new(NullMemoryProvider::new()) as Arc<dyn MemoryProvider>,+ );++ let outcome = status_list_rpc(&cfg)+ .await+ .expect("an unserved family must not surface as an RPC error");+ assert!(+ outcome.value.statuses.is_empty(),+ "the table is empty, not broken"+ );+}++/// Path three: the driver serves the family and the call fails.+///+/// The one a null driver cannot produce, and the one most likely to be+/// "tightened" by someone who has not read the comment — a backend blip is+/// exactly what looks like it deserves an error.+#[tokio::test]+async fn a_driver_error_is_degraded_to_an_empty_table_not_surfaced() {+ let (_tmp, cfg) = degradation_config();+ let driver = Arc::new(FailingSourceSync::default());+ binding::install_for_test(+ &cfg.workspace_dir,+ &cfg.subsystems.memory,+ Arc::clone(&driver) as Arc<dyn MemoryProvider>,+ );++ let outcome = status_list_rpc(&cfg)+ .await+ .expect("a driver-side failure must not surface as an RPC error");+ assert!(outcome.value.statuses.is_empty());+ assert_eq!(+ *driver.calls.lock().expect("calls lock"),+ 1,+ "the handler must have reached the driver — an empty table from an \+ unreached driver would prove nothing about the degradation"+ );+}