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: extend domain module and approval e2e coverage
Steven Enamakela131375cb262
diff --git a/tests/in_process/domain_modules_e2e.rs b/tests/in_process/domain_modules_e2e.rsindex 5a35104299..6d8bb2a9bd 100644--- a/tests/in_process/domain_modules_e2e.rs+++ b/tests/in_process/domain_modules_e2e.rs@@ -433,6 +433,55 @@ async fn config_agent_tools_and_threads_mutation_paths_round_trip() {data(&update_message, "threads_message_update").pointer("/extraMetadata/phase"),Some(&json!("updated")));+ assert_eq!(+ data(&update_message, "threads_message_update")+ .pointer("/extraMetadata/verified"),+ Some(&json!(true)),+ "boolean metadata must remain boolean in the projected message"+ );++ let missing_messages = rpc(+ &harness.rpc_base,+ 34_005,+ "openhuman.threads_messages_list",+ json!({ "thread_id": "missing-domain-e2e-thread" }),+ )+ .await;+ assert_eq!(+ data(&missing_messages, "threads_messages_list missing thread")+ .get("count")+ .and_then(Value::as_u64),+ Some(0),+ "listing messages for a missing thread is an empty read"+ );++ let fresh_turn_state = rpc(+ &harness.rpc_base,+ 34_006,+ "openhuman.threads_turn_state_get",+ json!({ "thread_id": "domain-e2e-thread" }),+ )+ .await;+ let fresh_turn_state = data(&fresh_turn_state, "fresh threads_turn_state_get");+ assert!(+ fresh_turn_state.get("turnState").is_none(),+ "fresh thread must omit turnState rather than serialize null: {fresh_turn_state}"+ );++ let fresh_clear = rpc(+ &harness.rpc_base,+ 34_007,+ "openhuman.threads_turn_state_clear",+ json!({ "thread_id": "domain-e2e-thread" }),+ )+ .await;+ assert_eq!(+ data(&fresh_clear, "fresh threads_turn_state_clear")+ .get("cleared")+ .and_then(Value::as_bool),+ Some(false),+ "clearing absent state reports cleared=false"+ );let delete_thread = rpc(&harness.rpc_base,diff --git a/tests/raw_coverage/composio_backend_tools_e2e.rs b/tests/raw_coverage/composio_backend_tools_e2e.rsnew file mode 100644index 0000000000..a235c621ab--- /dev/null+++ b/tests/raw_coverage/composio_backend_tools_e2e.rs@@ -0,0 +1,411 @@+//! Round20 raw/E2E coverage for Composio tool leftovers and adjacent+//! network-tool branches. All HTTP traffic stays on loopback mocks.++use crate::env_guard::EnvVarGuard;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};++use axum::body::to_bytes;+use axum::extract::{Request, State};+use axum::http::{Method, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::routing::any;+use axum::{Json, Router};+use serde_json::{json, Value};+use tempfile::{Builder, TempDir};++use openhuman_core::config::Config;+use openhuman_core::integrations::composio::ops::{composio_authorize, composio_list_tools};+use openhuman_core::security::credentials::{+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,+};+use openhuman_core::integrations::composio::tools::{+ ComposioListConnectionsTool, ComposioListToolkitsTool, ComposioListToolsTool,+};+use tinytools::{Tool, ToolCallOptions};++static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;++#[derive(Clone, Debug)]+struct RecordedRequest {+ method: Method,+ path: String,+ query: String,+ body: Value,+ api_key: Option<String>,+}++#[derive(Clone, Default)]+struct MockState {+ requests: Arc<Mutex<Vec<RecordedRequest>>>,+ connections_fail: Arc<Mutex<bool>>,+}++struct Harness {+ _tmp: TempDir,+ config: Config,+ _guards: Vec<EnvVarGuard>,+}++fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .blocking_lock()+}++async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .lock().await+}++fn tempdir() -> TempDir {+ std::fs::create_dir_all("target").expect("target dir");+ Builder::new()+ .prefix("tools-composio-network-leftovers-round20-")+ .tempdir_in("target")+ .expect("round20 tempdir")+}++async fn setup_config() -> Harness {+ crate::tinyhumans_boot::boot();+ let tmp = tempdir();+ let root = tmp.path().join("openhuman");+ let workspace = root.join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace dir");++ let guards = vec![+ EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &root),+ EnvVarGuard::set_path("HOME", tmp.path()),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"),+ EnvVarGuard::unset("OPENHUMAN_CORE_PORT"),+ EnvVarGuard::unset("OPENHUMAN_LSP_ENABLED"),+ ];++ let mut config = Config {+ workspace_dir: workspace,+ config_path: root.join("config.toml"),+ ..Config::default()+ };+ config.secrets.encrypt = false;+ config.observability.analytics_enabled = false;+ config.save().await.expect("save config");++ Harness {+ _tmp: tmp,+ config,+ _guards: guards,+ }+}++fn store_session_token(config: &Config) {+ AuthService::from_config(config)+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ "round20-session-token",+ HashMap::new(),+ true,+ )+ .expect("store app session token");+}++#[tokio::test]+async fn round20_backend_agent_tools_cover_markdown_filtering_and_errors() {+ let _lock = env_lock_async().await;+ let state = MockState::default();+ let base = start_loopback(+ Router::new()+ .fallback(any(composio_backend_handler))+ .with_state(state.clone()),+ )+ .await;+ let mut harness = setup_config().await;+ harness.config.api_url = Some(base);+ harness.config.save().await.expect("save backend config");+ store_session_token(&harness.config);++ let config = Arc::new(harness.config.clone());+ let list_toolkits = ComposioListToolkitsTool::new(config.clone());+ let toolkits = list_toolkits+ .execute(json!({}))+ .await+ .expect("list toolkits");+ assert!(!toolkits.is_error);+ assert!(toolkits.output().contains("gmail"));++ let connections_tool = ComposioListConnectionsTool::new(config.clone());+ let connections = connections_tool+ .execute(json!({}))+ .await+ .expect("list connections");+ assert!(!connections.is_error);+ assert!(connections.output().contains("conn-gmail"));+ assert!(!connections.output().contains("conn-pending"));++ let list_tools = ComposioListToolsTool::new(config.clone());+ let markdown = list_tools+ .execute_with_options(+ json!({+ "toolkits": ["gmail", "github"],+ "tags": ["readOnlyHint", "repos"],+ "include_unconnected": true+ }),+ ToolCallOptions {+ prefer_markdown: true,+ },+ )+ .await+ .expect("list tools markdown");+ assert!(!markdown.is_error);+ assert!(markdown.output().contains("GMAIL_FETCH_EMAILS"));+ assert!(markdown+ .markdown_formatted+ .as_deref()+ .unwrap_or_default()+ .contains("# Composio tools"));++ let connected_only = list_tools+ .execute(json!({ "toolkits": ["gmail", "github"] }))+ .await+ .expect("list tools connected only");+ assert!(!connected_only.is_error);+ assert!(connected_only.output().contains("GMAIL_FETCH_EMAILS"));+ assert!(!connected_only.output().contains("GITHUB_STAR_REPOSITORY"));++ let unsupported = list_tools+ .execute(json!({+ "toolkits": ["totallycustom"],+ "include_unconnected": true+ }))+ .await+ .expect("unsupported toolkit empty list");+ assert!(unsupported.is_error);+ assert!(unsupported.output().contains("no agent-ready actions"));++ *state.connections_fail.lock().expect("connections flag") = true;+ let connection_error = list_tools+ .execute(json!({ "toolkits": ["gmail"] }))+ .await+ .expect("connection prefilter error");+ assert!(connection_error.is_error);+ assert!(connection_error+ .output()+ .contains("failed to fetch connections"));++ let requests = state.requests.lock().expect("requests").clone();+ assert!(requests.iter().any(|request| {+ request.method == Method::GET+ && request.path == "/agent-integrations/composio/tools"+ && request.query.contains("toolkits=gmail")+ && request.query.contains("github")+ && request.query.contains("tags=readOnlyHint")+ && request.query.contains("repos")+ }));+ assert!(requests.iter().any(|request| {+ request.method == Method::GET+ && request.path == "/agent-integrations/composio/tools"+ && request.query.contains("toolkits=gmail")+ && request.query.contains("github")+ && !request.query.contains("tags=")+ }));+}++#[tokio::test]+async fn round20_composio_ops_cover_authorize_scopes() {+ let _lock = env_lock_async().await;+ let state = MockState::default();+ let base = start_loopback(+ Router::new()+ .fallback(any(composio_backend_handler))+ .with_state(state.clone()),+ )+ .await;+ let mut harness = setup_config().await;+ harness.config.api_url = Some(base);+ harness.config.save().await.expect("save backend config");+ store_session_token(&harness.config);++ let legacy_extra = composio_authorize(+ &openhuman_core::core::runtime::DispatchCtx::host_default(),+ &harness.config,+ "gmail",+ Some(json!({ "oauth_scopes": [123] })),+ )+ .await+ .expect("module ignores non-string legacy OAuth scope entries")+ .value;+ assert_eq!(legacy_extra.connection_id, "conn-authorize");++ let authorized = composio_authorize(+ &openhuman_core::core::runtime::DispatchCtx::host_default(),+ &harness.config,+ " gmail ",+ Some(json!({ "waba_id": "waba-round20" })),+ )+ .await+ .expect("authorize with required gmail scope")+ .value;+ assert_eq!(authorized.connection_id, "conn-authorize");++ let listed = composio_list_tools(+ &openhuman_core::core::runtime::DispatchCtx::host_default(),+ &harness.config,+ Some(vec!["gmail".into(), "github".into()]),+ Some(vec!["readOnlyHint".into()]),+ )+ .await+ .expect("ops list tools")+ .value;+ // The connector module lists only curated actions (b80c12358a): its+ // GitHub catalog has no GITHUB_STAR_REPOSITORY, so the mock's second+ // tool is gated out.+ let names: Vec<&str> = listed+ .tools+ .iter()+ .map(|tool| tool.function.name.as_str())+ .collect();+ assert_eq!(names, ["GMAIL_FETCH_EMAILS"]);++ let requests = state.requests.lock().expect("requests").clone();+ let authorize_body = requests+ .iter()+ .rfind(|request| request.path == "/agent-integrations/composio/authorize")+ .expect("authorize request with the requested WABA id")+ .body+ .clone();+ assert_eq!(authorize_body["toolkit"], "gmail");+ assert_eq!(authorize_body["waba_id"], "waba-round20");+ assert!(authorize_body["oauth_scopes"]+ .as_array()+ .expect("oauth scopes array")+ .iter()+ .any(|scope| scope+ .as_str()+ .unwrap_or_default()+ .contains("gmail.readonly")));+}++async fn start_loopback(app: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind loopback");+ let addr = listener.local_addr().expect("loopback addr");+ tokio::spawn(async move {+ axum::serve(listener, app).await.expect("serve loopback");+ });+ format!("http://127.0.0.1:{}", addr.port())+}++async fn composio_backend_handler(State(state): State<MockState>, request: Request) -> Response {+ let method = request.method().clone();+ let uri = request.uri().clone();+ let path = uri.path().to_string();+ let query = uri.query().unwrap_or_default().to_string();+ let bytes = to_bytes(request.into_body(), usize::MAX)+ .await+ .expect("request body");+ let body: Value = if bytes.is_empty() {+ json!({})+ } else {+ serde_json::from_slice(&bytes).expect("json body")+ };+ state+ .requests+ .lock()+ .expect("requests")+ .push(RecordedRequest {+ method: method.clone(),+ path: path.clone(),+ query: query.clone(),+ body: body.clone(),+ api_key: None,+ });++ match (method, path.as_str()) {+ (Method::GET, "/agent-integrations/composio/toolkits") => ok(json!({+ "toolkits": ["gmail", "github", "totallycustom"]+ })),+ (Method::GET, "/agent-integrations/composio/connections") => {+ if *state.connections_fail.lock().expect("connections flag") {+ return fail(StatusCode::BAD_GATEWAY, "connections unavailable");+ }+ ok(json!({+ "connections": [+ {+ "id": "conn-gmail",+ "toolkit": "gmail",+ "status": "ACTIVE",+ "createdAt": "2026-05-30T00:00:00Z"+ },+ {+ "id": "conn-pending",+ "toolkit": "github",+ "status": "PENDING",+ "createdAt": "2026-05-30T00:00:01Z"+ }+ ]+ }))+ }+ (Method::POST, "/agent-integrations/composio/authorize") => ok(json!({+ "connectUrl": "https://connect.example/round20",+ "connectionId": "conn-authorize"+ })),+ (Method::GET, "/agent-integrations/composio/tools") => {+ if query.contains("totallycustom") {+ ok(json!({ "tools": [] }))+ } else {+ ok(json!({+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "GMAIL_FETCH_EMAILS",+ "description": "Fetch Gmail messages\nwith whitespace",+ "parameters": {+ "type": "object",+ "required": ["query"],+ "properties": {+ "query": { "type": "string" },+ "max_results": { "type": "integer" }+ }+ }+ }+ },+ {+ "type": "function",+ "function": {+ "name": "GITHUB_STAR_REPOSITORY",+ "description": "Star a repository",+ "parameters": {+ "type": "object",+ "required": ["owner", "repo"],+ "properties": {+ "owner": { "type": "string" },+ "repo": { "type": "string" }+ }+ }+ }+ }+ ]+ }))+ }+ }+ _ => fail(StatusCode::NOT_FOUND, &format!("unhandled backend {path}")),+ }+}++fn ok(data: Value) -> Response {+ Json(json!({ "success": true, "data": data })).into_response()+}++fn fail(status: StatusCode, error: &str) -> Response {+ (+ status,+ Json(json!({ "success": false, "error": error.to_string() })),+ )+ .into_response()+}diff --git a/tests/raw_coverage/composio_direct_client_e2e.rs b/tests/raw_coverage/composio_direct_client_e2e.rsnew file mode 100644index 0000000000..375a3f9dd3--- /dev/null+++ b/tests/raw_coverage/composio_direct_client_e2e.rs@@ -0,0 +1,251 @@+//! Raw integration coverage for direct Composio tools.+//!+//! This binary stays on loopback mocks and temp stores. It exercises the+//! direct BYO-key tool surface without contacting Composio.++use std::sync::{Arc, Mutex};++use axum::body::to_bytes;+use axum::extract::{Request, State};+use axum::http::{Method, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::routing::any;+use axum::{Json, Router};+use serde_json::{json, Value};++use openhuman_core::config::Config;+use openhuman_core::integrations::composio::client::{direct_list_connections, DirectCredential};++#[derive(Clone, Default)]+struct MockState {+ requests: Arc<Mutex<Vec<RecordedRequest>>>,+}++#[derive(Clone, Debug)]+struct RecordedRequest {+ method: String,+ path: String,+ query: String,+ body: Value,+ api_key: Option<String>,+}++#[tokio::test]+async fn direct_composio_client_uses_loopback_for_connected_accounts() {+ // The read runs in the connector module, which is process-global.+ let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;+ let dir = tempfile::tempdir().expect("tempdir");+ let config = Config {+ workspace_dir: dir.path().to_path_buf(),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };+ let state = MockState::default();+ let app = Router::new()+ .fallback(any(composio_direct_handler))+ .with_state(state.clone());+ let base = start_loopback(app).await;+ let tool = Arc::new(+ DirectCredential::new_with_base_urls_for_loopback(+ " ck_round16 ",+ format!("{base}/api/v2"),+ format!("{base}/api/v3"),+ )+ .expect("loopback direct client"),+ );++ let mapped = direct_list_connections(&config, &tool)+ .await+ .expect("mapped connected accounts");+ assert_eq!(mapped.connections.len(), 4);+ assert!(mapped+ .connections+ .iter()+ .any(|conn| conn.id == "acct-github" && conn.toolkit == "github"));+ // Slug extraction: padded string, nested object, `appName` fallback, and a+ // row with no recognizable slug is kept with an empty toolkit.+ let toolkits: Vec<&str> = mapped+ .connections+ .iter()+ .map(|c| c.toolkit.as_str())+ .collect();+ assert_eq!(toolkits[..2], ["gmail", "github"]);+ assert_eq!(toolkits[2], "slack");+ assert_eq!(toolkits[3], "");++ let requests = state.requests.lock().expect("requests").clone();+ assert!(requests.iter().all(|request| {+ request.api_key.as_deref() == Some("ck_round16") || request.path == "/health"+ }));+ assert!(requests.iter().any(|request| {+ request.method == "GET"+ && request.path == "/api/v3/connected_accounts"+ && request.query.contains("limit=200")+ }));+}++async fn composio_direct_handler(State(state): State<MockState>, request: Request) -> Response {+ let method = request.method().clone();+ let uri = request.uri().clone();+ let path = uri.path().to_string();+ let query = uri.query().unwrap_or_default().to_string();+ let api_key = request+ .headers()+ .get("x-api-key")+ .and_then(|value| value.to_str().ok())+ .map(ToString::to_string);+ let body_bytes = to_bytes(request.into_body(), usize::MAX)+ .await+ .expect("mock request body");+ let body: Value = if body_bytes.is_empty() {+ json!({})+ } else {+ serde_json::from_slice(&body_bytes).expect("json body")+ };+ state+ .requests+ .lock()+ .expect("requests")+ .push(RecordedRequest {+ method: method.as_str().to_string(),+ path: path.clone(),+ query,+ body: body.clone(),+ api_key,+ });++ match (method, path.as_str()) {+ (Method::GET, "/api/v3/tools") => Json(json!({+ "items": [+ {+ "slug": "gmail-fetch-emails",+ "name": "Gmail fetch fallback",+ "description": "Fetch Gmail",+ "toolkit": { "slug": "gmail" },+ "input_parameters": {+ "type": "object",+ "properties": { "query": { "type": "string" } }+ }+ },+ {+ "name": "gmail-send-email",+ "description": "Send Gmail",+ "appName": "gmail",+ "parameters": { "type": "object" }+ },+ {+ "description": "dropped because it has no slug or name",+ "toolkit": { "slug": "gmail" }+ }+ ]+ }))+ .into_response(),+ (Method::POST, "/api/v3/tools/execute/GMAIL_FETCH_EMAILS") => Json(json!({+ "successful": true,+ "data": {+ "messages": [{ "id": "msg-direct", "subject": "hello" }]+ }+ }))+ .into_response(),+ (Method::POST, "/api/v3/tools/execute/FALLBACK_ACTION") => (+ StatusCode::BAD_GATEWAY,+ Json(json!({+ "error": { "message": "temporary v3 outage" }+ })),+ )+ .into_response(),+ (Method::POST, "/api/v2/actions/FALLBACK_ACTION/execute") => Json(json!({+ "legacy": true,+ "input": body.get("input").cloned().unwrap_or_else(|| json!({}))+ }))+ .into_response(),+ (Method::POST, "/api/v3/tools/execute/BROKEN_ACTION") => (+ StatusCode::BAD_REQUEST,+ Json(json!({+ "error": {+ "message": "bad connected_account_id acct-secret for entity_id entity-secret"+ }+ })),+ )+ .into_response(),+ (Method::POST, "/api/v2/actions/BROKEN_ACTION/execute") => (+ StatusCode::BAD_REQUEST,+ Json(json!({+ "message": "legacy connectedAccountId acct-secret and entityId entity-secret failed"+ })),+ )+ .into_response(),+ (Method::GET, "/api/v3/auth_configs") => Json(json!({+ "items": [+ { "id": "auth-disabled", "enabled": false, "status": "disabled" },+ { "id": "auth-enabled", "status": "ENABLED" }+ ]+ }))+ .into_response(),+ (Method::POST, "/api/v3/connected_accounts/link") => {+ let auth_config = body+ .get("auth_config_id")+ .and_then(Value::as_str)+ .unwrap_or_default();+ if auth_config == "auth-explicit" {+ Json(json!({ "redirectUrl": "https://connect.example/from-redirect-url" }))+ .into_response()+ } else {+ Json(json!({+ "data": {+ "redirect_url": "https://connect.example/from-data"+ }+ }))+ .into_response()+ }+ }+ (Method::GET, "/api/v3/connected_accounts") => Json(json!({+ "items": [+ {+ "id": "acct-gmail",+ "status": "ACTIVE",+ "created_at": "2026-05-29T12:00:00Z",+ "toolkit": " gmail "+ },+ {+ "id": "acct-github",+ "status": "INITIATED",+ "createdAt": "2026-05-29T12:01:00Z",+ "toolkit": { "slug": "github" }+ },+ {+ "id": "acct-slack",+ "status": "FAILED",+ "app_name": "slack"+ },+ {+ "id": "acct-empty-toolkit",+ "status": "ACTIVE",+ "toolkit": null+ },+ {+ "id": " ",+ "status": "ACTIVE",+ "toolkit": "not-returned"+ }+ ]+ }))+ .into_response(),+ _ => (+ StatusCode::NOT_FOUND,+ Json(json!({ "error": { "message": format!("unhandled {path}") } })),+ )+ .into_response(),+ }+}++async fn start_loopback(app: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind mock composio direct server");+ let addr = listener.local_addr().expect("mock addr");+ tokio::spawn(async move {+ let _ = axum::serve(listener, app).await;+ });+ format!("http://127.0.0.1:{}", addr.port())+}diff --git a/tests/raw_coverage/composio_direct_tools_e2e.rs b/tests/raw_coverage/composio_direct_tools_e2e.rsnew file mode 100644index 0000000000..45462dfe54--- /dev/null+++ b/tests/raw_coverage/composio_direct_tools_e2e.rs@@ -0,0 +1,404 @@+//! Round25 focused raw coverage for large Composio direct-mode misses.+//!+//! The direct-mode factory normally pins Composio's production HTTPS API.+//! This test uses debug-only loopback base overrides and temp config stores so+//! no real network, keychain, or backend session is required.++use crate::env_guard::EnvVarGuard;+use std::sync::{Arc, Mutex, OnceLock};++use axum::body::to_bytes;+use axum::extract::{Request, State};+use axum::http::{Method, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::routing::any;+use axum::{Json, Router};+use serde_json::{json, Value};+use tempfile::{Builder, TempDir};++use openhuman_core::config::Config;+use openhuman_core::integrations::composio::ops::{+ cached_active_integrations, composio_authorize, composio_execute, composio_list_connections,+ composio_list_toolkits, composio_list_tools, fetch_connected_integrations_status,+};+use openhuman_core::integrations::composio::tools::ComposioListToolsTool;+use openhuman_core::integrations::composio::{+ invalidate_connected_integrations_cache, FetchConnectedIntegrationsStatus,+};+use tinytools::{Tool, ToolCallOptions};++static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;++#[derive(Clone, Debug)]+struct RecordedRequest {+ method: Method,+ path: String,+ query: String,+ body: Value,+ api_key: Option<String>,+}++#[derive(Clone, Default)]+struct MockState {+ requests: Arc<Mutex<Vec<RecordedRequest>>>,+}++struct Harness {+ _tmp: TempDir,+ config: Config,+ _guards: Vec<EnvVarGuard>,+}++fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .blocking_lock()+}++async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .lock()+ .await+}++async fn setup_direct_config(base: &str) -> Harness {+ crate::tinyhumans_boot::boot();+ std::fs::create_dir_all("target").expect("target dir");+ let tmp = Builder::new()+ .prefix("tools-composio-large-round25-")+ .tempdir_in("target")+ .expect("round25 tempdir");+ let root = tmp.path().join("openhuman");+ let workspace = root.join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace dir");++ let guards = vec![+ EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &root),+ EnvVarGuard::set_path("HOME", tmp.path()),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set(+ "OPENHUMAN_COMPOSIO_DIRECT_BASE_V2",+ format!("{base}/api/v2"),+ ),+ EnvVarGuard::set(+ "OPENHUMAN_COMPOSIO_DIRECT_BASE_V3",+ format!("{base}/api/v3"),+ ),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"),+ EnvVarGuard::unset("OPENHUMAN_CORE_PORT"),+ ];++ let mut config = Config {+ workspace_dir: workspace,+ config_path: root.join("config.toml"),+ ..Config::default()+ };+ config.composio.mode = "direct".to_string();+ config.composio.api_key = Some(" ck_round25_direct ".to_string());+ config.composio.entity_id = " entity-round25 ".to_string();+ config.secrets.encrypt = false;+ config.observability.analytics_enabled = false;+ config.save().await.expect("save config");++ Harness {+ _tmp: tmp,+ config,+ _guards: guards,+ }+}++#[tokio::test]+async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_execute() {+ let _lock = env_lock_async().await;+ invalidate_connected_integrations_cache();++ let state = MockState::default();+ let base = start_loopback(+ Router::new()+ .fallback(any(composio_direct_handler))+ .with_state(state.clone()),+ )+ .await;+ let harness = setup_direct_config(&base).await;++ let toolkits = composio_list_toolkits(&harness.config)+ .await+ .expect("direct list toolkits")+ .value;+ assert!(toolkits.toolkits.is_empty());++ let connections = composio_list_connections(+ &openhuman_core::core::runtime::DispatchCtx::ambient(),+ &harness.config,+ )+ .await+ .expect("direct list connections")+ .value;+ assert_eq!(connections.connections.len(), 3);+ assert!(connections+ .connections+ .iter()+ .any(|conn| conn.id == "acct-gmail" && conn.normalized_toolkit() == "gmail"));++ let listed = composio_list_tools(+ &openhuman_core::core::runtime::DispatchCtx::ambient(),+ &harness.config,+ None,+ Some(vec![" readOnlyHint ".into(), " ".into()]),+ )+ .await+ .expect("direct list tools")+ .value;+ assert!(listed+ .tools+ .iter()+ .any(|tool| tool.function.name == "GMAIL_FETCH_EMAILS"));++ let markdown = ComposioListToolsTool::new(Arc::new(harness.config.clone()))+ .execute_with_options(+ json!({ "toolkits": ["gmail"], "tags": ["readOnlyHint"], "include_unconnected": true }),+ ToolCallOptions {+ prefer_markdown: true,+ },+ )+ .await+ .expect("direct list tools tool markdown");+ assert!(!markdown.is_error, "{}", markdown.output());+ assert_eq!(markdown.output(), "{\"tools\":[]}");++ let authorize = composio_authorize(+ &openhuman_core::core::runtime::DispatchCtx::host_default(),+ &harness.config,+ " gmail ",+ Some(json!({ "ignored_in_direct": true })),+ )+ .await+ .expect("direct authorize")+ .value;+ assert_eq!(authorize.connection_id, "");+ assert_eq!(+ authorize.connect_url,+ "https://connect.example.test/round25"+ );++ let executed = composio_execute(+ &harness.config,+ "GMAIL_FETCH_EMAILS",+ Some(json!({ "query": "label:INBOX" })),+ None,+ )+ .await+ .expect("direct execute")+ .value;+ assert!(executed.successful, "{executed:?}");+ assert_eq!(+ executed.data.pointer("/messages/0/id"),+ Some(&json!("msg-round25"))+ );+ assert_eq!(executed.cost_usd, 0.0);++ let failed_execute = composio_execute(+ &harness.config,+ "GMAIL_SEND_EMAIL",+ Some(json!({ "to": "[email protected]" })),+ None,+ )+ .await+ .expect("direct execute provider failure")+ .value;+ assert!(!failed_execute.successful);+ assert!(failed_execute+ .error+ .as_deref()+ .unwrap_or_default()+ .contains("provider rejected send"));++ match fetch_connected_integrations_status(&harness.config).await {+ FetchConnectedIntegrationsStatus::Authoritative(integrations) => {+ assert!(integrations+ .iter()+ .any(|item| item.toolkit == "gmail" && item.connected));+ assert!(integrations+ .iter()+ .any(|item| item.toolkit == "slack" && item.connected));+ assert!(!integrations+ .iter()+ .any(|item| item.toolkit == "github" && item.connected));+ }+ FetchConnectedIntegrationsStatus::Unavailable => {+ panic!("direct loopback integrations should be authoritative")+ }+ }+ assert!(cached_active_integrations(&harness.config).is_some());++ let requests = state.requests.lock().expect("requests").clone();+ assert!(requests.iter().all(|request| {+ request.api_key.as_deref() == Some("ck_round25_direct") || request.path == "/health"+ }));+ assert!(requests.iter().any(|request| {+ request.method == Method::GET+ && request.path.ends_with("/connected_accounts")+ && request.query.contains("limit=200")+ }));+ assert!(requests.iter().any(|request| {+ request.method == Method::GET+ && request.path.ends_with("/tools")+ && request.query.contains("tags=readOnlyHint")+ }));+ assert!(requests.iter().any(|request| {+ request.method == Method::POST+ && request.path.ends_with("/connected_accounts/link")+ && request.body["toolkit"] == "gmail"+ && request.body["entity_id"] == " entity-round25 "+ }));+ assert!(requests.iter().any(|request| {+ request.method == Method::POST+ && request.path.ends_with("/tools/execute/GMAIL_FETCH_EMAILS")+ && request.body["arguments"]["query"] == "label:INBOX"+ && request.body["entity_id"] == " entity-round25 "+ }));+}++async fn start_loopback(app: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind loopback");+ let addr = listener.local_addr().expect("local addr");+ tokio::spawn(async move {+ axum::serve(listener, app).await.expect("loopback server");+ });+ format!("http://127.0.0.1:{}", addr.port())+}++async fn composio_direct_handler(State(state): State<MockState>, request: Request) -> Response {+ let (parts, body) = request.into_parts();+ let method = parts.method;+ let path = parts.uri.path().to_string();+ let query = parts.uri.query().unwrap_or_default().to_string();+ let api_key = parts+ .headers+ .get("x-api-key")+ .and_then(|value| value.to_str().ok())+ .map(ToString::to_string);+ let body_bytes = to_bytes(body, 1024 * 1024).await.expect("body bytes");+ let body_json = if body_bytes.is_empty() {+ Value::Null+ } else {+ serde_json::from_slice(&body_bytes).unwrap_or(Value::Null)+ };++ state+ .requests+ .lock()+ .expect("requests")+ .push(RecordedRequest {+ method: method.clone(),+ path: path.clone(),+ query: query.clone(),+ body: body_json,+ api_key,+ });++ // TinyConnectors v0.3 serves direct-mode routes from the configured base+ // without the host's historical `/api/v3` prefix. Keep this fixture+ // tolerant of both shapes while retaining the recorded raw request above.+ let route = path+ .strip_prefix("/api/v3")+ .map_or_else(|| path.clone(), ToString::to_string);++ match (method, format!("/api/v3{route}").as_str()) {+ (Method::GET, "/api/v3/connected_accounts") => Json(json!({+ "items": [+ {+ "id": "acct-gmail",+ "status": "ACTIVE",+ "toolkit": { "slug": "gmail" },+ "created_at": "2026-05-30T00:00:00Z"+ },+ {+ "id": "acct-github",+ "status": "INITIATED",+ "toolkit": "github",+ "createdAt": "2026-05-30T00:00:01Z"+ },+ {+ "id": "acct-slack",+ "status": "CONNECTED",+ "appName": "slack",+ "created_at": "2026-05-30T00:00:02Z"+ },+ {+ "id": " ",+ "status": "ACTIVE",+ "toolkit": "dropme"+ }+ ]+ }))+ .into_response(),+ (Method::GET, "/api/v3/tools") => Json(json!({+ "items": [+ {+ "slug": "GMAIL_FETCH_EMAILS",+ "description": "Fetch Gmail messages",+ "toolkit": { "slug": "gmail" },+ "input_parameters": {+ "type": "object",+ "properties": {+ "query": { "type": "string" }+ }+ }+ },+ {+ "slug": "",+ "description": "Malformed row should be dropped",+ "toolkit": { "slug": "gmail" }+ },+ {+ "name": "SLACK_FETCH_MESSAGES",+ "description": "Fetch Slack messages",+ "appName": "slack",+ "parameters": {+ "type": "object",+ "properties": {+ "channel": { "type": "string" }+ }+ }+ }+ ]+ }))+ .into_response(),+ (Method::GET, "/api/v3/auth_configs") => Json(json!({+ "items": [+ { "id": "auth-disabled", "status": "disabled", "enabled": false },+ { "id": "auth-round25", "status": "enabled", "enabled": true }+ ]+ }))+ .into_response(),+ (Method::POST, "/api/v3/connected_accounts/link") => Json(json!({+ "redirectUrl": "https://connect.example.test/round25"+ }))+ .into_response(),+ (Method::POST, "/api/v3/tools/execute/GMAIL_FETCH_EMAILS") => Json(json!({+ "successful": true,+ "data": {+ "messages": [+ { "id": "msg-round25", "subject": "Coverage" }+ ]+ }+ }))+ .into_response(),+ (Method::POST, "/api/v3/tools/execute/GMAIL_SEND_EMAIL") => Json(json!({+ "successful": false,+ "error": "provider rejected send",+ "data": {+ "status": "blocked"+ }+ }))+ .into_response(),+ _ => (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" }))).into_response(),+ }+}diff --git a/tests/raw_coverage/composio_host_helpers_e2e.rs b/tests/raw_coverage/composio_host_helpers_e2e.rsnew file mode 100644index 0000000000..5fe7f326f2--- /dev/null+++ b/tests/raw_coverage/composio_host_helpers_e2e.rs@@ -0,0 +1,475 @@+//! Raw-line oriented coverage for deterministic Composio helpers.+//!+//! These tests avoid live Composio/backend calls and exercise public helper+//! surfaces that feed the JSON-RPC and agent-tool paths.++use openhuman_core::core::runtime::DispatchCtx;+use std::sync::{Arc, OnceLock};++use serde_json::{json, Value};+use tempfile::tempdir;++use openhuman_core::agent::prompts::ConnectedIntegration;+use openhuman_core::config::Config;+use openhuman_core::core::all::RegisteredController;+use openhuman_core::integrations::composio::client::{resolve_composio_route, ComposioRoute};+use openhuman_core::integrations::composio::{+ all_composio_controller_schemas, all_composio_registered_controllers,+ cached_active_integrations, connected_set_hash, connection_identity,+ fetch_connected_integrations, fetch_connected_integrations_status,+ invalidate_connected_integrations_cache, ComposioActionTool, FetchConnectedIntegrationsStatus,+};++use tinytools::Tool;++static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;++#[tokio::test]+async fn composio_connected_integrations_public_helpers_handle_empty_auth_and_identity_edges() {+ crate::tinyhumans_boot::boot();+ let dir = tempdir().expect("tempdir");+ let config = Config {+ workspace_dir: dir.path().to_path_buf(),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };++ invalidate_connected_integrations_cache();+ assert!(cached_active_integrations(&config).is_none());++ let first = ConnectedIntegration {+ toolkit: "gmail".into(),+ description: "Gmail".into(),+ tools: Vec::new(),+ gated_tools: Vec::new(),+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ };+ let second = ConnectedIntegration {+ toolkit: "slack".into(),+ description: "Slack".into(),+ tools: Vec::new(),+ gated_tools: Vec::new(),+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ };+ let disconnected = ConnectedIntegration {+ toolkit: "notion".into(),+ description: "Notion".into(),+ tools: Vec::new(),+ gated_tools: Vec::new(),+ connected: false,+ connections: Vec::new(),+ non_active_status: Some("EXPIRED".into()),+ };+ assert_eq!(+ connected_set_hash(&[first.clone(), second.clone(), disconnected.clone()]),+ connected_set_hash(&[disconnected, second, first])+ );+ assert_ne!(+ connected_set_hash(&[]),+ connected_set_hash(&[ConnectedIntegration {+ toolkit: "gmail".into(),+ description: String::new(),+ tools: Vec::new(),+ gated_tools: Vec::new(),+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ }])+ );++ let status = fetch_connected_integrations_status(&config).await;+ assert!(matches!(+ status,+ FetchConnectedIntegrationsStatus::Unavailable+ ));+ assert!(fetch_connected_integrations(&config).await.is_empty());+ assert!(cached_active_integrations(&config).is_none());++ assert_eq!(connection_identity(&config, " ").await, None);+ assert_eq!(connection_identity(&config, "unknown-toolkit").await, None);+}++#[tokio::test]+async fn composio_ops_mode_is_local_and_trigger_history_reads_the_module_archive() {+ let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;+ // The connector module keeps the trigger archive in host storage.+ let env_lock = ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .lock()+ .await;+ let _storage = crate::HostStorage::install(&env_lock);+ crate::tinyhumans_boot::boot();+ let dir = tempdir().expect("tempdir");+ let mut config = Config {+ workspace_dir: dir.path().to_path_buf(),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };+ config.composio.mode = "direct".into();+ openhuman_core::integrations::composio::init_composio_trigger_history(+ config.workspace_dir.clone(),+ )+ .expect("initialize the runtime-owned trigger archive lease");++ let mode = openhuman_core::integrations::composio::ops::composio_get_mode(&config)+ .await+ .expect("get mode should not call backend")+ .into_cli_compatible_json()+ .expect("mode outcome serializes");+ assert_eq!(mode.pointer("/result/mode"), Some(&json!("direct")));+ assert!(mode.pointer("/result/api_key_set").is_some());++ let history = openhuman_core::integrations::composio::ops::composio_list_trigger_history(+ &openhuman_core::core::runtime::DispatchCtx::host_default(),+ &config,+ Some(0),+ )+ .await+ .expect("the runtime-owned archive lease is available");+ let history = history+ .into_cli_compatible_json()+ .expect("history outcome serializes");+ assert!(history+ .pointer("/result/archive_dir")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .contains("triggers"));+}++#[tokio::test]+async fn composio_action_tool_execute_reports_missing_route_without_network() {+ let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;+ crate::tinyhumans_boot::boot();+ let tmp = tempfile::tempdir().expect("temp config directory");+ let config = Config {+ config_path: tmp.path().join("config.toml"),+ ..Default::default()+ };+ let tool = ComposioActionTool::new(+ Arc::new(config),+ "GMAIL_SEND_EMAIL".into(),+ "Send an email".into(),+ None,+ );++ let result = tool+ .execute(json!({ "to": "[email protected]", "subject": "no route" }))+ .await+ .expect("local validation returns a tool result");+ assert!(result.is_error);+ let rendered = serde_json::to_string(&result).unwrap();+ assert!(rendered.contains("without a connector route"), "{rendered}");+ assert!(rendered.contains("proxy"), "{rendered}");+}++#[test]+fn composio_client_factory_modes_are_deterministic_without_network() {+ crate::tinyhumans_boot::boot();+ let dir = tempdir().expect("tempdir");+ let mut config = Config {+ workspace_dir: dir.path().to_path_buf(),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };++ config.composio.mode = String::new();+ let backend_err = match resolve_composio_route(&config) {+ Ok(_) => panic!("backend without a session should fail"),+ Err(error) => error,+ };+ assert!(backend_err.to_string().contains("no backend session token"));++ config.composio.mode = "direct".into();+ let direct_err = match resolve_composio_route(&config) {+ Ok(_) => panic!("direct mode without an api key should fail"),+ Err(error) => error,+ };+ assert!(direct_err.to_string().contains("no api key is configured"));++ config.composio.api_key = Some(" cmp_test_key ".into());+ let direct = resolve_composio_route(&config).expect("inline direct key builds a client");+ assert_eq!(direct.mode(), "direct");+ assert!(matches!(direct, ComposioRoute::Direct(_)));++ config.composio.mode = "typo".into();+ let unknown = match resolve_composio_route(&config) {+ Ok(_) => panic!("unknown composio mode should fail"),+ Err(error) => error,+ };+ assert!(unknown.to_string().contains("unknown composio mode"));+}++#[tokio::test]+async fn composio_controller_registry_and_scope_handlers_cover_validation_edges() {+ let env_lock = ENV_LOCK+ .get_or_init(|| tokio::sync::Mutex::new(()))+ .lock()+ .await;+ // Scope preferences live in the connector module's host storage.+ let _storage = crate::HostStorage::install(&env_lock);+ crate::tinyhumans_boot::boot();+ // The controller loads config through the process workspace resolver. Pin+ // the test to an isolated workspace so the scope store does not depend on+ // a developer's local config.+ let workspace = tempdir().expect("isolated workspace");+ let workspace_dir = workspace.path().join("workspace");+ std::fs::create_dir_all(&workspace_dir).expect("create isolated workspace");+ let _workspace = WorkspaceEnvGuard::set(&workspace_dir);+ let schemas = all_composio_controller_schemas();+ let registered = all_composio_registered_controllers();+ assert_eq!(schemas.len(), registered.len());+ assert!(schemas.iter().any(|schema| schema.function == "execute"));+ assert!(schemas+ .iter()+ .any(|schema| schema.function == "set_api_key"));+ assert!(registered.iter().all(|controller| {+ controller+ .rpc_method_name()+ .starts_with("openhuman.composio_")+ }));++ let unknown = openhuman_core::integrations::composio::schemas::schemas("not_real");+ assert_eq!(unknown.function, "unknown");+ assert_eq!(unknown.inputs[0].name, "function");++ let get_scopes = composio_controller(®istered, "get_user_scopes");+ let scopes = composio_call(get_scopes, json!({ "toolkit": " Gmail " }))+ .await+ .expect("default user scopes");+ assert_eq!(scopes.pointer("/read"), Some(&json!(true)));+ assert_eq!(scopes.pointer("/write"), Some(&json!(true)));+ assert_eq!(scopes.pointer("/admin"), Some(&json!(false)));++ let missing_toolkit = composio_call(get_scopes, json!({}))+ .await+ .expect_err("toolkit is required");+ assert!(missing_toolkit.contains("missing required param 'toolkit'"));++ let set_scopes = composio_controller(®istered, "set_user_scopes");+ let invalid_write = composio_call(+ set_scopes,+ json!({ "toolkit": "gmail", "read": true, "write": "yes", "admin": false }),+ )+ .await+ .expect_err("write must be bool");+ assert!(invalid_write.contains("invalid 'write'"));+ // The pref persists in the connector module's host storage (b80c12358a)+ // and reads back through `get_user_scopes`.+ let saved = composio_call(+ set_scopes,+ json!({ "toolkit": " GitHub ", "read": true, "write": false, "admin": true }),+ )+ .await+ .expect("set_user_scopes persists to host storage");+ assert_eq!(saved.pointer("/admin"), Some(&json!(true)));+ assert_eq!(saved.pointer("/write"), Some(&json!(false)));+ let reread = composio_call(get_scopes, json!({ "toolkit": "github" }))+ .await+ .expect("get_user_scopes reads the stored pref");+ assert_eq!(reread.pointer("/admin"), Some(&json!(true)));+ assert_eq!(reread.pointer("/write"), Some(&json!(false)));+ assert!(+ !workspace_dir+ .join("integrations")+ .join("composio_user_scopes.json")+ .exists(),+ "the legacy workspace file is no longer written"+ );+}++struct WorkspaceEnvGuard(Option<std::ffi::OsString>);++impl WorkspaceEnvGuard {+ fn set(path: &std::path::Path) -> Self {+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", path) };+ Self(previous)+ }+}++impl Drop for WorkspaceEnvGuard {+ fn drop(&mut self) {+ match self.0.take() {+ Some(previous) => unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", previous) },+ None => unsafe { std::env::remove_var("OPENHUMAN_WORKSPACE") },+ }+ }+}++#[test]+fn composio_controller_schema_catalog_covers_all_declared_functions() {+ crate::tinyhumans_boot::boot();+ // (function, required input names, first output name). Assert the required+ // inputs are *present* rather than pinning `inputs.len() == N` — the exact+ // count broke whenever an additive optional param was declared (plan.md §3).+ let expected: [(&str, &[&str], &str); 22] = [+ ("list_toolkits", &[], "toolkits"),+ ("list_capabilities", &[], "capabilities"),+ ("list_agent_ready_toolkits", &[], "toolkits"),+ ("list_connections", &[], "connections"),+ ("authorize", &["toolkit"], "connectUrl"),+ ("delete_connection", &["connection_id"], "deleted"),+ ("list_tools", &["toolkits"], "tools"),+ ("execute", &["tool", "connection_id"], "result"),+ ("list_github_repos", &["connection_id"], "result"),+ ("create_trigger", &["slug", "connection_id"], "result"),+ ("get_user_profile", &["connection_id"], "profile"),+ ("refresh_all_identities", &[], "report"),+ ("list_trigger_history", &["limit"], "result"),+ ("get_user_scopes", &["toolkit"], "pref"),+ ("set_user_scopes", &["toolkit", "read", "write"], "pref"),+ ("list_available_triggers", &["toolkit"], "triggers"),+ ("list_triggers", &["toolkit"], "triggers"),+ ("enable_trigger", &["connection_id", "slug"], "result"),+ ("disable_trigger", &["trigger_id"], "deleted"),+ ("get_mode", &[], "mode"),+ ("set_api_key", &["api_key"], "result"),+ ("clear_api_key", &[], "result"),+ ];++ for (function, required_inputs, first_output) in expected {+ let schema = openhuman_core::integrations::composio::schemas::schemas(function);+ assert_eq!(schema.namespace, "composio");+ assert_eq!(schema.function, function);+ let input_names: Vec<&str> = schema.inputs.iter().map(|f| f.name).collect();+ for required in required_inputs {+ assert!(+ input_names.contains(required),+ "{function} must declare input `{required}` (got {input_names:?})"+ );+ }+ assert_eq!(schema.outputs[0].name, first_output, "{function}");+ assert!(!schema.description.is_empty());+ }+}++#[tokio::test]+async fn composio_controller_handlers_reject_bad_params_before_network() {+ crate::tinyhumans_boot::boot();+ let registered = all_composio_registered_controllers();++ let missing_authorize = composio_call(composio_controller(®istered, "authorize"), json!({}))+ .await+ .expect_err("authorize requires toolkit");+ assert!(missing_authorize.contains("missing required param 'toolkit'"));++ let blank_delete = composio_call(+ composio_controller(®istered, "delete_connection"),+ json!({ "connection_id": " " }),+ )+ .await+ .expect_err("delete requires non-empty connection");+ assert!(blank_delete.contains("'connection_id' must not be empty"));++ let invalid_list_tools = composio_call(+ composio_controller(®istered, "list_tools"),+ json!({ "toolkits": "gmail" }),+ )+ .await+ .expect_err("toolkits must be an array");+ assert!(invalid_list_tools.contains("invalid 'toolkits'"));++ let missing_execute = composio_call(composio_controller(®istered, "execute"), json!({}))+ .await+ .expect_err("execute requires tool");+ assert!(missing_execute.contains("missing required param 'tool'"));++ let blank_create = composio_call(+ composio_controller(®istered, "create_trigger"),+ json!({ "slug": " " }),+ )+ .await+ .expect_err("create trigger rejects blank slug");+ assert!(blank_create.contains("'slug' must not be empty"));++ let missing_profile = composio_call(+ composio_controller(®istered, "get_user_profile"),+ json!({}),+ )+ .await+ .expect_err("profile requires connection id");+ assert!(missing_profile.contains("missing required param 'connection_id'"));++ let blank_available = composio_call(+ composio_controller(®istered, "list_available_triggers"),+ json!({ "toolkit": " " }),+ )+ .await+ .expect_err("available triggers rejects blank toolkit");+ assert!(blank_available.contains("'toolkit' must not be empty"));++ let missing_enable_connection = composio_call(+ composio_controller(®istered, "enable_trigger"),+ json!({ "connection_id": " ", "slug": "GMAIL_NEW_GMAIL_MESSAGE" }),+ )+ .await+ .expect_err("enable trigger rejects blank connection");+ assert!(missing_enable_connection.contains("'connection_id' must not be empty"));++ let missing_disable = composio_call(+ composio_controller(®istered, "disable_trigger"),+ json!({}),+ )+ .await+ .expect_err("disable trigger requires id");+ assert!(missing_disable.contains("missing required param 'trigger_id'"));++ let bad_set_key = composio_call(+ composio_controller(®istered, "set_api_key"),+ json!({ "api_key": "" }),+ )+ .await+ .expect_err("set api key requires non-empty key");+ assert!(bad_set_key.contains("'api_key' must not be empty"));++ let bad_github_repos = composio_call(+ composio_controller(®istered, "list_github_repos"),+ json!({ "connection_id": 42 }),+ )+ .await+ .expect_err("github repos connection id must be string");+ assert!(bad_github_repos.contains("invalid params"));++ let bad_history_limit = composio_call(+ composio_controller(®istered, "list_trigger_history"),+ json!({ "limit": "many" }),+ )+ .await+ .expect_err("history limit must be numeric");+ assert!(bad_history_limit.contains("invalid params"));++ let bad_list_triggers = composio_call(+ composio_controller(®istered, "list_triggers"),+ json!({ "toolkit": 12 }),+ )+ .await+ .expect_err("list triggers toolkit must be string");+ assert!(bad_list_triggers.contains("invalid params"));++ let missing_enable_slug = composio_call(+ composio_controller(®istered, "enable_trigger"),+ json!({ "connection_id": "conn-1", "slug": " " }),+ )+ .await+ .expect_err("enable trigger rejects blank slug");+ assert!(missing_enable_slug.contains("'slug' must not be empty"));+}++fn composio_controller<'a>(+ controllers: &'a [RegisteredController],+ function: &str,+) -> &'a RegisteredController {+ controllers+ .iter()+ .find(|controller| controller.schema.function == function)+ .unwrap_or_else(|| panic!("controller {function} registered"))+}++async fn composio_call(controller: &RegisteredController, params: Value) -> Result<Value, String> {+ let params = params.as_object().cloned().unwrap_or_default();+ (controller.handler)(DispatchCtx::process_default(), params).await+}diff --git a/tests/raw_coverage/tool_registry_approval_e2e.rs b/tests/raw_coverage/tool_registry_approval_e2e.rsindex c0a18ca8dc..a8ad301227 100644--- a/tests/raw_coverage/tool_registry_approval_e2e.rs+++ b/tests/raw_coverage/tool_registry_approval_e2e.rs@@ -395,6 +395,182 @@ enabled = trueharness.rpc_join.abort();}+#[tokio::test]+async fn approval_schema_handlers_validate_params_and_surface_empty_gate_state() {+ let schemas = all_approval_controller_schemas();+ assert_eq!(+ schemas+ .iter()+ .map(|schema| schema.function)+ .collect::<Vec<_>>(),+ vec![+ "list_pending",+ "list_recent_decisions",+ "decide",+ "get_gate_state",+ "preauthorize_flow"+ ]+ );+ let unknown = openhuman_core::security::approval::schemas::schemas("missing");+ assert_eq!(unknown.namespace, "approval");+ assert_eq!(unknown.function, "unknown");+ assert_eq!(unknown.outputs[0].name, "error");++ let controllers = all_approval_registered_controllers();+ assert_eq!(controllers.len(), schemas.len());++ let list_handler = controllers+ .iter()+ .find(|controller| controller.schema.function == "list_pending")+ .expect("list pending controller")+ .handler;+ let list_value = list_handler(DispatchCtx::process_default(), Map::new())+ .await+ .expect("list pending value");+ assert!(list_value+ .get("result")+ .or(Some(&list_value))+ .and_then(Value::as_array)+ .is_some());++ let recent_handler = controllers+ .iter()+ .find(|controller| controller.schema.function == "list_recent_decisions")+ .expect("recent decisions controller")+ .handler;+ let mut invalid_limit = Map::new();+ invalid_limit.insert("limit".to_string(), json!("ten"));+ assert!(+ recent_handler(DispatchCtx::process_default(), invalid_limit)+ .await+ .expect_err("string limit")+ .contains("expected unsigned integer")+ );+ for invalid in [json!(true), json!([]), json!({ "limit": 10 })] {+ let mut invalid_limit = Map::new();+ invalid_limit.insert("limit".to_string(), invalid);+ assert!(+ recent_handler(DispatchCtx::process_default(), invalid_limit)+ .await+ .expect_err("non-numeric limit")+ .contains("expected unsigned integer")+ );+ }+ let mut negative_limit = Map::new();+ negative_limit.insert("limit".to_string(), json!(-1));+ assert!(+ recent_handler(DispatchCtx::process_default(), negative_limit)+ .await+ .expect_err("negative limit")+ .contains("expected unsigned integer")+ );+ let mut null_limit = Map::new();+ null_limit.insert("limit".to_string(), Value::Null);+ let recent_value = recent_handler(DispatchCtx::process_default(), null_limit)+ .await+ .expect("null limit should use default");+ assert!(recent_value+ .get("result")+ .or(Some(&recent_value))+ .and_then(Value::as_array)+ .is_some());++ let decide_handler = controllers+ .iter()+ .find(|controller| controller.schema.function == "decide")+ .expect("decide controller")+ .handler;+ assert!(decide_handler(DispatchCtx::process_default(), Map::new())+ .await+ .expect_err("missing request id")+ .contains("missing required param 'request_id'"));+ let mut numeric_request = Map::new();+ numeric_request.insert("request_id".to_string(), json!(42));+ numeric_request.insert("decision".to_string(), json!("deny"));+ assert!(+ decide_handler(DispatchCtx::process_default(), numeric_request)+ .await+ .expect_err("numeric request id")+ .contains("expected string")+ );+ for invalid in [+ Value::Null,+ json!(false),+ json!([]),+ json!({ "id": "missing" }),+ ] {+ let mut invalid_request = Map::new();+ invalid_request.insert("request_id".to_string(), invalid);+ invalid_request.insert("decision".to_string(), json!("deny"));+ assert!(+ decide_handler(DispatchCtx::process_default(), invalid_request)+ .await+ .expect_err("non-string request id")+ .contains("expected string")+ );+ }+ let mut numeric_decision = Map::new();+ numeric_decision.insert("request_id".to_string(), json!("missing"));+ numeric_decision.insert("decision".to_string(), json!(42));+ assert!(+ decide_handler(DispatchCtx::process_default(), numeric_decision)+ .await+ .expect_err("numeric decision")+ .contains("expected string")+ );+ let mut invalid_decision = Map::new();+ invalid_decision.insert("request_id".to_string(), json!("missing"));+ invalid_decision.insert("decision".to_string(), json!("maybe"));+ assert!(+ decide_handler(DispatchCtx::process_default(), invalid_decision)+ .await+ .expect_err("invalid decision")+ .contains("approve_once|approve_always_for_tool|approve_always_for_flow|deny")+ );++ let preauthorize_handler = controllers+ .iter()+ .find(|controller| controller.schema.function == "preauthorize_flow")+ .expect("preauthorize flow controller")+ .handler;+ assert!(+ preauthorize_handler(DispatchCtx::process_default(), Map::new())+ .await+ .expect_err("missing flow id")+ .contains("missing required param 'flow_id'")+ );+ let mut missing_tools = Map::new();+ missing_tools.insert("flow_id".to_string(), json!("flow-1"));+ assert!(+ preauthorize_handler(DispatchCtx::process_default(), missing_tools)+ .await+ .expect_err("missing tool names")+ .contains("missing required param 'tool_names'")+ );+ let mut non_array_tools = Map::new();+ non_array_tools.insert("flow_id".to_string(), json!("flow-1"));+ non_array_tools.insert("tool_names".to_string(), json!("slack_post"));+ assert!(+ preauthorize_handler(DispatchCtx::process_default(), non_array_tools)+ .await+ .expect_err("non-array tool names")+ .contains("expected array of strings")+ );+ let mut mixed_tools = Map::new();+ mixed_tools.insert("flow_id".to_string(), json!("flow-1"));+ mixed_tools.insert("tool_names".to_string(), json!(["ok", 42]));+ assert!(+ preauthorize_handler(DispatchCtx::process_default(), mixed_tools)+ .await+ .expect_err("non-string tool name entry")+ .contains("expected string")+ );+ // Success-path behavior (gate-absent tolerance, idempotent grants, audit+ // rows) is pinned by the unit tests in `approval::rpc`/`approval::store`;+ // asserting it here would be order-dependent on whether a sibling test+ // already installed the process-global gate.+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn approval_rpc_decision_paths_persist_always_allow_and_recent_audit() {let _lock = env_lock_async().await;