Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore(tests): remove obsolete integration tests and their Cargo.toml entries

Steven Enamakel1b43fae7ddec
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml
index 9442a5d3e3..fc473b2535 100644
--- a/crates/openhuman-cli/Cargo.toml
+++ b/crates/openhuman-cli/Cargo.toml
@@ -169,10 +169,6 @@ path = "../../tests/agent_prompt_comprehension_e2e.rs"
name = "agent_harness_public"
path = "../../tests/agent_harness_public.rs"
-[[test]]
-name = "agent_multimodal_public"
-path = "../../tests/agent_multimodal_public.rs"
-
[[test]]
name = "agent_turn_overrides_e2e"
path = "../../tests/agent_turn_overrides_e2e.rs"
@@ -185,10 +181,6 @@ path = "../../tests/calendar_grounding_e2e.rs"
name = "channels_default_channel_e2e"
path = "../../tests/channels_default_channel_e2e.rs"
-[[test]]
-name = "channels_host_boundary_e2e"
-path = "../../tests/channels_host_boundary_e2e.rs"
-
[[test]]
name = "cli_model_overrides_e2e"
path = "../../tests/cli_model_overrides_e2e.rs"
@@ -197,10 +189,6 @@ path = "../../tests/cli_model_overrides_e2e.rs"
name = "cli_sigpipe"
path = "../../tests/cli_sigpipe.rs"
-[[test]]
-name = "composio_list_tools_stack_overflow_regression"
-path = "../../tests/composio_list_tools_stack_overflow_regression.rs"
-
[[test]]
name = "config_auth_app_state_connectivity_e2e"
path = "../../tests/config_auth_app_state_connectivity_e2e.rs"
@@ -229,14 +217,6 @@ path = "../../tests/keyring_secretstore_e2e.rs"
name = "keyring_secretstore_fresh_e2e"
path = "../../tests/keyring_secretstore_fresh_e2e.rs"
-[[test]]
-name = "learning_phase4_integration_test"
-path = "../../tests/learning_phase4_integration_test.rs"
-
-[[test]]
-name = "linux_cef_deb_runtime_e2e"
-path = "../../tests/linux_cef_deb_runtime_e2e.rs"
-
[[test]]
name = "live_flows_demo_e2e"
path = "../../tests/live_flows_demo_e2e.rs"
@@ -326,10 +306,6 @@ path = "../../tests/skills_mcp_registry_live.rs"
name = "transcript_search_e2e"
path = "../../tests/transcript_search_e2e.rs"
-[[test]]
-name = "web_cancel_request_scoping"
-path = "../../tests/web_cancel_request_scoping.rs"
-
[[test]]
name = "worker_b_domain_e2e"
path = "../../tests/worker_b_domain_e2e.rs"
diff --git a/tests/agent_multimodal_public.rs b/tests/agent_multimodal_public.rs
deleted file mode 100644
index 015cdd7b75..0000000000
--- a/tests/agent_multimodal_public.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-use anyhow::Result;
-use openhuman_core::agent::messages::ChatMessage;
-use openhuman_core::agent::multimodal::{
- contains_image_markers, count_image_markers, extract_ollama_image_payload, parse_image_markers,
- prepare_messages_for_provider,
-};
-use openhuman_core::config::{MultimodalConfig, MultimodalFileConfig};
-
-#[test]
-fn marker_helpers_cover_mixed_content_and_payload_extraction() {
- let messages = vec![
- ChatMessage::assistant("[IMAGE:/tmp/ignored.png]"),
- ChatMessage::user("look [IMAGE:/tmp/a.png] then [IMAGE:data:image/png;base64,abcd]"),
- ];
-
- let (cleaned, refs) = parse_image_markers(messages[1].content.as_str());
- assert_eq!(cleaned, "look then");
- assert_eq!(refs.len(), 2);
- assert_eq!(count_image_markers(&messages), 2);
- assert!(contains_image_markers(&messages));
- assert_eq!(
- extract_ollama_image_payload("data:image/png;base64,abcd").as_deref(),
- Some("abcd")
- );
- // #5146 P6 reversed this: a filesystem path used to be forwarded verbatim as
- // if it were image bytes, and Ollama answered `illegal base64 data at input
- // byte 19` — an error naming neither the parameter nor the path. Trimming
- // still happens, but the trimmed value has to be base64 to be returned.
- assert_eq!(
- extract_ollama_image_payload(" /tmp/a.png ").as_deref(),
- None
- );
- let (cleaned_unclosed, refs_unclosed) = parse_image_markers("broken [IMAGE:/tmp/a.png");
- assert_eq!(cleaned_unclosed, "broken [IMAGE:/tmp/a.png");
- assert!(refs_unclosed.is_empty());
-
- let (cleaned_empty, refs_empty) = parse_image_markers("keep [IMAGE:] literal");
- assert_eq!(cleaned_empty, "keep [IMAGE:] literal");
- assert!(refs_empty.is_empty());
-
- assert!(!contains_image_markers(&[ChatMessage::assistant(
- "no user refs"
- )]));
-}
-
-#[tokio::test]
-async fn prepare_messages_passthrough_when_no_user_images_exist() -> Result<()> {
- let messages = vec![
- ChatMessage::system("sys"),
- ChatMessage::assistant("[IMAGE:/tmp/not-counted.png]"),
- ChatMessage::user("plain text"),
- ];
-
- let prepared = prepare_messages_for_provider(
- &messages,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await?;
- assert!(!prepared.contains_images);
- assert_eq!(prepared.messages.len(), 3);
- assert_eq!(prepared.messages[2].content, "plain text");
- Ok(())
-}
-
-#[tokio::test]
-async fn prepare_messages_accepts_data_uris_and_preserves_other_messages() -> Result<()> {
- let messages = vec![
- ChatMessage::assistant("already there"),
- ChatMessage::user("inspect [IMAGE:data:image/PNG;base64,iVBORw0KGgo=]"),
- ];
-
- let prepared = prepare_messages_for_provider(
- &messages,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await?;
- assert!(prepared.contains_images);
- assert_eq!(prepared.messages[0].content, "already there");
-
- let (cleaned, refs) = parse_image_markers(&prepared.messages[1].content);
- assert_eq!(cleaned, "inspect");
- assert_eq!(refs.len(), 1);
- assert!(refs[0].starts_with("data:image/png;base64,"));
- Ok(())
-}
-
-#[tokio::test]
-async fn prepare_messages_rejects_invalid_data_uri_forms() {
- let invalid_non_base64 = vec![ChatMessage::user("bad [IMAGE:data:image/png,abcd]")];
- let err = prepare_messages_for_provider(
- &invalid_non_base64,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await
- .expect_err("non-base64 data uri should fail");
- assert!(err
- .to_string()
- .contains("only base64 data URIs are supported"));
-
- let invalid_mime = vec![ChatMessage::user("bad [IMAGE:data:text/plain;base64,YQ==]")];
- let err = prepare_messages_for_provider(
- &invalid_mime,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await
- .expect_err("unsupported mime should fail");
- assert!(err.to_string().contains("MIME type is not allowed"));
-
- let invalid_base64 = vec![ChatMessage::user("bad [IMAGE:data:image/png;base64,%%%]")];
- let err = prepare_messages_for_provider(
- &invalid_base64,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await
- .expect_err("invalid base64 should fail");
- assert!(err.to_string().contains("invalid base64 payload"));
-}
-
-#[tokio::test]
-async fn prepare_messages_rejects_unknown_local_mime() {
- let temp = tempfile::tempdir().expect("tempdir");
- let file_path = temp.path().join("sample.txt");
- std::fs::write(&file_path, b"not an image").expect("write sample");
-
- let messages = vec![ChatMessage::user(format!(
- "bad [IMAGE:{}]",
- file_path.display()
- ))];
- let err = prepare_messages_for_provider(
- &messages,
- &MultimodalConfig::default(),
- &MultimodalFileConfig::default(),
- )
- .await
- .expect_err("unknown mime should fail");
- assert!(err.to_string().contains("unknown"));
-}
diff --git a/tests/channels_host_boundary_e2e.rs b/tests/channels_host_boundary_e2e.rs
deleted file mode 100644
index 8d2abd6bac..0000000000
--- a/tests/channels_host_boundary_e2e.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-//! End-to-end coverage for the ChannelHost capability boundary.
-//!
-//! Builds the *real* OpenHuman `ChannelHost` via `build_channel_host` and
-//! drives each capability through the `dyn ChannelHost` trait objects exactly
-//! as a ported channel provider would — proving the assembled host works
-//! across the portable boundary, not just the concrete adapters in isolation.
-
-use std::sync::Arc;
-
-use openhuman_core::channels::host::build_channel_host;
-use openhuman_core::config::Config;
-use tinychannels::host::{ApprovalDecision, ConversationMessage};
-
-/// A config pinned to a throwaway workspace with the local runtime disabled,
-/// so filesystem-backed capabilities are isolated and inference is short-circuited.
-fn test_config(workspace: &std::path::Path) -> Config {
- let mut config = Config::default();
- config.workspace_dir = workspace.to_path_buf();
- config.local_ai.runtime_enabled = false;
- config
-}
-
-#[test]
-fn host_advertises_the_wired_capability_set() {
- let host = build_channel_host(Arc::new(Config::default()));
- let caps = host.capabilities();
- assert!(caps.lifecycle);
- assert!(caps.stt);
- assert!(caps.tts);
- assert!(!caps.reaction_gate);
- assert!(caps.approvals);
- assert!(caps.conversation_store);
- assert!(caps.event_sink);
- assert!(!caps.is_lean());
- // Not yet backed portably — a provider needing these degrades gracefully.
- assert!(!caps.turn_dispatch);
- assert!(!caps.run_ledger);
-}
-
-#[tokio::test]
-async fn conversation_store_roundtrips_through_the_boundary() {
- let dir = tempfile::tempdir().expect("tempdir");
- let host = build_channel_host(Arc::new(test_config(dir.path())));
- let store = host.conversations().expect("conversation store present");
-
- let thread = "e2e-thread";
- store
- .append(
- thread,
- ConversationMessage {
- role: "user".into(),
- content: "ping".into(),
- timestamp: None,
- },
- )
- .await
- .expect("append user");
- store
- .append(
- thread,
- ConversationMessage {
- role: "assistant".into(),
- content: "pong".into(),
- timestamp: None,
- },
- )
- .await
- .expect("append assistant");
-
- let history = store.history(thread, 10).await.expect("history");
- assert_eq!(history.len(), 2);
- assert_eq!(history[0].content, "ping");
- assert_eq!(history[1].content, "pong");
-}
-
-#[test]
-fn host_offers_no_reaction_gate() {
- let dir = tempfile::tempdir().expect("tempdir");
- let host = build_channel_host(Arc::new(test_config(dir.path())));
- assert!(host.reactions().is_none());
- assert!(!host.capabilities().reaction_gate);
-}
-
-#[test]
-fn approval_gate_parses_replies_through_the_boundary() {
- let host = build_channel_host(Arc::new(Config::default()));
- let gate = host.approvals().expect("approval gate present");
- assert_eq!(gate.parse_reply("yes"), Some(ApprovalDecision::Approve));
- assert_eq!(gate.parse_reply("no"), Some(ApprovalDecision::Deny));
- assert_eq!(gate.parse_reply("not-a-decision"), None);
-}
-
-#[tokio::test]
-async fn event_sink_publishes_web_channel_events() {
- let host = build_channel_host(Arc::new(Config::default()));
- let events = host.events().expect("event sink present");
- let ok = events
- .publish(
- "web",
- "chat_segment",
- serde_json::json!({
- "event": "chat_segment",
- "client_id": "c",
- "thread_id": "t",
- "request_id": "r",
- "message": "hi"
- }),
- )
- .await;
- assert!(ok.is_ok());
-}
-
-#[test]
-fn lifecycle_registry_accepts_shutdown_hooks() {
- let host = build_channel_host(Arc::new(Config::default()));
- let lifecycle = host.lifecycle().expect("lifecycle present");
- // Registration must not panic; the hook runs only at real process shutdown.
- lifecycle.register_shutdown(
- "e2e-test-hook",
- Box::new(|| Box::pin(async move { /* no-op */ })),
- );
-}
diff --git a/tests/composio_list_tools_stack_overflow_regression.rs b/tests/composio_list_tools_stack_overflow_regression.rs
deleted file mode 100644
index 07c60fcca8..0000000000
--- a/tests/composio_list_tools_stack_overflow_regression.rs
+++ /dev/null
@@ -1,396 +0,0 @@
-//! Regression for the SIGBUS in `crahs.log` (May 17, 2026, build 0.53.49).
-//!
-//! ## What crashed
-//!
-//! While a user chat went through
-//! `web_channel → orchestrator turn → delegate_to_integrations_agent
-//! → integrations_agent → composio_list_tools` (that specialist has since
-//! been removed — the orchestrator searches for and calls the action itself
-//! — but the sub-agent runner path below is the one every delegation takes), the
-//! in-process core
-//! aborted with `EXC_BAD_ACCESS (SIGBUS) — KERN_PROTECTION_FAILURE`
-//! at an address inside the **stack guard page** of a `tokio-rt-worker`
-//! thread. That's a stack overflow — not a Rust panic. The kernel
-//! reported `"Could not determine thread index for stack guard region"`.
-//!
-//! Bottom of the offending stack:
-//!
-//! ```text
-//! toml_parser::on_array_open / value / document ← recursive descent
-//! ← toml::de::from_str
-//! ← config::schema::load::parse_config_with_recovery
-//! ← Config::load_or_init_with_env_lookup
-//! ← config::ops::load_config_with_timeout
-//! ← ComposioListToolsTool::execute
-//! ← subagent_runner::run_inner_loop / run_typed_mode / run_subagent
-//! ← SkillDelegationTool::execute (delegate_to_integrations_agent, since removed)
-//! ← Agent::execute_tool_call / execute_tools / turn
-//! ← web_chat::run_chat_task
-//! ```
-//!
-//! The crash trigger is `composio_list_tools` reloading the config from
-//! disk on every call (added in #1710 Wave 4 so a mid-session
-//! `composio.mode` toggle is observed). The root cause is the
-//! combination of:
-//!
-//! 1. a ~50-frame async tower from the web channel down into
-//! the sub-agent runner,
-//! 2. serde-monomorphised `Visitor` frames for the deeply-nested
-//! [`Config`] struct, each of which can be several KB,
-//! 3. the recursive-descent TOML parser piling on a few more frames,
-//! 4. all of it running on tokio's default ~2 MB worker-thread stack.
-//!
-//! ## Why pre-existing e2e tests missed it
-//!
-//! `tests/json_rpc_e2e.rs` and the WDIO suite invoke `composio_execute`
-//! / `composio_list_tools` directly over the RPC transport. That path
-//! is only a few frames deep: transport → handler → composio. None of
-//! the existing specs string together the full `web channel chat →
-//! orchestrator → delegate_to_integrations_agent → sub-agent →
-//! composio_list_tools` chain, which is what actually piles the stack
-//! high enough to hit the guard page.
-//!
-//! ## What this test does
-//!
-//! Faithful reproduction in cargo-test is awkward: we can't easily
-//! rebuild the upper chat-channel layers (`web_chat::
-//! run_chat_task → Agent::turn → execute_tools → <delegation tool>`)
-//! without standing up an HTTP + Socket.IO stack. We drive the production
-//! path from `run_subagent` downward — i.e. everything below a delegation
-//! tool's `execute` — on a production-realistic 2 MB tokio worker stack.
-//!
-//! **Caveat — what this test does and does not catch.** Because the
-//! upper ~30 frames are missing, the bare path here fits in 2 MB even
-//! without the fix. The bug only manifests when the *full* production
-//! tower piles on. So:
-//!
-//! * **What this test does catch:** structural regressions in the
-//! sub-agent → composio_list_tools → load_config_with_timeout
-//! dispatch chain — if a refactor breaks that path or makes it
-//! blow even the production-shaped budget, this test trips.
-//! * **What this test does NOT catch:** a re-introduction of the
-//! specific stack-overflow trigger (re-inlining the TOML parse onto
-//! the worker). The production crash needed the full tower above
-//! `run_subagent` to push 2 MB over.
-//!
-//! The actual stack-overflow fix is in
-//! [`crates/openhuman-core/src/config/schema/load.rs`](`parse_config_with_recovery`)
-//! and [`crates/openhuman-core/src/config/ops.rs`](`load_config_with_timeout`):
-//!
-//! * `parse_config_with_recovery` runs `toml::from_str::<Config>` on
-//! a blocking-pool thread via `spawn_blocking`. The blocking thread
-//! has a *fresh* stack (no async tower above it), so the parser's
-//! serde-monomorphised `Visitor` frames don't compound with the
-//! agent-harness frames that called it.
-//! * `load_config_with_timeout` is fronted by a process-global cache
-//! keyed on `OPENHUMAN_WORKSPACE`, invalidated by `Config::save()`.
-//! Hot-path consumers (composio per-call reload, #1710 Wave 4) get
-//! a clone, never re-entering the parser.
-//!
-//! ## Setup
-//!
-//! * fresh tokio multi-thread runtime, `thread_stack_size(2 << 20)`
-//! (production default), so the test runs in the same stack budget
-//! production does — anything larger would let dormant regressions
-//! hide for longer,
-//! * `OPENHUMAN_WORKSPACE` pointed at a tempdir with a representative
-//! `config.toml` so the TOML parser does real work,
-//! * `run_subagent(critic)` exactly like a delegation tool
-//! does, with a stubbed `ChatModel`
-//! that emits one `composio_list_tools` tool call on iteration 1
-//! and stops on iteration 2.
-//!
-//! Assertion is implicit: cargo reports the test as failed when the
-//! tokio runtime aborts with stack overflow.
-
-// This stress target is still compiled by normal cargo test. Under llvm-cov,
-// coverage instrumentation makes the already-large integration-test binary
-// trip CI's linker with SIGBUS before the regression can run.
-#![cfg(not(coverage))]
-
-use anyhow::Result;
-use async_trait::async_trait;
-use openhuman_core::agent::harness::definition::{AgentDefinitionRegistry, ModelSpec};
-use openhuman_core::agent::harness::{with_parent_context, ParentExecutionContext};
-use openhuman_core::agent::prompts::ToolCallFormat;
-use openhuman_core::agent::subagent_host::{run_subagent, SubagentRunOptions};
-use openhuman_core::config::AgentConfig;
-use openhuman_core::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
-use parking_lot::Mutex;
-use serde_json::json;
-use std::sync::Arc;
-use tempfile::tempdir;
-use tinyinference_llm::message::AssistantMessage;
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
-use tinyinference_llm::tool::ToolCall;
-
-// ── env serialisation (config-rs reads process env) ──────────────────
-
-static ENV_LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let m = ENV_LOCK.get_or_init(|| std::sync::Mutex::new(()));
- match m.lock() {
- Ok(g) => g,
- Err(p) => p.into_inner(),
- }
-}
-
-struct EnvGuard {
- key: &'static str,
- prev: Option<String>,
-}
-
-impl EnvGuard {
- fn set(key: &'static str, val: &str) -> Self {
- let prev = std::env::var(key).ok();
- // SAFETY: caller holds env_lock().
- unsafe { std::env::set_var(key, val) };
- Self { key, prev }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- match &self.prev {
- // SAFETY: caller's env_lock guard is still alive during drop.
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
-// ── representative on-disk config ────────────────────────────────────
-//
-// Shape-matches a real user's `config.toml`: many `#[serde(default)]`
-// sub-sections so the Visitor traversal during `toml::from_str::<Config>`
-// monomorphises through the same code paths as production.
-
-const REPRESENTATIVE_CONFIG_TOML: &str = r#"
-schema_version = 2
-default_model = "reasoning-v1"
-default_temperature = 0.7
-temperature_unsupported_models = ["o1*", "o3*", "o4*", "gpt-5*"]
-onboarding_completed = true
-chat_onboarding_completed = true
-
-[observability]
-[autonomy]
-[runtime]
-[autocomplete]
-[reliability]
-[scheduler]
-[scheduler_gate]
-[agent]
-[orchestrator]
-[composio]
-mode = "backend"
-entity_id = "test-entity"
-"#;
-
-// ── mock model that emits one composio_list_tools tool call ─────────
-
-struct StubModel {
- iter: Arc<Mutex<usize>>,
- profile: ModelProfile,
-}
-
-#[async_trait]
-impl ChatModel<()> for StubModel {
- fn profile(&self) -> Option<&ModelProfile> {
- Some(&self.profile)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let mut count = self.iter.lock();
- *count += 1;
- if *count == 1 {
- Ok(ModelResponse {
- message: AssistantMessage {
- id: None,
- content: Vec::new(),
- tool_calls: vec![ToolCall::new(
- "call_1",
- "composio_list_tools",
- json!({ "toolkits": ["gmail"] }),
- )],
- usage: None,
- origin: None,
- },
- usage: None,
- finish_reason: Some("tool_calls".into()),
- raw: None,
- resolved_model: None,
- continue_turn: None,
- served_from_cache: false,
- correlation: None,
- resolved_route: None,
- })
- } else {
- Ok(ModelResponse::assistant("done"))
- }
- }
-}
-
-// ── stub memory ──────────────────────────────────────────────────────
-
-struct StubMemory;
-
-#[async_trait]
-impl Memory for StubMemory {
- async fn store(
- &self,
- _: &str,
- _: &str,
- _: &str,
- _: MemoryCategory,
- _: Option<&str>,
- ) -> Result<()> {
- Ok(())
- }
- async fn recall(&self, _: &str, _: usize, _: RecallOpts<'_>) -> Result<Vec<MemoryEntry>> {
- Ok(vec![])
- }
- async fn get(&self, _: &str, _: &str) -> Result<Option<MemoryEntry>> {
- Ok(None)
- }
- async fn list(
- &self,
- _: Option<&str>,
- _: Option<&MemoryCategory>,
- _: Option<&str>,
- ) -> Result<Vec<MemoryEntry>> {
- Ok(vec![])
- }
- async fn forget(&self, _: &str, _: &str) -> Result<bool> {
- Ok(true)
- }
- async fn namespace_summaries(&self) -> Result<Vec<NamespaceSummary>> {
- Ok(vec![])
- }
- async fn count(&self) -> Result<usize> {
- Ok(0)
- }
- async fn health_check(&self) -> bool {
- true
- }
- fn name(&self) -> &str {
- "stub"
- }
-}
-
-// ── the regression itself ────────────────────────────────────────────
-
-/// Structural regression for the path that crashed in `crahs.log`.
-/// See module docs for what this test does and does not catch.
-///
-/// `#[test]` (not `#[tokio::test]`) so the worker stack size is set
-/// explicitly. The work runs via `tokio::spawn` so the assertion is
-/// performed on a 2 MB worker rather than on `block_on`'s driver
-/// thread (which inherits the much larger cargo-test main-thread stack
-/// and would hide stack-budget regressions).
-#[test]
-#[ignore = "TODO(#6379): hosted TinyAgents delegation exceeds the production worker stack budget"]
-fn composio_list_tools_via_subagent_runs_on_production_worker_stack() {
- // Serialise env mutation across the test binary (other tests may
- // poke OPENHUMAN_WORKSPACE concurrently).
- let _env = env_lock();
-
- let tmp = tempdir().expect("tempdir");
- std::fs::write(tmp.path().join("config.toml"), REPRESENTATIVE_CONFIG_TOML)
- .expect("write representative config.toml");
- let _ws_guard = EnvGuard::set(
- "OPENHUMAN_WORKSPACE",
- tmp.path().to_str().expect("tempdir path utf-8"),
- );
-
- // Production tokio worker stack default is ~2 MB. The SIGBUS in
- // crahs.log occurred at an address inside a 2080 KB stack region
- // (`Stack 302648000-302850000`). Reproduce that budget exactly.
- let rt = tokio::runtime::Builder::new_multi_thread()
- .worker_threads(2)
- .thread_stack_size(2 * 1024 * 1024)
- .enable_all()
- .build()
- .expect("build runtime");
-
- // The actual work has to be on a worker thread, not the
- // `block_on` driver thread (which inherits the OS test-runner stack
- // and is much larger). Spawn → join to force the closure onto a
- // 2 MB worker.
- rt.block_on(async {
- tokio::spawn(drive_subagent())
- .await
- .expect("subagent task must complete without SIGBUS / panic");
- });
-}
-
-async fn drive_subagent() {
- let _ = AgentDefinitionRegistry::init_global_builtins();
-
- let mut profile = ModelProfile::default();
- profile.tool_calling = true;
- let model = Arc::new(StubModel {
- iter: Arc::new(Mutex::new(0)),
- profile,
- });
-
- let parent = ParentExecutionContext {
- agent_definition_id: "orchestrator".into(),
- allowed_subagent_ids: ["critic".to_string()].into_iter().collect(),
- turn_model_source: openhuman_core::agent::tinyagents::TurnModelSource::from_model(model),
- all_tools: Arc::new(vec![]),
- all_tool_specs: Arc::new(vec![]),
- // #6145: empty means "same surface as `all_tool_specs`" — the
- // catalogue falls back to it, so these stubs keep the behaviour
- // they had before the parent's visible set became its own field.
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".into(),
- temperature: 0.4,
- workspace_dir: std::env::temp_dir(),
- workspace_descriptor: None,
- memory: Arc::new(StubMemory),
- agent_config: AgentConfig::default(),
- workflows: Arc::new(vec![]),
- memory_context: Arc::new(None),
- session_id: "stack-regression-session".into(),
- channel: "test".into(),
- connected_integrations: vec![],
- tool_call_format: ToolCallFormat::PFormat,
- session_key: "0_stack_regression".into(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- };
-
- let mut def = AgentDefinitionRegistry::global()
- .expect("registry initialised")
- .get("critic")
- .expect("critic built-in must exist")
- .clone();
- // A shipped definition with a `model.hint` would otherwise build a
- // fresh model via the workload factory and try to hit the real
- // backend. Override to Inherit so the stub model above receives the
- // request — same trick used in `tests/calendar_grounding_e2e.rs`.
- def.model = ModelSpec::Inherit;
-
- // The assertion is implicit: if the worker thread overflows its
- // stack the cargo-test process aborts (SIGABRT / SIGBUS) and no
- // test report is emitted. We don't care whether the sub-agent
- // semantically "succeeded" — only that the runtime did not abort.
- let _ = with_parent_context(parent, async move {
- run_subagent(
- &def,
- "list available gmail actions",
- SubagentRunOptions::default(),
- )
- .await
- })
- .await;
-}
diff --git a/tests/learning_phase4_integration_test.rs b/tests/learning_phase4_integration_test.rs
deleted file mode 100644
index 6ad2002c83..0000000000
--- a/tests/learning_phase4_integration_test.rs
+++ /dev/null
@@ -1,313 +0,0 @@
-//! Phase 4 integration test for agent self-learning (#566).
-//!
-//! Exercises the full end-to-end pipeline:
-//! 1. Initialize a temp memory client + facet cache + stability detector + profile_md renderer.
-//! 2. Push 5 candidates spanning multiple classes.
-//! 3. Call `StabilityDetector::rebuild()`.
-//! 4. Verify `CacheRebuilt` event fired.
-//! 5. Verify `ProfileMdRenderer` wrote to `PROFILE.md` with expected blocks + bullets.
-//! 6. Call `learning.pin_facet` RPC for one entry → re-rebuild → verify it stays Active.
-//! 7. Call `learning.forget_facet` for another → verify it disappears from PROFILE.md.
-//! 8. Call `learning.list_facets` → verify shape.
-//!
-//! Run with: `cargo test --test learning_phase4_integration_test`
-
-use std::sync::Arc;
-use std::time::SystemTime;
-use std::time::UNIX_EPOCH;
-
-use openhuman_core::agent::learning::cache::{class_prefix, FacetCache};
-use openhuman_core::agent::learning::candidate::{
- self as candidate, CueFamily, EvidenceRef, FacetClass, LearningCandidate,
-};
-use openhuman_core::agent::learning::profile_md_renderer::ProfileMdRenderer;
-use openhuman_core::agent::learning::stability_detector::StabilityDetector;
-use openhuman_core::memory::api::provider::{FacetState, FacetType, ProfileFacet, UserState};
-use tempfile::TempDir;
-
-fn now_secs() -> f64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs_f64()
-}
-
-fn make_candidate(
- class: FacetClass,
- key: &str,
- value: &str,
- cue: CueFamily,
- now: f64,
-) -> LearningCandidate {
- LearningCandidate {
- class,
- key: key.into(),
- value: value.into(),
- cue_family: cue,
- evidence: EvidenceRef::Episodic { episodic_id: 1 },
- initial_confidence: 0.9,
- observed_at: now,
- }
-}
-
-/// Build a test harness backed by an in-memory SQLite database.
-///
-/// Uses the global candidate buffer (Phase 3 public API). To avoid test
-/// interference the harness immediately drains the buffer before pushing
-/// its own candidates.
-struct TestHarness {
- cache: Arc<FacetCache>,
- detector: StabilityDetector,
- renderer: Arc<ProfileMdRenderer>,
- workspace: TempDir,
-}
-
-impl TestHarness {
- fn new() -> Self {
- // In-memory profile rather than an in-memory SQLite store: the facet
- // store moved behind the memory driver, and this test is about the
- // learning pipeline, not persistence.
- // One shared profile behind both handles — the cache and the detector
- // must see the same facets, exactly as they shared one SQLite
- // connection before.
- let profile: Arc<openhuman_core::agent::learning::test_profile::InMemoryProfile> =
- Arc::new(Default::default());
- let cache = Arc::new(FacetCache::for_tests(Arc::clone(&profile) as Arc<_>));
-
- let workspace = TempDir::new().unwrap();
- let renderer = Arc::new(ProfileMdRenderer::new(
- Arc::clone(&cache),
- workspace.path().to_path_buf(),
- ));
-
- // Drain any stale candidates from prior tests so they don't affect
- // this test's results.
- let _ = candidate::global().drain();
-
- let detector =
- StabilityDetector::new(FacetCache::for_tests(Arc::clone(&profile) as Arc<_>));
-
- TestHarness {
- cache,
- detector,
- renderer,
- workspace,
- }
- }
-}
-
-// ── The integration test ──────────────────────────────────────────────────────
-
-#[tokio::test]
-async fn phase4_end_to_end_pin_forget_profile_md_list() {
- let harness = TestHarness::new();
- let now = now_secs();
-
- // Step 1: Push 5 candidates spanning multiple classes.
- // Push enough explicit evidence per candidate to clear τ_promote = 1.5.
- let candidates = [
- (FacetClass::Style, "verbosity", "terse"),
- (FacetClass::Identity, "name", "Alice"),
- (FacetClass::Tooling, "editor", "neovim"),
- (
- FacetClass::Goal,
- "primary",
- "Ship the agent self-learning feature",
- ),
- (FacetClass::Veto, "no-emojis", "avoid emojis in output"),
- ];
-
- for (class, key, value) in &candidates {
- // Push 5 explicit candidates per key so the aggregated stability clears τ_promote.
- for j in 0..5_u32 {
- candidate::global().push(make_candidate(
- *class,
- key,
- value,
- CueFamily::Explicit,
- now - f64::from(j),
- ));
- }
- }
-
- // Step 2: Run rebuild.
- let outcome = harness.detector.rebuild(now).await.unwrap();
- assert!(
- outcome.added >= 1,
- "rebuild should have added rows: {outcome:?}"
- );
-
- // Step 3: Verify all 5 candidates are now Active.
- let active = harness.cache.list_active().await.unwrap();
- assert!(
- active.len() >= 5,
- "expected ≥ 5 active rows, got {}: {:?}",
- active.len(),
- active.iter().map(|f| &f.key).collect::<Vec<_>>(),
- );
-
- // Step 4: Render PROFILE.md via the renderer.
- harness.renderer.render().await.unwrap();
-
- let profile_path = harness.workspace.path().join("PROFILE.md");
- assert!(profile_path.exists(), "PROFILE.md was not created");
- let profile_content = std::fs::read_to_string(&profile_path).unwrap();
-
- // Verify expected blocks.
- assert!(
- profile_content.contains("## Style"),
- "Style block missing:\n{profile_content}"
- );
- assert!(
- profile_content.contains("## Identity"),
- "Identity block missing:\n{profile_content}"
- );
- assert!(
- profile_content.contains("## Tooling"),
- "Tooling block missing:\n{profile_content}"
- );
- assert!(
- profile_content.contains("## Goals"),
- "Goals block missing:\n{profile_content}"
- );
- assert!(
- profile_content.contains("## Vetoes"),
- "Vetoes block missing:\n{profile_content}"
- );
- // Style facet should be in **key**: value format.
- assert!(
- profile_content.contains("terse"),
- "style/verbosity=terse missing:\n{profile_content}"
- );
- // Goal should render as plain sentence.
- assert!(
- profile_content.contains("Ship the agent self-learning feature"),
- "goal sentence missing:\n{profile_content}"
- );
-
- // Step 5: Pin the style/verbosity facet.
- let style_key = format!("{}/verbosity", class_prefix(FacetClass::Style));
- harness
- .cache
- .set_user_state(&style_key, UserState::Pinned)
- .await
- .unwrap();
-
- // Re-rebuild with no new candidates (only decay applies).
- let outcome2 = harness.detector.rebuild(now).await.unwrap();
- // The pinned row should remain Active regardless of decay.
- let pinned_facet = harness.cache.get(&style_key).await.unwrap();
- assert!(pinned_facet.is_some(), "pinned row must survive re-rebuild");
- let pf = pinned_facet.unwrap();
- assert_eq!(
- pf.state,
- FacetState::Active,
- "pinned row must stay Active after re-rebuild"
- );
- assert_eq!(pf.user_state, UserState::Pinned);
- let _ = outcome2; // used for assertion comment
-
- // Re-render and verify pin marker.
- harness.renderer.render().await.unwrap();
- let profile_after_pin = std::fs::read_to_string(&profile_path).unwrap();
- assert!(
- profile_after_pin.contains("*(pinned)*"),
- "pinned marker missing from PROFILE.md:\n{profile_after_pin}"
- );
-
- // Step 6: Forget the identity/name facet.
- let identity_key = format!("{}/name", class_prefix(FacetClass::Identity));
- let mut identity_facet = harness.cache.get(&identity_key).await.unwrap().unwrap();
- identity_facet.user_state = UserState::Forgotten;
- identity_facet.state = FacetState::Dropped;
- harness.cache.upsert(&identity_facet).await.unwrap();
-
- // Re-render.
- harness.renderer.render().await.unwrap();
- let profile_after_forget = std::fs::read_to_string(&profile_path).unwrap();
- // identity/name=Alice should no longer appear in the visible sections.
- // (The identity block placeholder renders if all identity rows are non-active.)
- let identity_block_start = profile_after_forget
- .find("<!-- openhuman:identity:start -->")
- .unwrap_or(0);
- let identity_block_end = profile_after_forget
- .find("<!-- openhuman:identity:end -->")
- .unwrap_or(profile_after_forget.len());
- let identity_block_content = &profile_after_forget[identity_block_start..identity_block_end];
- assert!(
- !identity_block_content.contains("Alice")
- || identity_block_content.contains("*(no entries yet)*"),
- "forgotten facet Alice must not appear in identity block:\n{identity_block_content}"
- );
-
- // Step 7: list_facets — verify shape.
- let all_active = harness.cache.list_active().await.unwrap();
- // The style facet should be present (pinned, Active).
- assert!(
- all_active.iter().any(|f| f.key == style_key),
- "pinned style/verbosity must appear in list_active"
- );
- // The forgotten identity/name should NOT appear in Active list.
- assert!(
- !all_active.iter().any(|f| f.key == identity_key),
- "forgotten identity/name must not appear in list_active"
- );
-
- // Verify the connected-accounts block is untouched (never written by renderer).
- assert!(
- !profile_after_forget.contains("<!-- openhuman:connected-accounts:start -->"),
- "connected-accounts block should not be written by the renderer"
- );
-
- println!("phase4_end_to_end_pin_forget_profile_md_list: all assertions passed");
-}
-
-// ── list_facets unit-level smoke test (no RPC server needed) ─────────────────
-
-#[tokio::test]
-async fn list_facets_cache_direct_active_vs_all() {
- let cache = openhuman_core::agent::learning::test_profile::in_memory_cache();
-
- let make = |id: &str, key: &str, state: FacetState| ProfileFacet {
- facet_id: id.into(),
- facet_type: FacetType::Preference,
- key: key.into(),
- value: "val".into(),
- confidence: 0.8,
- evidence_count: 2,
- source_segment_ids: None,
- first_seen_at: 1000.0,
- last_seen_at: 2000.0,
- state,
- stability: 2.0,
- user_state: UserState::Auto,
- evidence_refs: vec![],
- class: key.split('/').next().map(str::to_string),
- cue_families: None,
- };
-
- cache
- .upsert(&make("f1", "style/verbosity", FacetState::Active))
- .await
- .unwrap();
- cache
- .upsert(&make("f2", "style/tone", FacetState::Provisional))
- .await
- .unwrap();
- cache
- .upsert(&make("f3", "identity/name", FacetState::Dropped))
- .await
- .unwrap();
-
- let active = cache.list_active().await.unwrap();
- assert_eq!(
- active.len(),
- 1,
- "list_active should only return Active rows"
- );
- assert_eq!(active[0].key, "style/verbosity");
-
- let all = cache.list_all().await.unwrap();
- // All 3 rows (Active + Provisional + Dropped).
- assert_eq!(all.len(), 3, "list_all should return all rows");
-}