Skip to content

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

test(memory): restore the host tests deleted for an incidental engine import\n\nAn audit of every deleted assertion against upstream found that five `tests/`\ntargets were removed for the wrong reason. Each is about *this* crate's\nbehaviour and named the engine once or twice in passing, and the pass that\nremoved them keyed on "does this file reference the engine" rather than on\nwhat it asserts.\n\n near90_closure_raw_coverage_e2e 23 host refs : 1 engine\n agent_session_turn_raw_coverage_e2e 21 : 1\n agent_archivist_debug_round21_raw_coverage 13 : 2\n agent_turn_overrides_e2e 12 : 1\n memory_sync_round23_raw_coverage_e2e 8 : 1\n\n18 tests come back. `memory_sync_round23`'s subject is\n`integrations::composio::identity_store` — this host's own port — and it\nmerely imported `is_self_identity_any_toolkit` alongside; `agent_turn_overrides`\nand `agent_session_turn` assert turn-override and session-turn behaviour and\nneeded only *a* memory to construct an agent with.\n\nThat last need is now `tests/support/noop_memory.rs`. It has to live under\n`tests/` rather than reuse `memory::test_support::noop_memory`, because that\none is `pub(crate)` and a `tests/*.rs` target links this crate as an ordinary\ndependency where crate-private items are invisible — the same wall\n`host_impls::install_for_tests` hit from the other side.\n\n`ollama_embeddings_fallback_e2e` was restored by the same sweep and deleted\nagain on inspection: its subject is `effective_embedding_settings_probed`,\nwhich is defined in `tinymemory_core::store::factories`. Host-reference count\nmade it look host-owned; the API it exercises settles it. Counting references\nis a filter, not a verdict.\n\nFour more tests went in the other direction. `raw_coverage_all` carries\n`required-features`, so a default-feature `cargo test` **silently skips it and\nstill exits 0** — the trap AGENTS.md names. Verified against\n`scripts/ci/product-features.sh`, three of its files still drove the engine\nthrough `setup_provider`, `fts5`, `segments`, `profile`, `sources::sync` and\n`sources::status`. Those are gone now, and every check from here uses the\nproduct feature set.\n\nRefs #6161\n

Shanu2d25cbbd3671
diff --git a/tests/agent_turn_overrides_e2e.rs b/tests/agent_turn_overrides_e2e.rs
new file mode 100644
index 0000000000..a7322c4780
--- /dev/null
+++ b/tests/agent_turn_overrides_e2e.rs
@@ -0,0 +1,679 @@
+//! E2E coverage for per-turn `TurnOverrides` (openhuman#5844 / opencompany#1725).
+//!
+//! #5844 shipped four per-turn suppressions and two terminal goal APIs with no
+//! test in any e2e lane. Inside the unit lane the coverage was thinner than it
+//! looked: `suppress_active_goal` appears only as a field set to `true` inside
+//! the *memory-agent* test's struct literal
+//! (`session/turn_tests_part_02_tests.rs:114`) with nothing asserting the goal
+//! block is absent, and `suppress_transcript_autoload` appears once, as `false`
+//! (`:115`) — it is never exercised at all.
+//!
+//! These drive a real `Agent::turn` against a scripted model and assert on what
+//! actually reaches the provider.
+//!
+//! # Every test carries its own control
+//!
+//! A suppression test with no control passes happily when the feature it
+//! suppresses never ran in the first place. So each case first asserts the
+//! un-overridden turn DOES carry the thing, then that the overridden one does
+//! not. If a control ever stops holding, the paired assertion has stopped
+//! proving anything and must be re-derived rather than trusted.
+//!
+//! The env var and the goal store are process-global, so every test holds
+//! `env_lock()` across its await points on purpose — the lock IS the
+//! serialization mechanism, which makes `clippy::await_holding_lock` a false
+//! positive here.
+#![allow(clippy::await_holding_lock)]
+
+#[path = "support/noop_memory.rs"]
+mod noop_memory;
+
+use async_trait::async_trait;
+use std::collections::VecDeque;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex, OnceLock};
+use tempfile::TempDir;
+
+use openhuman_core::openhuman::agent::dispatcher::{NativeToolDispatcher, XmlToolDispatcher};
+use openhuman_core::openhuman::agent::harness::session::TurnOverrides;
+use openhuman_core::openhuman::agent::tinyagents::thread_context::with_thread_id;
+use openhuman_core::openhuman::agent::Agent;
+use openhuman_core::openhuman::config::{AgentConfig, Config, ContextConfig, MemoryConfig};
+use openhuman_core::openhuman::threads::goals::{runtime as goal_runtime, store as goal_store};
+use openhuman_core::openhuman::tools::{
+ PermissionLevel, Tool, ToolContent, ToolResult, ToolScope as RuntimeToolScope,
+};
+use tinyinference::message::Message;
+use tinyinference::model::{
+ ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+};
+
+// ─── Harness ────────────────────────────────────────────────────────────────
+
+struct EnvGuard {
+ key: &'static str,
+ previous: Option<std::ffi::OsString>,
+}
+
+impl EnvGuard {
+ fn set_path(key: &'static str, value: &std::path::Path) -> Self {
+ let previous = std::env::var_os(key);
+ unsafe { std::env::set_var(key, value) };
+ Self { key, previous }
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ match self.previous.take() {
+ Some(value) => unsafe { std::env::set_var(self.key, value) },
+ None => unsafe { std::env::remove_var(self.key) },
+ }
+ }
+}
+
+static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ ENV_LOCK
+ .get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
+
+/// `create_memory` requires the TinyMemory host seams and fails loudly when they
+/// are unwired — a deliberate choice, since an unwired embedding host would
+/// otherwise corrupt an embedding space quietly. Installed on a wide stack
+/// because the seam installer recurses deeply.
+fn ensure_memory_seams() {
+ MEMORY_SEAMS_INIT.get_or_init(|| {
+ std::thread::Builder::new()
+ .name("turn-overrides-e2e-seams".to_string())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(|| {
+ })
+ .expect("spawn turn-overrides seam installer")
+ .join()
+ .expect("turn-overrides seam installer panicked");
+ });
+}
+
+/// The agent turn loop needs the wide worker stack the product gives it.
+fn run_on_agent_stack<F, Fut>(name: &str, future_factory: F)
+where
+ F: FnOnce() -> Fut + Send + 'static,
+ Fut: std::future::Future<Output = ()> + 'static,
+{
+ std::thread::Builder::new()
+ .name(name.to_string())
+ .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(move || {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .enable_all()
+ .build()
+ .expect("build turn-overrides runtime")
+ .block_on(future_factory());
+ })
+ .expect("spawn turn-overrides thread")
+ .join()
+ .expect("turn-overrides thread should not panic");
+}
+
+#[derive(Clone, Debug)]
+struct CapturedRequest {
+ messages: Vec<Message>,
+ tool_names: Vec<String>,
+}
+
+struct ScriptedModel {
+ responses: Mutex<VecDeque<ModelResponse>>,
+ requests: Mutex<Vec<CapturedRequest>>,
+ profile: ModelProfile,
+}
+
+impl ScriptedModel {
+ fn new(responses: Vec<ModelResponse>) -> Arc<Self> {
+ Arc::new(Self {
+ responses: Mutex::new(responses.into_iter().collect()),
+ requests: Mutex::new(Vec::new()),
+ profile: ModelProfile::default(),
+ })
+ }
+
+ fn requests(&self) -> Vec<CapturedRequest> {
+ self.requests.lock().unwrap().clone()
+ }
+
+ /// Every message text the provider was ever handed, flattened.
+ fn all_prompt_text(&self) -> String {
+ self.requests()
+ .iter()
+ .flat_map(|request| request.messages.iter().map(|message| message.text()))
+ .collect::<Vec<_>>()
+ .join("\n---\n")
+ }
+
+ fn capture(&self, request: &ModelRequest) {
+ self.requests.lock().unwrap().push(CapturedRequest {
+ messages: request.messages.clone(),
+ tool_names: request.tools.iter().map(|tool| tool.name.clone()).collect(),
+ });
+ }
+
+ fn pop(&self) -> ModelResponse {
+ self.responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| ModelResponse::assistant("default scripted final"))
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ScriptedModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(&self.profile)
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ self.capture(&request);
+ Ok(self.pop())
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference::Result<ModelStream> {
+ self.capture(&request);
+ let items = vec![
+ ModelStreamItem::Started,
+ ModelStreamItem::Completed(self.pop()),
+ ];
+ Ok(Box::pin(futures::stream::iter(items)))
+ }
+}
+
+/// A trivial always-available tool, so `suppress_tools` has something to hide.
+struct EchoTool;
+
+#[async_trait]
+impl Tool for EchoTool {
+ fn name(&self) -> &str {
+ "turn_overrides_echo"
+ }
+
+ fn description(&self) -> &str {
+ "Echo a value back."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({
+ "type": "object",
+ "properties": { "value": { "type": "string" } },
+ "required": ["value"],
+ })
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::ReadOnly
+ }
+
+ fn scope(&self) -> RuntimeToolScope {
+ RuntimeToolScope::All
+ }
+
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult {
+ content: vec![ToolContent::Text {
+ text: "echoed".to_string(),
+ }],
+ is_error: false,
+ markdown_formatted: None,
+ })
+ }
+}
+
+fn workspace(label: &str) -> (TempDir, PathBuf) {
+ let temp = TempDir::new().expect("workspace tempdir");
+ let path = temp.path().join(label);
+ std::fs::create_dir_all(&path).expect("create workspace dir");
+ (temp, path)
+}
+
+fn agent_with(
+ model: Arc<dyn ChatModel<()>>,
+ tools: Vec<Box<dyn Tool>>,
+ workspace_path: PathBuf,
+ dispatcher: Box<dyn openhuman_core::openhuman::agent::dispatcher::ToolDispatcher>,
+) -> Agent {
+ Agent::builder()
+ .chat_model(model)
+ .tools(tools)
+ .memory(noop_memory::noop_memory())
+ .tool_dispatcher(dispatcher)
+ .workspace_dir(workspace_path)
+ .event_context("turn-overrides-session", "turn-overrides-channel")
+ .agent_definition_name("turn-overrides/orchestrator")
+ .config(AgentConfig {
+ max_tool_iterations: 2,
+ max_history_messages: 12,
+ ..AgentConfig::default()
+ })
+ .context_config(ContextConfig::default())
+ .auto_save(true)
+ .explicit_preferences_enabled(false)
+ .build()
+ .expect("build agent")
+}
+
+fn text(body: &str) -> ModelResponse {
+ ModelResponse::assistant(body)
+}
+
+// ─── suppress_active_goal ───────────────────────────────────────────────────
+
+/// A goal an earlier task left uncompleted must not steer an unrelated chat
+/// turn: `suppress_active_goal` keeps the `[thread goal]` block out of the
+/// prompt entirely.
+#[test]
+fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt() {
+ run_on_agent_stack(
+ "turn-overrides-suppress-active-goal",
+ suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner,
+ );
+}
+
+async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+
+ // Control and measured agent get SEPARATE workspaces on purpose.
+ //
+ // `agent_with` builds with `auto_save(true)` and one shared
+ // `agent_definition_name`, so a second agent in the same workspace starts
+ // with an empty history and auto-loads the FIRST agent's transcript — which
+ // contains the very `[thread goal]` block this test is asserting the absence
+ // of. Sharing a workspace therefore makes this test fail for a reason that
+ // has nothing to do with `suppress_active_goal` (proved: with one workspace
+ // the control passes and the suppression assertion fails, while
+ // `suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript`
+ // passes — i.e. the replay is real). Two workspaces, one goal seeded in each,
+ // isolates the flag under test.
+ let (_control_temp, control_workspace) = workspace("suppress-active-goal-control");
+ let (_temp, workspace_path) = workspace("suppress-active-goal");
+
+ const THREAD: &str = "thread-suppress-active-goal";
+ const OBJECTIVE: &str = "turn-overrides objective that must not leak into small talk";
+
+ with_thread_id(THREAD, async {
+ // CONTROL — without the override the goal reaches the prompt.
+ let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
+ goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)
+ .await
+ .expect("seed an active thread goal for the control");
+ let control_model = ScriptedModel::new(vec![text("control final")]);
+ let mut control = agent_with(
+ control_model.clone(),
+ Vec::new(),
+ control_workspace.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ control
+ .turn("where are we on the task?")
+ .await
+ .expect("control turn should succeed");
+ assert!(
+ control_model.all_prompt_text().contains(OBJECTIVE),
+ "control: an Active thread goal must reach the prompt, otherwise this test \
+ cannot prove that suppression does anything"
+ );
+ drop(control_guard);
+
+ // SUPPRESSED — a goal seeded identically, in a workspace no other agent
+ // has ever written a transcript into, must not appear.
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ goal_store::set(&workspace_path, THREAD, OBJECTIVE, None)
+ .await
+ .expect("seed an active thread goal for the measured agent");
+ let model = ScriptedModel::new(vec![text("chat final")]);
+ let mut agent = agent_with(
+ model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ agent.set_next_turn_overrides(TurnOverrides {
+ suppress_active_goal: true,
+ ..Default::default()
+ });
+ agent.turn("hey").await.expect("suppressed turn");
+
+ let prompt = model.all_prompt_text();
+ assert!(
+ !prompt.contains(OBJECTIVE),
+ "suppress_active_goal must keep the thread goal's objective out of the prompt; \
+ prompt was: {prompt}"
+ );
+ assert!(
+ !prompt.contains("[thread goal]"),
+ "suppress_active_goal must not inject the [thread goal] block; prompt was: {prompt}"
+ );
+ })
+ .await;
+}
+
+// ─── suppress_transcript_autoload ───────────────────────────────────────────
+
+/// The silent one. `turn()` auto-resumes an empty-history session from the
+/// agent's most recent on-disk transcript, and that lookup resolves the latest
+/// transcript **by agent name — it is not thread-scoped**. A host that has just
+/// re-bound its in-memory history to a different chat therefore gets the
+/// previous thread's conversation back underneath it and answers grounded in the
+/// wrong one, with no error anywhere (#1725).
+#[test]
+fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript() {
+ run_on_agent_stack(
+ "turn-overrides-suppress-transcript-autoload",
+ suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript_inner,
+ );
+}
+
+async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+ let (_temp, workspace_path) = workspace("suppress-transcript-autoload");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+
+ const PRIOR_MARKER: &str = "turn-overrides-prior-thread-secret-topic";
+ // Two ids, so the run enacts #1725's actual shape: a host that has re-bound
+ // its history to a *different* chat, not merely a second agent on the same
+ // one.
+ //
+ // These scopes do not steer the lookup, and are not meant to. Autoload is
+ // `session_io_impl_01_part_01.rs:45` — `latest_for_agent(&self.agent_definition_name)`
+ // — which never reads `thread_context::current_thread_id()`; that
+ // agent-name-only resolution IS the defect the override exists to work
+ // around. They are here so the control states the stronger fact (the prior
+ // transcript is replayed *even under a different thread id*), and so that a
+ // future change making autoload thread-scoped fails this control loudly
+ // instead of passing while quietly changing what the test means.
+ const PRIOR_THREAD: &str = "turn-overrides-autoload-thread-a";
+ const LATER_THREAD: &str = "turn-overrides-autoload-thread-b";
+
+ // A first conversation persists a transcript under this agent name.
+ with_thread_id(PRIOR_THREAD, async {
+ let first_model = ScriptedModel::new(vec![text("first thread reply")]);
+ let mut first = agent_with(
+ first_model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ first
+ .turn(PRIOR_MARKER)
+ .await
+ .expect("first thread turn should succeed");
+ })
+ .await;
+
+ // Everything below is the *later* chat the host has re-bound to.
+ with_thread_id(LATER_THREAD, async {
+ // CONTROL — a fresh agent with an empty history DOES pick that transcript
+ // up, across the thread change.
+ let control_model = ScriptedModel::new(vec![text("control reply")]);
+ let mut control = agent_with(
+ control_model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ control
+ .turn("an unrelated question")
+ .await
+ .expect("control turn should succeed");
+ assert!(
+ control_model.all_prompt_text().contains(PRIOR_MARKER),
+ "control: a fresh agent must auto-load the prior thread's transcript even under a \
+ different thread id, otherwise this test cannot prove that \
+ suppress_transcript_autoload prevents anything"
+ );
+
+ // SUPPRESSED — the same shape must not see the earlier conversation.
+ let model = ScriptedModel::new(vec![text("clean reply")]);
+ let mut agent = agent_with(
+ model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ agent.set_next_turn_overrides(TurnOverrides {
+ suppress_transcript_autoload: true,
+ ..Default::default()
+ });
+ agent
+ .turn("an unrelated question")
+ .await
+ .expect("suppressed turn should succeed");
+
+ let prompt = model.all_prompt_text();
+ assert!(
+ !prompt.contains(PRIOR_MARKER),
+ "suppress_transcript_autoload must not replay another conversation's transcript \
+ into the prompt; found the prior thread's marker in: {prompt}"
+ );
+ })
+ .await;
+}
+
+// ─── one-shot semantics ─────────────────────────────────────────────────────
+
+/// The overrides are consumed by exactly ONE turn.
+///
+/// `turn()` takes them with `std::mem::take`, so the turn after a suppressed one
+/// is back to full agentic behaviour without the caller restoring anything. A
+/// suppression that leaked forward would silently strip a real task turn of its
+/// toolbelt.
+#[test]
+fn turn_overrides_apply_to_exactly_one_turn_and_then_reset() {
+ run_on_agent_stack(
+ "turn-overrides-reset",
+ turn_overrides_apply_to_exactly_one_turn_and_then_reset_inner,
+ );
+}
+
+async fn turn_overrides_apply_to_exactly_one_turn_and_then_reset_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+ let (_temp, workspace_path) = workspace("overrides-reset");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+
+ let model = ScriptedModel::new(vec![text("suppressed reply"), text("restored reply")]);
+ let mut agent = agent_with(
+ model.clone(),
+ vec![Box::new(EchoTool)],
+ workspace_path.clone(),
+ Box::new(NativeToolDispatcher),
+ );
+
+ agent.set_next_turn_overrides(TurnOverrides {
+ suppress_tools: true,
+ ..Default::default()
+ });
+ agent.turn("small talk").await.expect("suppressed turn");
+ agent.turn("now do real work").await.expect("restored turn");
+
+ let requests = model.requests();
+ assert_eq!(
+ requests.len(),
+ 2,
+ "expected exactly one provider call per turn, got {}",
+ requests.len()
+ );
+ assert!(
+ requests[0].tool_names.is_empty(),
+ "turn 1 set suppress_tools, so it must carry an empty tool schema; got {:?}",
+ requests[0].tool_names
+ );
+ assert!(
+ requests[1]
+ .tool_names
+ .iter()
+ .any(|name| name == "turn_overrides_echo"),
+ "turn 2 set no overrides, so the toolbelt must be back — the override is one-shot, \
+ not a rebuild; got {:?}",
+ requests[1].tool_names
+ );
+}
+
+// ─── the terminal goal APIs ─────────────────────────────────────────────────
+
+/// The goal API had `pause_for_current_thread` but no terminal counterpart, so a
+/// goal a finished task left behind stayed `Active` and was re-injected on every
+/// later turn. #5844 added both halves: `complete_for_current_thread` settles the
+/// goal (and a settled goal renders no context block), `clear_for_current_thread`
+/// removes the row outright.
+#[test]
+fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns() {
+ run_on_agent_stack(
+ "turn-overrides-goal-terminal-apis",
+ thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner,
+ );
+}
+
+async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+
+ // Separate workspaces, for the same reason as
+ // `suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt`: a second
+ // agent in the same workspace auto-loads the first one's transcript, which
+ // still contains the `[thread goal]` block, so the post-completion
+ // assertion would fail on replayed history rather than on a live goal.
+ let (_control_temp, control_workspace) = workspace("goal-terminal-control");
+ let (_temp, workspace_path) = workspace("goal-terminal-apis");
+
+ const THREAD: &str = "thread-goal-terminal";
+ const OBJECTIVE: &str = "turn-overrides objective a finished task must stop replaying";
+
+ with_thread_id(THREAD, async {
+ // CONTROL — an Active goal reaches a turn.
+ let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
+ goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)
+ .await
+ .expect("seed an active thread goal for the control");
+ let control_model = ScriptedModel::new(vec![text("pre-completion reply")]);
+ let mut control = agent_with(
+ control_model.clone(),
+ Vec::new(),
+ control_workspace.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ control.turn("status?").await.expect("pre-completion turn");
+ assert!(
+ control_model.all_prompt_text().contains(OBJECTIVE),
+ "control: the goal must reach a turn before it is completed, otherwise this \
+ test cannot prove completion changes anything"
+ );
+ drop(control_guard);
+
+ // MEASURED — seed the same goal in a pristine workspace, settle it via
+ // the API under test, then run the only turn that workspace ever sees.
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ goal_store::set(&workspace_path, THREAD, OBJECTIVE, None)
+ .await
+ .expect("seed an active thread goal for the measured agent");
+ let seeded = goal_runtime::load_for_current_thread(&workspace_path)
+ .await
+ .expect("the seeded goal must load before completion");
+ assert_eq!(
+ seeded.objective, OBJECTIVE,
+ "control: the goal must be loadable before completing it"
+ );
+
+ goal_runtime::complete_for_current_thread(&workspace_path).await;
+
+ // A completed goal renders no context block, so a later turn is clean
+ // with no per-turn override set at all.
+ let model = ScriptedModel::new(vec![text("post-completion reply")]);
+ let mut agent = agent_with(
+ model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ agent
+ .turn("something unrelated")
+ .await
+ .expect("post-completion turn");
+ let prompt = model.all_prompt_text();
+ assert!(
+ !prompt.contains(OBJECTIVE),
+ "a goal completed via complete_for_current_thread must stop being injected into \
+ later turns; found it in: {prompt}"
+ );
+
+ goal_runtime::clear_for_current_thread(&workspace_path).await;
+ assert!(
+ goal_runtime::load_for_current_thread(&workspace_path)
+ .await
+ .is_none(),
+ "clear_for_current_thread must remove the goal row outright"
+ );
+
+ // The goal cleared above was already Completed, and a completed goal is
+ // excluded from later prompts anyway — so on its own that only proves a
+ // completed row can be deleted. A `clear` that silently no-opped on an
+ // ACTIVE goal would pass everything above it. Seed a fresh active goal
+ // and clear that one too.
+ const ACTIVE_OBJECTIVE: &str = "turn-overrides-active-goal-to-be-cleared";
+ goal_store::set(&workspace_path, THREAD, ACTIVE_OBJECTIVE, None)
+ .await
+ .expect("seed a second, still-active thread goal");
+ let active = goal_runtime::load_for_current_thread(&workspace_path)
+ .await
+ .expect("the second goal must load while it is still active");
+ assert_eq!(
+ active.objective, ACTIVE_OBJECTIVE,
+ "control: the active goal must be live before clearing it, otherwise clearing it \
+ proves nothing"
+ );
+
+ goal_runtime::clear_for_current_thread(&workspace_path).await;
+ assert!(
+ goal_runtime::load_for_current_thread(&workspace_path)
+ .await
+ .is_none(),
+ "clear_for_current_thread must remove an ACTIVE goal, not only a completed one"
+ );
+
+ // And it must actually stop reaching the prompt — deletion of the row is
+ // the mechanism, absence from the turn is the contract.
+ let post_clear_model = ScriptedModel::new(vec![text("post-clear reply")]);
+ let mut post_clear = agent_with(
+ post_clear_model.clone(),
+ Vec::new(),
+ workspace_path.clone(),
+ Box::new(XmlToolDispatcher),
+ );
+ post_clear
+ .turn("something else entirely")
+ .await
+ .expect("post-clear turn");
+ let post_clear_prompt = post_clear_model.all_prompt_text();
+ assert!(
+ !post_clear_prompt.contains(ACTIVE_OBJECTIVE),
+ "an active goal cleared via clear_for_current_thread must stop being injected \
+ into later turns; found it in: {post_clear_prompt}"
+ );
+ })
+ .await;
+}
diff --git a/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs b/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..30a74039fc
--- /dev/null
+++ b/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs
@@ -0,0 +1,394 @@
+use anyhow::Result;
+use async_trait::async_trait;
+use openhuman_core::openhuman::agent::debug::{
+ dump_agent_prompt, write_prompt_dumps, DumpPromptOptions, DumpedPrompt,
+};
+use openhuman_core::openhuman::agent::harness::archivist::ArchivistHook;
+use openhuman_core::openhuman::agent::harness::{
+ run_subagent, with_parent_context, AgentDefinition, DefinitionSource, ModelSpec,
+ ParentExecutionContext, PromptSource, SandboxMode, SubagentRunError, SubagentRunOptions,
+ ToolScope,
+};
+use openhuman_core::openhuman::agent::hooks::{PostTurnHook, ToolCallRecord, TurnContext};
+use openhuman_core::openhuman::config::AgentConfig;
+use openhuman_core::openhuman::agent::context::prompt::ToolCallFormat;
+use openhuman_core::openhuman::memory::{
+ Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts,
+};
+use openhuman_core::openhuman::memory::api::provider::MemoryProvider;
+// Raw assertion reads against the engine the provider wraps — see the note in
+// `archivist_tests.rs`: production writes through the provider, the proof that
+// a row landed reads the store directly.
+use openhuman_core::openhuman::inference::tokenjuice::AgentTokenjuiceCompression;
+use openhuman_core::openhuman::tools::{PermissionLevel, Tool, ToolResult};
+use parking_lot::Mutex;
+use rusqlite::Connection;
+use serde_json::json;
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+use tempfile::TempDir;
+use tinyinference::message::{AssistantMessage, ContentBlock};
+use tinyinference::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
+use tinyinference::tool::ToolCall;
+use tinyinference::usage::Usage;
+
+struct ScriptedModel {
+ responses: Mutex<VecDeque<anyhow::Result<ModelResponse>>>,
+ requests: Mutex<Vec<String>>,
+}
+
+impl ScriptedModel {
+ fn new(responses: Vec<anyhow::Result<ModelResponse>>) -> Arc<Self> {
+ Arc::new(Self {
+ responses: Mutex::new(VecDeque::from(responses)),
+ requests: Mutex::new(Vec::new()),
+ })
+ }
+
+ fn requests(&self) -> Vec<String> {
+ self.requests.lock().clone()
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ScriptedModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: OnceLock<ModelProfile> = OnceLock::new();
+ Some(PROFILE.get_or_init(|| ModelProfile {
+ provider: Some("round21".to_string()),
+ tool_calling: true,
+ parallel_tool_calls: true,
+ ..ModelProfile::default()
+ }))
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ self.requests.lock().push(
+ request
+ .messages
+ .iter()
+ .map(|message| format!("{message:?}:{}", message.text()))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ );
+ self.responses
+ .lock()
+ .pop_front()
+ .unwrap_or_else(|| Ok(text_response("fallback final")))
+ .map_err(|error| tinyinference::Error::Model(error.to_string()))
+ }
+}
+
+struct StubMemory;
+
+#[async_trait]
+impl Memory for StubMemory {
+ fn name(&self) -> &str {
+ "round21-memory"
+ }
+
+ async fn store(
+ &self,
+ _namespace: &str,
+ _key: &str,
+ _content: &str,
+ _category: MemoryCategory,
+ _session_id: Option<&str>,
+ ) -> Result<()> {
+ Ok(())
+ }
+
+ async fn recall(
+ &self,
+ _query: &str,
+ _limit: usize,
+ _opts: RecallOpts<'_>,
+ ) -> Result<Vec<MemoryEntry>> {
+ Ok(Vec::new())
+ }
+
+ async fn get(&self, _namespace: &str, _key: &str) -> Result<Option<MemoryEntry>> {
+ Ok(None)
+ }
+
+ async fn list(
+ &self,
+ _namespace: Option<&str>,
+ _category: Option<&MemoryCategory>,
+ _session_id: Option<&str>,
+ ) -> Result<Vec<MemoryEntry>> {
+ Ok(Vec::new())
+ }
+
+ async fn forget(&self, _namespace: &str, _key: &str) -> Result<bool> {
+ Ok(false)
+ }
+
+ async fn namespace_summaries(&self) -> Result<Vec<NamespaceSummary>> {
+ Ok(Vec::new())
+ }
+
+ async fn count(&self) -> Result<usize> {
+ Ok(0)
+ }
+
+ async fn health_check(&self) -> bool {
+ true
+ }
+}
+
+struct EchoTool;
+
+#[async_trait]
+impl Tool for EchoTool {
+ fn name(&self) -> &str {
+ "echo"
+ }
+
+ fn description(&self) -> &str {
+ "Deterministic round21 echo"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "message": { "type": "string" }
+ }
+ })
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> Result<ToolResult> {
+ Ok(ToolResult::success(format!("echo:{args}")))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::None
+ }
+}
+
+fn turn(session_id: &str, user_message: &str, assistant_response: &str) -> TurnContext {
+ TurnContext {
+ user_message: user_message.to_string(),
+ assistant_response: assistant_response.to_string(),
+ tool_calls: Vec::new(),
+ turn_duration_ms: 25,
+ session_id: Some(session_id.to_string()),
+ agent_id: Some("round21_agent".to_string()),
+ entrypoint: Some("raw-e2e".to_string()),
+ iteration_count: 1,
+ }
+}
+
+fn text_response(text: &str) -> ModelResponse {
+ let mut usage = Usage::new(13, 5);
+ usage.cache_read_tokens = 2;
+ ModelResponse::assistant(text).with_usage(usage)
+}
+
+fn tool_response(name: &str, arguments: serde_json::Value) -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: vec![
+ ContentBlock::Text("calling echo".to_string()),
+ ContentBlock::thinking("scripted tool use"),
+ ],
+ tool_calls: vec![ToolCall::new("round21-call", name, arguments)],
+ usage: None,
+ },
+ usage: None,
+ finish_reason: Some("tool_calls".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+fn definition(max_iterations: usize) -> AgentDefinition {
+ AgentDefinition {
+ id: "round21_worker".to_string(),
+ when_to_use: "round21 raw coverage".to_string(),
+ display_name: Some("Round 21 Worker".to_string()),
+ system_prompt: PromptSource::Inline("Round21 worker prompt".to_string()),
+ omit_identity: true,
+ omit_memory_context: false,
+ omit_safety_preamble: true,
+ omit_profile: true,
+ omit_memory_md: true,
+ trigger_memory_agent: Default::default(),
+ model: ModelSpec::Inherit,
+ temperature: 0.0,
+ tools: ToolScope::Named(vec!["echo".to_string()]),
+ disallowed_tools: Vec::new(),
+ skill_filter: None,
+ extra_tools: Vec::new(),
+ max_iterations,
+ iteration_policy: Default::default(),
+ max_result_chars: None,
+ max_turn_output_tokens: None,
+ timeout_secs: None,
+ sandbox_mode: SandboxMode::None,
+ background: false,
+ tokenjuice_compression: AgentTokenjuiceCompression::Auto,
+ subagents: Vec::new(),
+ delegate_name: None,
+ agent_tier: Default::default(),
+ source: DefinitionSource::Builtin,
+ graph: Default::default(),
+ }
+}
+
+fn parent_context(workspace: &Path, model: Arc<ScriptedModel>) -> ParentExecutionContext {
+ let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];
+ let specs = tools.iter().map(|tool| tool.spec()).collect();
+ ParentExecutionContext {
+ agent_definition_id: "orchestrator".into(),
+ allowed_subagent_ids: [
+ "test".to_string(),
+ "archivist".to_string(),
+ "summarizer".to_string(),
+ ]
+ .into_iter()
+ .collect(),
+ turn_model_source: openhuman_core::openhuman::agent::tinyagents::TurnModelSource::from_model(
+ model,
+ ),
+ all_tools: Arc::new(tools),
+ all_tool_specs: Arc::new(specs),
+ visible_tool_names: std::collections::HashSet::new(),
+ subagent_tool_ceiling_names: std::collections::HashSet::new(),
+ model_name: "round21-parent-model".to_string(),
+ temperature: 0.0,
+ workspace_dir: workspace.to_path_buf(),
+ workspace_descriptor: None,
+ memory: Arc::new(StubMemory),
+ agent_config: AgentConfig::default(),
+ workflows: Arc::new(Vec::new()),
+ memory_context: Arc::new(Some("parent memory".to_string())),
+ session_id: "round21-parent-session".to_string(),
+ channel: "round21-channel".to_string(),
+ connected_integrations: Vec::new(),
+ tool_call_format: ToolCallFormat::Native,
+ session_key: "1700000000_round21_parent".to_string(),
+ session_parent_prefix: None,
+ on_progress: None,
+ run_queue: None,
+ }
+}
+
+#[tokio::test]
+async fn subagent_no_parent_and_checkpoint_fallback_are_deterministic() -> Result<()> {
+ let no_parent = run_subagent(
+ &definition(1),
+ "outside a parent context",
+ SubagentRunOptions::default(),
+ )
+ .await
+ .expect_err("run without parent should fail");
+ assert!(matches!(no_parent, SubagentRunError::NoParentContext));
+
+ let tmp = TempDir::new()?;
+ let provider = ScriptedModel::new(vec![
+ Ok(tool_response("echo", json!({"message": "first"}))),
+ Err(anyhow::anyhow!("checkpoint model unavailable")),
+ ]);
+ let parent = parent_context(tmp.path(), provider.clone());
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(
+ &definition(1),
+ "use the echo tool once",
+ SubagentRunOptions {
+ task_id: Some("round21-task".to_string()),
+ ..SubagentRunOptions::default()
+ },
+ )
+ .await
+ })
+ .await?;
+
+ assert_eq!(outcome.iterations, 1);
+ assert!(outcome.output.contains("tool-call limit (1 steps)"));
+ assert!(outcome
+ .output
+ .contains("echo [ok]: echo:{\"message\":\"first\"}"));
+ assert!(provider
+ .requests()
+ .iter()
+ .any(|request| request.contains("reached your tool-call limit")));
+ Ok(())
+}
+
+#[tokio::test]
+async fn debug_prompt_dump_requires_toolkit_before_composio_network() -> Result<()> {
+ let tmp = TempDir::new()?;
+ let err = dump_agent_prompt(DumpPromptOptions {
+ agent_id: "integrations_agent".to_string(),
+ toolkit: None,
+ workspace_dir_override: Some(tmp.path().to_path_buf()),
+ model_override: Some("round21-debug-model".to_string()),
+ })
+ .await
+ .expect_err("integrations_agent without toolkit should fail locally");
+
+ assert!(err.to_string().contains("requires a `toolkit` argument"));
+ let opts = DumpPromptOptions::new("orchestrator");
+ assert_eq!(opts.agent_id, "orchestrator");
+ assert!(opts.toolkit.is_none());
+ Ok(())
+}
+
+#[test]
+fn debug_dump_writer_sanitizes_names_and_writes_summary_sidecars() -> Result<()> {
+ let tmp = TempDir::new()?;
+ let dumps = vec![DumpedPrompt {
+ agent_id: "agent/with spaces".to_string(),
+ toolkit: Some("gmail:primary".to_string()),
+ mode: "session",
+ model: "round21-model".to_string(),
+ workspace_dir: PathBuf::from("/tmp/round21-workspace"),
+ text: "SYSTEM PROMPT\n".to_string(),
+ tool_names: vec!["echo".to_string(), "search".to_string()],
+ tool_specs: vec![
+ json!({"name": "echo", "description": "echo back", "parameters": {}}),
+ json!({"name": "search", "description": "search docs", "parameters": {}}),
+ ],
+ skill_tool_count: 1,
+ }];
+
+ let summary = write_prompt_dumps(tmp.path(), &dumps)?;
+ assert_eq!(
+ summary.prompt_paths[0],
+ tmp.path().join("1_agent_with_spaces_gmail_primary.md")
+ );
+ assert_eq!(
+ std::fs::read_to_string(&summary.prompt_paths[0])?,
+ "SYSTEM PROMPT\n"
+ );
+ let meta = std::fs::read_to_string(
+ tmp.path()
+ .join("1_agent_with_spaces_gmail_primary.meta.txt"),
+ )?;
+ assert!(meta.contains("agent: agent/with spaces"));
+ assert!(meta.contains("toolkit: gmail:primary"));
+ let summary_text = std::fs::read_to_string(summary.summary_path)?;
+ assert!(summary_text.contains("agent/with spaces@gmail:primary"));
+ assert!(summary_text.contains("tools=2"));
+ // The per-dump tools sidecar carries the rendered tool schemas verbatim,
+ // one entry per tool in `tool_names` order.
+ let tools_json = std::fs::read_to_string(
+ tmp.path().join("1_agent_with_spaces_gmail_primary.tools.json"),
+ )?;
+ let specs: Vec<serde_json::Value> = serde_json::from_str(&tools_json)?;
+ assert_eq!(specs.len(), 2);
+ assert_eq!(specs[0]["name"], "echo");
+ assert_eq!(specs[1]["name"], "search");
+ Ok(())
+}
diff --git a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..f6b0328e62
--- /dev/null
+++ b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
@@ -0,0 +1,1249 @@
+#[path = "../support/noop_memory.rs"]
+mod noop_memory;
+
+use async_trait::async_trait;
+use openhuman_core::openhuman::agent::dispatcher::{NativeToolDispatcher, XmlToolDispatcher};
+use openhuman_core::openhuman::agent::harness::definition::AgentTier;
+use openhuman_core::openhuman::agent::harness::subagent_runner::run_subagent;
+use openhuman_core::openhuman::agent::harness::{
+ with_parent_context, AgentDefinition, DefinitionSource, ModelSpec, ParentExecutionContext,
+ PromptSource, SandboxMode, SubagentRunError, SubagentRunOptions, ToolScope,
+};
+use openhuman_core::openhuman::agent::hooks::{PostTurnHook, TurnContext};
+use openhuman_core::openhuman::agent::progress::AgentProgress;
+use openhuman_core::openhuman::agent::tool_policy::{
+ ToolPolicy, ToolPolicyDecision, ToolPolicyRequest,
+};
+use openhuman_core::openhuman::agent::Agent;
+use openhuman_core::openhuman::config::{AgentConfig, Config, ContextConfig, MemoryConfig};
+use openhuman_core::openhuman::agent::messages::ConversationMessage;
+use openhuman_core::openhuman::memory::{
+ Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts,
+};
+use openhuman_core::openhuman::inference::tokenjuice::AgentTokenjuiceCompression;
+use openhuman_core::openhuman::tools::traits::ToolCallOptions;
+use openhuman_core::openhuman::tools::{
+ PermissionLevel, Tool, ToolContent, ToolResult, ToolScope as RuntimeToolScope,
+};
+use serde_json::json;
+use std::collections::{HashMap, HashSet, VecDeque};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use tempfile::TempDir;
+use tinyinference::message::{AssistantMessage, ContentBlock, Message, MessageDelta};
+use tinyinference::model::{
+ ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+};
+use tinyinference::tool::{ToolCall, ToolDelta};
+use tinyinference::usage::Usage;
+use tokio::sync::{Mutex as AsyncMutex, Notify};
+use tokio::time::{timeout, Duration};
+
+struct EnvGuard {
+ key: &'static str,
+ previous: Option<std::ffi::OsString>,
+}
+
+impl EnvGuard {
+ fn set_path(key: &'static str, value: &std::path::Path) -> Self {
+ let previous = std::env::var_os(key);
+ unsafe { std::env::set_var(key, value) };
+ Self { key, previous }
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ match self.previous.take() {
+ Some(value) => unsafe { std::env::set_var(self.key, value) },
+ None => unsafe { std::env::remove_var(self.key) },
+ }
+ }
+}
+
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ static LOCK: &std::sync::OnceLock<std::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;
+ LOCK.get_or_init(|| std::sync::Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+}
+
+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
+
+fn ensure_memory_seams() {
+ MEMORY_SEAMS_INIT.get_or_init(|| {
+ std::thread::Builder::new()
+ .name("agent-session-turn-raw-coverage-seams".to_string())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(|| {
+ })
+ .expect("spawn agent session turn raw coverage seam installer")
+ .join()
+ .expect("agent session turn raw coverage seam installer panicked");
+ });
+}
+
+fn run_on_agent_stack<F, Fut>(name: &str, future_factory: F)
+where
+ F: FnOnce() -> Fut + Send + 'static,
+ Fut: std::future::Future<Output = ()> + 'static,
+{
+ std::thread::Builder::new()
+ .name(name.to_string())
+ .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(move || {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .enable_all()
+ .build()
+ .expect("build agent session turn raw coverage runtime")
+ .block_on(future_factory());
+ })
+ .expect("spawn agent session turn raw coverage thread")
+ .join()
+ .expect("agent session turn raw coverage thread should not panic");
+}
+
+#[derive(Clone, Debug)]
+struct CapturedRequest {
+ model: String,
+ temperature: f64,
+ messages: Vec<Message>,
+ tool_names: Vec<String>,
+ stream_was_requested: bool,
+}
+
+struct ScriptedModel {
+ responses: Mutex<VecDeque<anyhow::Result<ModelResponse>>>,
+ requests: Mutex<Vec<CapturedRequest>>,
+ stream_events: Vec<ModelStreamItem>,
+ profile: ModelProfile,
+ /// When set, every `chat` call fails with this message — models a provider
+ /// that is down for the whole turn, so no fallback route can recover it.
+ always_fail: Option<&'static str>,
+}
+
+impl Default for ScriptedModel {
+ fn default() -> Self {
+ Self {
+ responses: Mutex::new(VecDeque::new()),
+ requests: Mutex::new(Vec::new()),
+ stream_events: Vec::new(),
+ profile: ModelProfile::default(),
+ always_fail: None,
+ }
+ }
+}
+
+impl ScriptedModel {
+ fn new(responses: Vec<ModelResponse>) -> Arc<Self> {
+ Arc::new(Self {
+ responses: Mutex::new(responses.into_iter().map(Ok).collect()),
+ ..Self::default()
+ })
+ }
+
+ fn failing(message: &'static str) -> Arc<Self> {
+ Arc::new(Self {
+ always_fail: Some(message),
+ ..Self::default()
+ })
+ }
+
+ fn requests(&self) -> Vec<CapturedRequest> {
+ self.requests.lock().unwrap().clone()
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ScriptedModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(&self.profile)
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ self.capture(&request, false);
+ self.pop_response()
+ }
+
+ async fn stream(&self, _state: &(), request: ModelRequest) -> tinyinference::Result<ModelStream> {
+ self.capture(&request, true);
+ let response = self.pop_response()?;
+ let mut items = vec![ModelStreamItem::Started];
+ items.extend(self.stream_events.iter().cloned());
+ items.push(ModelStreamItem::Completed(response));
+ Ok(Box::pin(futures::stream::iter(items)))
+ }
+}
+
+impl ScriptedModel {
+ fn capture(&self, request: &ModelRequest, streamed: bool) {
+ self.requests.lock().unwrap().push(CapturedRequest {
+ model: request.model.clone().unwrap_or_default(),
+ temperature: request.temperature.unwrap_or_default(),
+ messages: request.messages.clone(),
+ tool_names: request.tools.iter().map(|tool| tool.name.clone()).collect(),
+ stream_was_requested: streamed,
+ });
+ }
+
+ fn pop_response(&self) -> tinyinference::Result<ModelResponse> {
+ if let Some(message) = self.always_fail {
+ return Err(tinyinference::Error::Model(message.to_string()));
+ }
+ self.responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| Ok(text_response("default scripted final")))
+ .map_err(|error| tinyinference::Error::Model(error.to_string()))
+ }
+}
+
+struct StaticMemory {
+ entries: Mutex<Vec<MemoryEntry>>,
+ entries_by_query: HashMap<String, Vec<MemoryEntry>>,
+ fail_recall: bool,
+ blocked_query: Option<String>,
+ recall_started: Option<Arc<Notify>>,
+ release_recall: Option<Arc<Notify>>,
+ recall_cancelled: Option<Arc<AtomicBool>>,
+}
+
+struct RecallCancellationGuard {
+ cancelled: Arc<AtomicBool>,
+ armed: bool,
+}
+
+impl Drop for RecallCancellationGuard {
+ fn drop(&mut self) {
+ if self.armed {
+ self.cancelled.store(true, Ordering::SeqCst);
+ }
+ }
+}
+
+impl Default for StaticMemory {
+ fn default() -> Self {
+ Self {
+ entries: Mutex::new(Vec::new()),
+ entries_by_query: HashMap::new(),
+ fail_recall: false,
+ blocked_query: None,
+ recall_started: None,
+ release_recall: None,
+ recall_cancelled: None,
+ }
+ }
+}
+
+#[async_trait]
+impl Memory for StaticMemory {
+ fn name(&self) -> &str {
+ "round17-memory"
+ }
+
+ async fn store(
+ &self,
+ namespace: &str,
+ key: &str,
+ content: &str,
+ category: MemoryCategory,
+ session_id: Option<&str>,
+ ) -> anyhow::Result<()> {
+ let mut entries = self.entries.lock().unwrap();
+ let id = format!("{namespace}:{key}:{}", entries.len());
+ entries.push(MemoryEntry {
+ id,
+ key: key.to_string(),
+ content: content.to_string(),
+ namespace: Some(namespace.to_string()),
+ category,
+ timestamp: "2026-05-29T00:00:00Z".to_string(),
+ session_id: session_id.map(str::to_string),
+ score: Some(0.95),
+ taint: Default::default(),
+ });
+ Ok(())
+ }
+
+ async fn recall(
+ &self,
+ query: &str,
+ limit: usize,
+ _opts: RecallOpts<'_>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ if self.fail_recall {
+ anyhow::bail!("forced recall failure for {query}");
+ }
+ if self.blocked_query.as_deref() == Some(query) {
+ if let Some(started) = &self.recall_started {
+ started.notify_one();
+ }
+ let mut cancellation_guard = self.recall_cancelled.as_ref().map(|cancelled| {
+ RecallCancellationGuard {
+ cancelled: cancelled.clone(),
+ armed: true,
+ }
+ });
+ if let Some(release) = &self.release_recall {
+ release.notified().await;
+ }
+ if let Some(guard) = &mut cancellation_guard {
+ guard.armed = false;
+ }
+ }
+ if let Some(entries) = self.entries_by_query.get(query) {
+ return Ok(entries.iter().take(limit).cloned().collect());
+ }
+ Ok(self
+ .entries
+ .lock()
+ .unwrap()
+ .iter()
+ .take(limit)
+ .cloned()
+ .collect())
+ }
+
+ async fn get(&self, namespace: &str, key: &str) -> anyhow::Result<Option<MemoryEntry>> {
+ Ok(self
+ .entries
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|entry| entry.namespace.as_deref() == Some(namespace) && entry.key == key)
+ .cloned())
+ }
+
+ async fn list(
+ &self,
+ namespace: Option<&str>,
+ category: Option<&MemoryCategory>,
+ session_id: Option<&str>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ Ok(self
+ .entries
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|entry| namespace.is_none_or(|ns| entry.namespace.as_deref() == Some(ns)))
+ .filter(|entry| category.is_none_or(|cat| &entry.category == cat))
+ .filter(|entry| session_id.is_none_or(|sid| entry.session_id.as_deref() == Some(sid)))
+ .cloned()
+ .collect())
+ }
+
+ async fn forget(&self, namespace: &str, key: &str) -> anyhow::Result<bool> {
+ let mut entries = self.entries.lock().unwrap();
+ let before = entries.len();
+ entries.retain(|entry| entry.namespace.as_deref() != Some(namespace) || entry.key != key);
+ Ok(entries.len() != before)
+ }
+
+ async fn namespace_summaries(&self) -> anyhow::Result<Vec<NamespaceSummary>> {
+ Ok(vec![NamespaceSummary {
+ namespace: "round17".to_string(),
+ count: self.entries.lock().unwrap().len(),
+ last_updated: Some("2026-05-29T00:00:00Z".to_string()),
+ }])
+ }
+
+ async fn count(&self) -> anyhow::Result<usize> {
+ Ok(self.entries.lock().unwrap().len())
+ }
+
+ async fn health_check(&self) -> bool {
+ true
+ }
+}
+
+struct RecordingHook {
+ calls: Arc<AsyncMutex<Vec<TurnContext>>>,
+ notify: Arc<Notify>,
+ fail: bool,
+}
+
+#[async_trait]
+impl PostTurnHook for RecordingHook {
+ fn name(&self) -> &str {
+ "round17-recording"
+ }
+
+ async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {
+ self.calls.lock().await.push(ctx.clone());
+ self.notify.notify_waiters();
+ if self.fail {
+ anyhow::bail!("hook failure is non-blocking");
+ }
+ Ok(())
+ }
+}
+
+struct Round17Tool {
+ name: &'static str,
+ output: &'static str,
+ calls: Arc<AtomicUsize>,
+ error_result: bool,
+ execution_error: bool,
+ permission: PermissionLevel,
+ scope: RuntimeToolScope,
+}
+
+impl Round17Tool {
+ fn boxed(name: &'static str, output: &'static str, calls: Arc<AtomicUsize>) -> Box<dyn Tool> {
+ Box::new(Self {
+ name,
+ output,
+ calls,
+ error_result: false,
+ execution_error: false,
+ permission: PermissionLevel::ReadOnly,
+ scope: RuntimeToolScope::All,
+ })
+ }
+
+ fn write(name: &'static str, calls: Arc<AtomicUsize>) -> Box<dyn Tool> {
+ Box::new(Self {
+ name,
+ output: "write-output",
+ calls,
+ error_result: false,
+ execution_error: false,
+ permission: PermissionLevel::Write,
+ scope: RuntimeToolScope::All,
+ })
+ }
+
+ fn failing_execute(name: &'static str, calls: Arc<AtomicUsize>) -> Box<dyn Tool> {
+ Box::new(Self {
+ name,
+ output: "not used",
+ calls,
+ error_result: false,
+ execution_error: true,
+ permission: PermissionLevel::ReadOnly,
+ scope: RuntimeToolScope::All,
+ })
+ }
+
+ fn tool_error(name: &'static str, calls: Arc<AtomicUsize>) -> Box<dyn Tool> {
+ Box::new(Self {
+ name,
+ output: "semantic failure",
+ calls,
+ error_result: true,
+ execution_error: false,
+ permission: PermissionLevel::ReadOnly,
+ scope: RuntimeToolScope::All,
+ })
+ }
+
+ fn cli_only(name: &'static str, calls: Arc<AtomicUsize>) -> Box<dyn Tool> {
+ Box::new(Self {
+ name,
+ output: "cli-only",
+ calls,
+ error_result: false,
+ execution_error: false,
+ permission: PermissionLevel::ReadOnly,
+ scope: RuntimeToolScope::CliRpcOnly,
+ })
+ }
+}
+
+#[async_trait]
+impl Tool for Round17Tool {
+ fn name(&self) -> &str {
+ self.name
+ }
+
+ fn description(&self) -> &str {
+ "round17 deterministic tool"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "value": { "type": "string" }
+ }
+ })
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.execute_with_options(args, ToolCallOptions::default())
+ .await
+ }
+
+ async fn execute_with_options(
+ &self,
+ args: serde_json::Value,
+ options: ToolCallOptions,
+ ) -> anyhow::Result<ToolResult> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if self.execution_error {
+ anyhow::bail!("execution exploded");
+ }
+ let suffix = args
+ .get("value")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or_default();
+ let text = if suffix.is_empty() {
+ self.output.to_string()
+ } else {
+ format!("{}:{suffix}", self.output)
+ };
+ Ok(ToolResult {
+ content: vec![ToolContent::Text { text: text.clone() }],
+ is_error: self.error_result,
+ markdown_formatted: options.prefer_markdown.then(|| format!("**{text}**")),
+ })
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ self.permission
+ }
+
+ fn scope(&self) -> RuntimeToolScope {
+ self.scope
+ }
+}
+
+struct DenyNamedPolicy(&'static str);
+
+#[async_trait]
+impl ToolPolicy for DenyNamedPolicy {
+ fn name(&self) -> &str {
+ "round17-deny"
+ }
+
+ async fn check(&self, request: &ToolPolicyRequest) -> ToolPolicyDecision {
+ if request.tool_name == self.0 {
+ ToolPolicyDecision::deny("round17 policy says no")
+ } else {
+ ToolPolicyDecision::Allow
+ }
+ }
+}
+
+fn usage(input_tokens: u64, output_tokens: u64, cached_input_tokens: u64) -> Usage {
+ let mut usage = Usage::new(input_tokens, output_tokens);
+ usage.cache_read_tokens = cached_input_tokens;
+ usage
+}
+
+fn text_response(text: &str) -> ModelResponse {
+ ModelResponse::assistant(text).with_usage(usage(17, 9, 4))
+}
+
+fn reasoning_text_response(text: &str, reasoning: &str, usage: Usage) -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: vec![
+ ContentBlock::Text(text.to_string()),
+ ContentBlock::thinking(reasoning),
+ ],
+ tool_calls: Vec::new(),
+ usage: Some(usage),
+ },
+ usage: Some(usage),
+ finish_reason: Some("stop".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+fn tool_response(id: &str, name: &str, args: serde_json::Value) -> ModelResponse {
+ let usage = usage(21, 6, 5);
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: vec![
+ ContentBlock::Text("native preamble".to_string()),
+ ContentBlock::thinking("native reasoning"),
+ ],
+ tool_calls: vec![ToolCall::new(id, name, args)],
+ usage: Some(usage),
+ },
+ usage: Some(usage),
+ finish_reason: Some("tool_calls".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+fn prompt_tool_response(name: &str, args: serde_json::Value) -> ModelResponse {
+ tool_response(&format!("round17-{name}"), name, args)
+}
+
+fn native_profile() -> ModelProfile {
+ ModelProfile {
+ provider: Some("round17".to_string()),
+ tool_calling: true,
+ parallel_tool_calls: true,
+ streaming: true,
+ streaming_tool_chunks: true,
+ ..ModelProfile::default()
+ }
+}
+
+fn workspace(label: &str) -> (TempDir, PathBuf) {
+ let root = std::env::current_dir()
+ .unwrap()
+ .join("target")
+ .join(format!(
+ "agent-session-turn-round17-{label}-{}",
+ uuid::Uuid::new_v4()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let temp = TempDir::new_in(root.parent().unwrap()).unwrap();
+ let path = temp.path().join(label);
+ std::fs::create_dir_all(&path).unwrap();
+ (temp, path)
+}
+
+fn agent_with(
+ model: Arc<dyn ChatModel<()>>,
+ tools: Vec<Box<dyn Tool>>,
+ workspace_path: PathBuf,
+ dispatcher: Box<dyn openhuman_core::openhuman::agent::dispatcher::ToolDispatcher>,
+ config: AgentConfig,
+ context_config: ContextConfig,
+) -> Agent {
+ Agent::builder()
+ .chat_model(model)
+ .tools(tools)
+ .memory(noop_memory::noop_memory())
+ .tool_dispatcher(dispatcher)
+ .workspace_dir(workspace_path)
+ .event_context("round17-session", "round17-channel")
+ .agent_definition_name("round17/orchestrator")
+ .config(config)
+ .context_config(context_config)
+ .auto_save(true)
+ .explicit_preferences_enabled(false)
+ .build()
+ .unwrap()
+}
+
+#[test]
+fn turn_native_tool_progress_reasoning_usage_and_resume_seed_paths() {
+ run_on_agent_stack(
+ "agent-session-turn-native-tool-raw-coverage",
+ turn_native_tool_progress_reasoning_usage_and_resume_seed_paths_inner,
+ );
+}
+
+async fn turn_native_tool_progress_reasoning_usage_and_resume_seed_paths_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+ let (_temp, workspace_path) = workspace("native-progress");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let calls = Arc::new(AtomicUsize::new(0));
+ let provider = Arc::new(ScriptedModel {
+ responses: Mutex::new(
+ vec![
+ Ok(tool_response(
+ "native-1",
+ "round17_echo",
+ json!({ "value": "alpha" }),
+ )),
+ Ok(reasoning_text_response(
+ "native final",
+ "final hidden reasoning",
+ usage(5, 3, 2),
+ )),
+ ]
+ .into(),
+ ),
+ requests: Mutex::new(Vec::new()),
+ stream_events: vec![
+ ModelStreamItem::MessageDelta(MessageDelta::text("stream text")),
+ ModelStreamItem::MessageDelta(MessageDelta::reasoning("stream thought")),
+ ModelStreamItem::ToolCallDelta(ToolDelta {
+ call_id: "native-1".to_string(),
+ tool_name: Some("round17_echo".to_string()),
+ content: String::new(),
+ }),
+ ModelStreamItem::ToolCallDelta(ToolDelta {
+ call_id: "native-1".to_string(),
+ tool_name: None,
+ content: "{\"value\":\"alpha\"}".to_string(),
+ }),
+ ],
+ profile: native_profile(),
+ always_fail: None,
+ });
+ let mut agent = agent_with(
+ provider.clone(),
+ vec![Round17Tool::boxed(
+ "round17_echo",
+ "echo-output",
+ calls.clone(),
+ )],
+ workspace_path,
+ Box::new(NativeToolDispatcher),
+ AgentConfig {
+ max_tool_iterations: 4,
+ max_history_messages: 12,
+ ..AgentConfig::default()
+ },
+ ContextConfig {
+ prefer_markdown_tool_output: true,
+ ..ContextConfig::default()
+ },
+ );
+ let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(64);
+ agent.set_on_progress(Some(progress_tx));
+
+ let answer = agent.turn("use the native tool").await.unwrap();
+ assert_eq!(answer, "native final");
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert!(agent.history().iter().any(|message| matches!(
+ message,
+ ConversationMessage::AssistantToolCalls {
+ tool_calls,
+ reasoning_content,
+ ..
+ } if tool_calls[0].id == "native-1" && reasoning_content.as_deref() == Some("native reasoning")
+ )));
+ assert!(agent.history().iter().any(|message| matches!(
+ message,
+ ConversationMessage::Chat(chat)
+ if chat.role == "assistant"
+ && chat.extra_metadata.as_ref()
+ .and_then(|m| m.get("reasoning_content"))
+ .and_then(|v| v.as_str()) == Some("final hidden reasoning")
+ )));
+
+ let mut progress = Vec::new();
+ while let Ok(event) = progress_rx.try_recv() {
+ progress.push(event);
+ }
+ assert!(progress
+ .iter()
+ .any(|event| matches!(event, AgentProgress::TurnStarted)));
+ assert!(progress.iter().any(|event| matches!(
+ event,
+ AgentProgress::TextDelta { delta, iteration: 1 } if delta == "stream text"
+ )));
+ assert!(progress.iter().any(|event| matches!(
+ event,
+ AgentProgress::ThinkingDelta { delta, iteration: 1 } if delta == "stream thought"
+ )));
+ assert!(progress.iter().any(|event| matches!(
+ event,
+ AgentProgress::ToolCallCompleted { tool_name, success, .. }
+ if tool_name == "round17_echo" && *success
+ )));
+
+ let requests = provider.requests();
+ assert!(requests[0].stream_was_requested);
+ assert_eq!(requests[0].tool_names, vec!["round17_echo"]);
+ assert!(requests[1]
+ .messages
+ .iter()
+ .any(|message| matches!(message, Message::Tool(_))
+ && message.text().contains("**echo-output:alpha**")));
+
+ let (_seeded_tmp, seeded_workspace) = workspace("seeded-resume");
+ let mut seeded = agent_with(
+ ScriptedModel::new(vec![text_response("seeded final")]),
+ vec![Round17Tool::boxed(
+ "round17_echo",
+ "unused",
+ Arc::new(AtomicUsize::new(0)),
+ )],
+ seeded_workspace,
+ Box::new(XmlToolDispatcher),
+ AgentConfig {
+ max_history_messages: 3,
+ ..AgentConfig::default()
+ },
+ ContextConfig::default(),
+ );
+ seeded
+ .seed_resume_from_messages(
+ vec![
+ ("user".to_string(), "old one".to_string()),
+ ("assistant".to_string(), "old two".to_string()),
+ ("user".to_string(), "current".to_string()),
+ ],
+ "current",
+ )
+ .unwrap();
+ let seeded_answer = seeded.run_single("current").await.unwrap();
+ assert_eq!(seeded_answer, "seeded final");
+}
+
+#[test]
+fn turn_citation_task_replaces_previous_handle_and_joins_successfully() {
+ run_on_agent_stack(
+ "agent-session-turn-citation-task-raw-coverage",
+ turn_citation_task_replaces_previous_handle_and_joins_successfully_inner,
+ );
+}
+
+async fn turn_citation_task_replaces_previous_handle_and_joins_successfully_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+ let (_temp, workspace_path) = workspace("citation-task");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let citation = |id: &str| MemoryEntry {
+ id: id.to_string(),
+ key: "project.summary".to_string(),
+ content: "The launch checklist is ready.".to_string(),
+ namespace: Some("projects".to_string()),
+ category: MemoryCategory::Conversation,
+ timestamp: "2026-05-29T00:00:00Z".to_string(),
+ session_id: None,
+ score: Some(0.9),
+ taint: Default::default(),
+ };
+ let first_started = Arc::new(Notify::new());
+ let never_release_first = Arc::new(Notify::new());
+ let first_cancelled = Arc::new(AtomicBool::new(false));
+ let memory = Arc::new(StaticMemory {
+ entries: Mutex::new(Vec::new()),
+ entries_by_query: HashMap::from([
+ (
+ "first citation query".to_string(),
+ vec![citation("citation-first")],
+ ),
+ (
+ "second citation query".to_string(),
+ vec![citation("citation-second")],
+ ),
+ ]),
+ fail_recall: false,
+ blocked_query: Some("first citation query".to_string()),
+ recall_started: Some(first_started.clone()),
+ release_recall: Some(never_release_first),
+ recall_cancelled: Some(first_cancelled.clone()),
+ });
+ let mut agent = Agent::builder()
+ .chat_model(ScriptedModel::new(vec![
+ text_response("first answer"),
+ text_response("second answer"),
+ ]))
+ .tools(Vec::new())
+ .memory(memory)
+ .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .workspace_dir(workspace_path)
+ .event_context("round17-session", "round17-channel")
+ .agent_definition_name("round17/orchestrator")
+ .config(AgentConfig::default())
+ .context_config(ContextConfig::default())
+ .auto_save(false)
+ .explicit_preferences_enabled(false)
+ .build()
+ .unwrap();
+
+ assert_eq!(agent.turn("first citation query").await.unwrap(), "first answer");
+ timeout(Duration::from_secs(1), first_started.notified())
+ .await
+ .expect("first citation recall should be in flight");
+ // Starting a second turn must abort the blocked first task before installing
+ // the query-specific citation task joined below.
+ let second_answer = timeout(
+ Duration::from_secs(1),
+ agent.turn("second citation query"),
+ )
+ .await
+ .expect("replacement turn must not wait for the blocked first recall")
+ .unwrap();
+ assert_eq!(second_answer, "second answer");
+ timeout(Duration::from_secs(1), async {
+ while !first_cancelled.load(Ordering::SeqCst) {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the first citation recall future should be cancelled");
+ let citations = agent.take_last_turn_citations().await;
+ assert_eq!(citations.len(), 1);
+ assert_eq!(citations[0].id, "citation-second");
+}
+
+#[test]
+fn turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_exercised() {
+ run_on_agent_stack(
+ "agent-session-turn-xml-raw-coverage",
+ turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_exercised_inner,
+ );
+}
+
+async fn turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_exercised_inner() {
+ ensure_memory_seams();
+ let _env = env_lock();
+ let (_temp, workspace_path) = workspace("xml-failures");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let ok_calls = Arc::new(AtomicUsize::new(0));
+ let err_calls = Arc::new(AtomicUsize::new(0));
+ let boom_calls = Arc::new(AtomicUsize::new(0));
+ let write_calls = Arc::new(AtomicUsize::new(0));
+ let provider = Arc::new(ScriptedModel {
+ responses: Mutex::new(
+ vec![
+ Ok(prompt_tool_response("hidden_tool", json!({ "value": "h" }))),
+ Ok(prompt_tool_response("cli_only", json!({ "value": "c" }))),
+ Ok(prompt_tool_response(
+ "round17_error",
+ json!({ "value": "e" }),
+ )),
+ Ok(prompt_tool_response(
+ "round17_boom",
+ json!({ "value": "b" }),
+ )),
+ Ok(prompt_tool_response(
+ "round17_write",
+ json!({ "value": "w" }),
+ )),
+ Ok(prompt_tool_response("round17_ok", json!({ "value": "o" }))),
+ Ok(ModelResponse::assistant("")),
+ ]
+ .into(),
+ ),
+ requests: Mutex::new(Vec::new()),
+ ..ScriptedModel::default()
+ });
+ let hook_calls = Arc::new(AsyncMutex::new(Vec::<TurnContext>::new()));
+ let hook_notify = Arc::new(Notify::new());
+ let mut channel_permissions = std::collections::HashMap::new();
+ channel_permissions.insert("round17-channel".to_string(), "read_only".to_string());
+ let mut agent = Agent::builder()
+ .chat_model(provider.clone())
+ .tools(vec![
+ Round17Tool::boxed("round17_ok", "ok-output", ok_calls.clone()),
+ Round17Tool::tool_error("round17_error", err_calls.clone()),
+ Round17Tool::failing_execute("round17_boom", boom_calls.clone()),
+ Round17Tool::write("round17_write", write_calls.clone()),
+ Round17Tool::cli_only("cli_only", Arc::new(AtomicUsize::new(0))),
+ ])
+ .memory(Arc::new(StaticMemory {
+ entries: Mutex::new(vec![MemoryEntry {
+ id: "m1".to_string(),
+ key: "k1".to_string(),
+ content: "remembered citation".to_string(),
+ namespace: Some("round17".to_string()),
+ category: MemoryCategory::Conversation,
+ timestamp: "2026-05-29T00:00:00Z".to_string(),
+ session_id: None,
+ score: Some(0.9),
+ taint: Default::default(),
+ }]),
+ entries_by_query: HashMap::new(),
+ fail_recall: true,
+ blocked_query: None,
+ recall_started: None,
+ release_recall: None,
+ recall_cancelled: None,
+ }))
+ .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .workspace_dir(workspace_path)
+ .event_context("round17-session", "round17-channel")
+ .agent_definition_name("round17/orchestrator")
+ .config(AgentConfig {
+ max_tool_iterations: 6,
+ channel_permissions,
+ ..AgentConfig::default()
+ })
+ // Budget must clear the rendered policy-denial message (~400 B) so the
+ // `denied by policy 'round17-deny'` assertion below still sees it. Before
+ // the tinyagents 1.5 migration (#4473) policy denials bypassed the
+ // per-result budget entirely; the migration now routes them through
+ // `ToolOutputMiddleware.after_tool`, so a tiny 96 B budget truncated the
+ // denial down to a `[… truncated …]` stub and the assertion no longer
+ // saw it. Production's default budget is 16 KiB, so real denials (~400 B)
+ // are never truncated — the old 96 B here was an artificial value with no
+ // assertion depending on truncation actually happening.
+ // TODO(follow-up): restore the "policy denials are exempt from the
+ // per-result budget" contract in production (tag the denial render with
+ // POLICY_BLOCKED_MARKER and skip the budget/persist path for it in
+ // `ToolOutputMiddleware.after_tool`). That also re-enables the no-progress
+ // `hard_reject` fast-path, which currently never fires for policy denials
+ // because their render omits the marker it greps for.
+ .context_config(ContextConfig {
+ tool_result_budget_bytes: 8192,
+ ..ContextConfig::default()
+ })
+ .post_turn_hooks(vec![Arc::new(RecordingHook {
+ calls: hook_calls.clone(),
+ notify: hook_notify.clone(),
+ fail: true,
+ })])
+ .tool_policy(Arc::new(DenyNamedPolicy("round17_ok")))
+ .explicit_preferences_enabled(false)
+ .build()
+ .unwrap();
+ let mut visible = HashSet::new();
+ visible.insert("round17_ok".to_string());
+ visible.insert("round17_error".to_string());
+ visible.insert("round17_boom".to_string());
+ visible.insert("round17_write".to_string());
+ visible.insert("cli_only".to_string());
+ agent.set_visible_tool_names(visible);
+
+ let checkpoint = agent.turn("exercise failure branches").await.unwrap();
+ assert!(
+ checkpoint.contains("Tool 'round17_ok' was denied by policy 'round17-deny'")
+ && checkpoint.contains("Different commands are all failing"),
+ "fallback checkpoint should be deterministic, got {checkpoint}"
+ );
+ assert_eq!(ok_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(err_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(boom_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(write_calls.load(Ordering::SeqCst), 0);
+ assert!(agent.take_last_turn_citations().await.is_empty());
+
+ timeout(Duration::from_secs(1), async {
+ loop {
+ if !hook_calls.lock().await.is_empty() {
+ break;
+ }
+ hook_notify.notified().await;
+ }
+ })
+ .await
+ .unwrap();
+ let hooks = hook_calls.lock().await;
+ assert_eq!(hooks[0].assistant_response, checkpoint);
+ assert_eq!(hooks[0].tool_calls.len(), 6);
+
+ let joined = provider
+ .requests()
+ .into_iter()
+ .flat_map(|request| request.messages)
+ .map(|message| message.text().to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ // An unregistered tool (`hidden_tool`, absent from both the tool set and the
+ // visible allowlist) is never executed: since issue #4249 it flows through the
+ // tinyagents `UnknownToolPolicy::ReturnToolError` path, which injects a
+ // recoverable result naming the requested tool and the valid ones instead of
+ // the legacy "not available to this agent" wording. The security guarantee —
+ // the hidden tool does not run — is preserved.
+ assert!(joined.contains("unknown tool `hidden_tool`"));
+ assert!(joined.contains("semantic failure"));
+ assert!(joined.contains("Error executing round17_boom"));
+ // Policy denials now terminate through the checkpoint path above instead
+ // of being replayed into a subsequent model request.
+
+ let (_failing_tmp, failing_workspace) = workspace("provider-error");
+ let provider_error = ScriptedModel::failing("provider offline");
+ let mut failing_agent = agent_with(
+ provider_error,
+ vec![],
+ failing_workspace,
+ Box::new(XmlToolDispatcher),
+ AgentConfig::default(),
+ ContextConfig::default(),
+ );
+ // A provider that fails on every attempt (primary *and* every same-family
+ // fallback route the tinyagents `RunPolicy.fallback` chain tries — issue #4249,
+ // Workstream 02.2) must surface a terminal error from `run_single` rather than
+ // wedging on a partial/empty reply. `ScriptedModel::failing` fails
+ // unconditionally, so the cross-route fallback cannot mask it.
+ let err = failing_agent.run_single("fail now").await.unwrap_err();
+ assert!(err.to_string().contains("provider offline"));
+}
+
+#[tokio::test]
+async fn subagent_runner_parent_context_filters_tools_caps_output_and_reports_errors() {
+ let _env = env_lock();
+ let no_parent = run_subagent(
+ &definition("round17_child", ToolScope::Wildcard, None, 3),
+ "outside turn",
+ SubagentRunOptions::default(),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(no_parent, SubagentRunError::NoParentContext));
+
+ let (_temp, workspace_path) = workspace("subagent");
+ let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let echo_calls = Arc::new(AtomicUsize::new(0));
+ let hidden_calls = Arc::new(AtomicUsize::new(0));
+ let provider = Arc::new(ScriptedModel {
+ responses: Mutex::new(
+ vec![
+ Ok(tool_response(
+ "child-1",
+ "round17_echo",
+ json!({ "value": "child" }),
+ )),
+ Ok(text_response("child final response that should be capped")),
+ ]
+ .into(),
+ ),
+ requests: Mutex::new(Vec::new()),
+ profile: native_profile(),
+ ..ScriptedModel::default()
+ });
+ let all_tools = vec![
+ Round17Tool::boxed("round17_echo", "child-tool", echo_calls.clone()),
+ Round17Tool::boxed("round17_hidden", "hidden-tool", hidden_calls.clone()),
+ Round17Tool::boxed(
+ "spawn_subagent",
+ "must-strip",
+ Arc::new(AtomicUsize::new(0)),
+ ),
+ ];
+ let all_specs = all_tools.iter().map(|tool| tool.spec()).collect::<Vec<_>>();
+ let parent = ParentExecutionContext {
+ agent_definition_id: "orchestrator".into(),
+ allowed_subagent_ids: [
+ "round17_child".to_string(),
+ "round17_provider_error".to_string(),
+ ]
+ .into_iter()
+ .collect(),
+ turn_model_source: openhuman_core::openhuman::agent::tinyagents::TurnModelSource::from_model(
+ provider.clone(),
+ ),
+ all_tools: Arc::new(all_tools),
+ all_tool_specs: Arc::new(all_specs),
+ visible_tool_names: std::collections::HashSet::new(),
+ subagent_tool_ceiling_names: std::collections::HashSet::new(),
+ model_name: "parent-model".to_string(),
+ temperature: 0.22,
+ workspace_dir: workspace_path.clone(),
+ workspace_descriptor: None,
+ memory: Arc::new(StaticMemory::default()),
+ agent_config: AgentConfig {
+ max_tool_iterations: 5,
+ ..AgentConfig::default()
+ },
+ workflows: Arc::new(Vec::new()),
+ memory_context: Arc::new(Some("parent memory context".to_string())),
+ session_id: "round17-parent-session".to_string(),
+ channel: "round17-parent-channel".to_string(),
+ connected_integrations: Vec::new(),
+ tool_call_format: openhuman_core::openhuman::agent::context::prompt::ToolCallFormat::Json,
+ session_key: "123_parent".to_string(),
+ session_parent_prefix: Some("root_ancestor".to_string()),
+ on_progress: None,
+ run_queue: None,
+ };
+
+ let outcome = with_parent_context(parent.clone(), async {
+ run_subagent(
+ &definition(
+ "round17_child",
+ ToolScope::Named(vec![
+ "round17_echo".to_string(),
+ "round17_hidden".to_string(),
+ "spawn_subagent".to_string(),
+ ]),
+ Some(18),
+ 4,
+ ),
+ "delegate this",
+ SubagentRunOptions {
+ context: Some("spawn context".to_string()),
+ model_override: Some("override-model".to_string()),
+ task_id: Some("task-round17".to_string()),
+ ..SubagentRunOptions::default()
+ },
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(outcome.task_id, "task-round17");
+ assert_eq!(outcome.agent_id, "round17_child");
+ assert_eq!(outcome.iterations, 2);
+ assert!(outcome.output.ends_with("[...truncated]"));
+ assert_eq!(echo_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(hidden_calls.load(Ordering::SeqCst), 0);
+
+ let requests = provider.requests();
+ assert_eq!(requests[0].model, "override-model");
+ assert_eq!(requests[0].temperature, 0.4);
+ assert_eq!(requests[0].tool_names, vec!["round17_echo"]);
+ assert!(requests[0]
+ .messages
+ .iter()
+ .any(|message| matches!(message, Message::System(_))
+ && message.text().contains("Sub-agent Role Contract")
+ && message.text().contains("round17 child prompt")));
+ assert!(requests[0]
+ .messages
+ .iter()
+ .any(|message| matches!(message, Message::User(_))
+ && message.text().contains("spawn context")
+ && message.text().contains("delegate this")));
+
+ let error_parent = ParentExecutionContext {
+ turn_model_source: openhuman_core::openhuman::agent::tinyagents::TurnModelSource::from_model(
+ ScriptedModel::failing("subagent provider offline"),
+ ),
+ ..parent
+ };
+ let provider_err = with_parent_context(error_parent, async {
+ run_subagent(
+ &definition("round17_provider_error", ToolScope::Wildcard, None, 1),
+ "provider error",
+ SubagentRunOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(provider_err, SubagentRunError::Provider(_)));
+ assert!(provider_err
+ .to_string()
+ .contains("subagent provider offline"));
+}
+
+fn definition(
+ id: &str,
+ tools: ToolScope,
+ max_result_chars: Option<usize>,
+ max_iterations: usize,
+) -> AgentDefinition {
+ AgentDefinition {
+ id: id.to_string(),
+ when_to_use: "round17 test definition".to_string(),
+ display_name: Some(id.to_string()),
+ system_prompt: PromptSource::Inline("round17 child prompt".to_string()),
+ omit_identity: true,
+ omit_memory_context: false,
+ omit_safety_preamble: true,
+ omit_profile: true,
+ omit_memory_md: true,
+ model: ModelSpec::Inherit,
+ temperature: 0.4,
+ tools,
+ disallowed_tools: vec!["round17_hidden".to_string()],
+ skill_filter: None,
+ extra_tools: Vec::new(),
+ max_iterations,
+ iteration_policy: Default::default(),
+ max_result_chars,
+ max_turn_output_tokens: None,
+ timeout_secs: None,
+ sandbox_mode: SandboxMode::None,
+ background: false,
+ trigger_memory_agent: Default::default(),
+ tokenjuice_compression: AgentTokenjuiceCompression::Auto,
+ subagents: Vec::new(),
+ delegate_name: None,
+ agent_tier: AgentTier::Worker,
+ source: DefinitionSource::Builtin,
+ graph: Default::default(),
+ }
+}
diff --git a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
index ba886453b8..4018b1385a 100644
--- a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
@@ -235,567 +235,3 @@ async fn one_response_server(
(url, task)
}
-#[tokio::test]
-async fn round19_app_state_local_state_snapshot_and_corruption_edges() {
- let _lock = env_lock();
- let harness = setup("http://127.0.0.1:9");
- let config = harness.config().await;
-
- let mut metadata = HashMap::new();
- metadata.insert("user_id".to_string(), "round19-user".to_string());
- metadata.insert(
- "user_json".to_string(),
- json!({
- "id": "round19-user",
- "fullName": "Round Nineteen",
- "email": "[email protected]"
- })
- .to_string(),
- );
- AuthService::from_config(&config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- "local-dev-token-round19",
- metadata,
- true,
- )
- .expect("seed local app session");
-
- let updated = update_local_state(StoredAppStatePatch {
- keyring_consent: None,
- encryption_key: Some(Some(" round19-key ".to_string())),
- onboarding_tasks: Some(Some(StoredOnboardingTasks {
- accessibility_permission_granted: true,
- local_model_consent_given: false,
- local_model_download_started: true,
- enabled_tools: vec!["rss".to_string()],
- connected_sources: vec!["folder".to_string(), "github".to_string()],
- updated_at_ms: Some(19),
- })),
- })
- .await
- .expect("write local app state")
- .value;
- assert_eq!(updated.encryption_key.as_deref(), Some("round19-key"));
- assert_eq!(
- updated
- .onboarding_tasks
- .as_ref()
- .expect("tasks")
- .connected_sources,
- vec!["folder", "github"]
- );
-
- let snap = snapshot().await.expect("snapshot").value;
- assert!(snap.auth.is_authenticated);
- assert_eq!(
- snap.session_token.as_deref(),
- Some("local-dev-token-round19")
- );
- assert_eq!(snap.auth.user_id.as_deref(), Some("round19-user"));
- assert_eq!(
- snap.current_user.as_ref().and_then(|v| v.get("fullName")),
- Some(&json!("Round Nineteen"))
- );
- assert!(snap.onboarding_completed);
- assert!(snap.analytics_enabled);
-
- let cleared = update_local_state(StoredAppStatePatch {
- keyring_consent: None,
- encryption_key: Some(Some(" ".to_string())),
- onboarding_tasks: Some(None),
- })
- .await
- .expect("clear local app state")
- .value;
- assert!(cleared.encryption_key.is_none());
- assert!(cleared.onboarding_tasks.is_none());
-
- std::fs::create_dir_all(harness.state_dir()).expect("state dir");
- std::fs::write(harness.app_state_file(), b"{not-json").expect("corrupt app state");
- let recovered = snapshot()
- .await
- .expect("snapshot quarantines corrupt state")
- .value;
- assert!(recovered.local_state.encryption_key.is_none());
- assert!(
- !harness.app_state_file().exists(),
- "corrupt app-state.json should be moved aside"
- );
- let has_quarantine = std::fs::read_dir(harness.state_dir())
- .expect("state entries")
- .filter_map(Result::ok)
- .any(|entry| {
- entry
- .file_name()
- .to_string_lossy()
- .contains("json.corrupted")
- });
- assert!(has_quarantine, "corrupt app state should leave artifact");
-}
-
-#[test]
-fn round19_credentials_profile_mutation_errors_and_secret_fallbacks() {
- let _lock = env_lock();
- let harness = setup("http://127.0.0.1:9");
- let state_dir = harness.root.join("profile-store");
- let store = AuthProfilesStore::new(&state_dir, false);
-
- assert_eq!(profile_id(" github ", " work "), "github:work");
- let expiring = TokenSet {
- access_token: "access".into(),
- refresh_token: Some("refresh".into()),
- id_token: Some("id".into()),
- expires_at: Some(Utc::now() + chrono::Duration::seconds(5)),
- token_type: Some("Bearer".into()),
- scope: Some("repo".into()),
- };
- assert!(expiring.is_expiring_within(std::time::Duration::from_secs(10)));
-
- let mut oauth = AuthProfile::new_oauth("github", "work", expiring);
- oauth.metadata = BTreeMap::from([("team".to_string(), "core".to_string())]);
- store
- .upsert_profile(oauth.clone(), true)
- .expect("insert oauth");
- let updated = store
- .update_profile(&oauth.id, |profile| {
- profile.workspace_id = Some("workspace-round19".to_string());
- profile.metadata.insert("updated".into(), "yes".into());
- Ok(())
- })
- .expect("update profile");
- assert_eq!(updated.workspace_id.as_deref(), Some("workspace-round19"));
-
- let updater_err = store
- .update_profile(&oauth.id, |_profile| {
- anyhow::bail!("round19 updater failed")
- })
- .expect_err("updater error should propagate")
- .to_string();
- assert!(updater_err.contains("round19 updater failed"));
- let missing_err = store
- .update_profile("missing-profile", |_profile| Ok(()))
- .expect_err("missing update should fail")
- .to_string();
- assert!(missing_err.contains("Auth profile not found"));
-
- store
- .clear_active_profile("github")
- .expect("clear active profile");
- assert!(store
- .load()
- .expect("load after clear")
- .active_profiles
- .get("github")
- .is_none());
- store
- .set_active_profile("github", &oauth.id)
- .expect("reactivate profile");
- assert!(!store
- .remove_profile("missing-profile")
- .expect("remove missing profile"));
- assert!(store.remove_profile(&oauth.id).expect("remove oauth"));
- assert!(store.load().expect("load after remove").profiles.is_empty());
-}
-
-#[tokio::test]
-async fn round19_credentials_service_prefix_and_corrupt_store_recovery() {
- let _lock = env_lock();
- let harness = setup("http://127.0.0.1:9");
- let config = harness.config().await;
- let auth = AuthService::from_config(&config);
-
- auth.store_provider_token(
- "channel:slack:bot",
- "primary",
- "xoxb-round19",
- HashMap::from([("team_id".to_string(), "T19".to_string())]),
- true,
- )
- .expect("store slack token");
- auth.store_provider_token(
- "channel:telegram:managed_dm",
- "primary",
- "telegram-round19",
- HashMap::new(),
- true,
- )
- .expect("store telegram token");
- auth.store_provider_token("github", "work", "ghp-round19", HashMap::new(), true)
- .expect("store github token");
-
- let channels = list_provider_credentials_by_prefix(&config, "channel:")
- .await
- .expect("list channel credentials");
- assert_eq!(
- channels
- .iter()
- .map(|profile| profile.provider.as_str())
- .collect::<Vec<_>>(),
- vec!["channel:slack:bot", "channel:telegram:managed_dm"]
- );
- assert!(channels
- .iter()
- .any(|profile| profile.metadata_keys == vec!["team_id"]));
-
- let store = AuthProfilesStore::new(&harness.state_dir().join("credentials"), false);
- let path = store.path().to_path_buf();
- std::fs::create_dir_all(path.parent().expect("profile parent")).expect("profile dir");
- std::fs::write(
- &path,
- serde_json::to_string_pretty(&json!({
- "schema_version": 1,
- "updated_at": Utc::now().to_rfc3339(),
- "active_profiles": { "bad": "legacy-bad-kind" },
- "profiles": {
- "legacy-bad-kind": {
- "provider": "bad",
- "profile_name": "legacy",
- "kind": "api_key",
- "token": "plain-token",
- "created_at": Utc::now().to_rfc3339(),
- "updated_at": Utc::now().to_rfc3339()
- }
- }
- }))
- .expect("profile json"),
- )
- .expect("write bad profile");
- let recovered = store.load().expect("bad kind should be dropped");
- assert!(recovered.profiles.is_empty());
- assert!(recovered.active_profiles.is_empty());
-
- std::fs::write(&path, "{broken").expect("write corrupt profile store");
- let empty = store.load().expect("corrupt store quarantined");
- assert!(empty.profiles.is_empty());
- assert!(!path.exists());
-}
-
-#[tokio::test]
-async fn round19_threads_ops_cover_title_message_delete_and_purge_edges() {
- let _lock = env_lock();
- let _harness = setup("http://127.0.0.1:9");
-
- let created = thread_ops::thread_create_new(CreateConversationThreadRequest {
- labels: Some(vec!["personal".to_string(), "onboarding".to_string()]),
- personality_id: Some("coach".to_string()),
- })
- .await
- .expect("create thread")
- .value
- .data
- .expect("created thread");
- assert!(created.title.starts_with("Chat "));
- assert_eq!(created.personality_id.as_deref(), Some("coach"));
-
- let empty_title = thread_ops::thread_update_title(UpdateConversationThreadTitleRequest {
- thread_id: created.id.clone(),
- title: " ".to_string(),
- })
- .await
- .expect_err("empty title rejected");
- assert!(empty_title.contains("title must not be empty"));
-
- let renamed = thread_ops::thread_update_title(UpdateConversationThreadTitleRequest {
- thread_id: created.id.clone(),
- title: " Durable user title ".to_string(),
- })
- .await
- .expect("rename thread")
- .value
- .data
- .expect("renamed thread");
- assert_eq!(renamed.title, "Durable user title");
-
- let labels = thread_ops::thread_update_labels(UpdateConversationThreadLabelsRequest {
- thread_id: created.id.clone(),
- labels: Vec::new(),
- })
- .await
- .expect("clear labels")
- .value
- .data
- .expect("labels response");
- assert!(labels.labels.is_empty());
-
- let user_message = ConversationMessageRecord {
- id: "msg-user".to_string(),
- content: "Plan the June launch checklist with design, QA, and release owners.".to_string(),
- message_type: "text".to_string(),
- extra_metadata: json!({"source":"round19"}),
- sender: "user".to_string(),
- created_at: Utc::now().to_rfc3339(),
- };
- thread_ops::message_append(AppendConversationMessageRequest {
- thread_id: created.id.clone(),
- message: user_message.clone(),
- })
- .await
- .expect("append user message");
- let updated_message = thread_ops::message_update(UpdateConversationMessageRequest {
- thread_id: created.id.clone(),
- message_id: user_message.id.clone(),
- extra_metadata: Some(json!({"edited": true})),
- })
- .await
- .expect("update message")
- .value
- .data
- .expect("message data");
- assert_eq!(updated_message.extra_metadata["edited"], true);
-
- let messages = thread_ops::messages_list(ConversationMessagesRequest {
- thread_id: created.id.clone(),
- })
- .await
- .expect("list messages")
- .value
- .data
- .expect("messages");
- assert_eq!(messages.count, 1);
-
- let non_placeholder =
- thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: created.id.clone(),
- assistant_message: Some("Here is a concise plan.".to_string()),
- })
- .await
- .expect("non-placeholder skips generation")
- .value
- .data
- .expect("title generation response");
- assert_eq!(non_placeholder.title, "Durable user title");
-
- let listed = thread_ops::threads_list(EmptyRequest {})
- .await
- .expect("list threads")
- .value
- .data
- .expect("thread list");
- assert_eq!(listed.count, 1);
-
- let missing_append = thread_ops::message_append(AppendConversationMessageRequest {
- thread_id: "missing-thread".to_string(),
- message: ConversationMessageRecord {
- id: "missing-msg".to_string(),
- content: "hello".to_string(),
- message_type: "text".to_string(),
- extra_metadata: Value::Null,
- sender: "user".to_string(),
- created_at: Utc::now().to_rfc3339(),
- },
- })
- .await
- .expect_err("missing thread should map to ThreadsError");
- assert_eq!(
- missing_append.to_string(),
- "thread missing-thread not found"
- );
-
- let deleted = thread_ops::thread_delete(DeleteConversationThreadRequest {
- thread_id: created.id.clone(),
- deleted_at: Utc::now().to_rfc3339(),
- })
- .await
- .expect("delete thread")
- .value
- .data
- .expect("delete response");
- assert!(deleted.deleted);
-
- let purged = thread_ops::threads_purge(EmptyRequest {})
- .await
- .expect("purge empty")
- .value
- .data
- .expect("purge response");
- assert_eq!(purged.agent_threads_deleted, 0);
-}
-
-#[test]
-fn round19_welcome_migration_handles_renames_collisions_and_marker() {
- let _lock = env_lock();
- let harness = setup("http://127.0.0.1:9");
- let workspace = harness.workspace_dir();
- std::fs::create_dir_all(workspace.join("session_raw")).expect("raw dir");
-
- let blocked = workspace.join("session_raw/1715000000_welcome_thread-abc.jsonl");
- write_transcript(&blocked, "welcome_thread-abc", "thread-abc");
- let collision = workspace.join("session_raw/1715000000_orchestrator_thread-abc.jsonl");
- write_transcript(&collision, "orchestrator_thread-abc", "thread-abc");
- let err = migrate_welcome_agent_artifacts(&workspace)
- .expect_err("destination collision should fail migration");
- assert!(err.contains("partial migration"));
- assert!(std::fs::read_to_string(&blocked)
- .expect("blocked transcript")
- .contains("\"agent\":\"welcome_thread-abc\""));
-
- std::fs::remove_file(collision).expect("remove collision");
- let result = migrate_welcome_agent_artifacts(&workspace).expect("retry migration");
- assert_eq!(result.transcripts_updated, 1);
- assert_eq!(result.transcript_files_renamed, 1);
- assert!(workspace
- .join("session_raw/1715000000_orchestrator_thread-abc.jsonl")
- .exists());
-
- let again = migrate_welcome_agent_artifacts(&workspace).expect("marker skip");
- assert!(again.already_done);
-}
-
-fn write_transcript(path: &Path, agent: &str, thread_id: &str) {
- let body = format!(
- "{{\"_meta\":{{\"agent\":\"{agent}\",\"dispatcher\":\"native\",\"created\":\"2026-05-01T00:00:00Z\",\"updated\":\"2026-05-01T00:00:00Z\",\"turn_count\":1,\"input_tokens\":0,\"output_tokens\":0,\"cached_input_tokens\":0,\"charged_amount_usd\":0.0,\"thread_id\":\"{thread_id}\"}}}}\n{{\"role\":\"user\",\"content\":\"hi\"}}\n"
- );
- std::fs::create_dir_all(path.parent().expect("transcript parent")).expect("transcript dir");
- std::fs::write(path, body).expect("write transcript");
-}
-
-#[tokio::test]
-async fn round19_memory_sources_registry_readers_sync_and_reconcile_edges() {
- let _lock = env_lock();
- ensure_memory_seams();
- let harness = setup("http://127.0.0.1:9");
- let config = harness.config().await;
-
- let invalid = memory_sources::registry::add_source(source_entry("", SourceKind::Folder, "No id"))
- .await
- .expect_err("id required");
- assert!(invalid.contains("id is required"), "unexpected validation error: {invalid}");
-
- let folder_dir = harness.root.join("notes");
- std::fs::create_dir_all(&folder_dir).expect("notes dir");
- std::fs::write(folder_dir.join("note.md"), "# Round 19\nbody").expect("note");
- std::fs::write(folder_dir.join("skip.txt"), "ignored").expect("skip");
- let mut folder = source_entry("src-folder", SourceKind::Folder, "Notes");
- folder.path = Some(folder_dir.to_string_lossy().to_string());
- folder.glob = Some("**/*".to_string());
- let added = memory_sources::registry::add_source(folder.clone())
- .await
- .expect("add folder source");
- assert_eq!(added.id, "src-folder");
- let duplicate = memory_sources::registry::add_source(folder.clone())
- .await
- .expect_err("duplicate source rejected");
- assert!(duplicate.contains("already exists"));
-
- let updated = memory_sources::registry::update_source(
- "src-folder",
- MemorySourcePatch {
- label: Some("Renamed notes".to_string()),
- enabled: Some(false),
- ..MemorySourcePatch::default()
- },
- )
- .await
- .expect("update source");
- assert_eq!(updated.label, "Renamed notes");
- assert!(!updated.enabled);
- assert_eq!(
- memory_sources::registry::list_enabled_by_kind(SourceKind::Folder)
- .await
- .expect("list enabled folders")
- .len(),
- 0
- );
- let disabled_sync = tinymemory_core::sources::sync::sync_source(updated.clone(), Arc::new(config.clone()))
- .await
- .expect_err("disabled source rejected");
- assert!(disabled_sync.contains("disabled"));
-
- let reader = openhuman_core::openhuman::memory::sources::readers::folder::FolderReader;
- let listed = reader
- .list_items(&folder, &config)
- .await
- .expect("folder list items");
- assert_eq!(listed.len(), 2);
- let md = reader
- .read_item(&folder, "note.md", &config)
- .await
- .expect("read note");
- assert_eq!(md.title, "note.md");
- let traversal = reader
- .read_item(&folder, "../outside.md", &config)
- .await
- .expect_err("path traversal denied");
- assert!(traversal.contains("path traversal") || traversal.contains("file not found"));
-
- let twitter = source_entry("src-twitter", SourceKind::TwitterQuery, "Tweets");
- let twitter_sync = tinymemory_core::sources::sync::sync_source(
- MemorySourceEntry {
- query: Some("openhuman".to_string()),
- ..twitter
- },
- Arc::new(config.clone()),
- )
- .await;
- assert!(
- twitter_sync.is_ok(),
- "twitter placeholder is reported async"
- );
-
- let upserted =
- memory_sources::upsert_composio_source("gmail", "conn-round19-abcdefghi", "Gmail first")
- .await
- .expect("insert composio source");
- let updated_composio =
- memory_sources::upsert_composio_source("gmail", "conn-round19-abcdefghi", "Gmail updated")
- .await
- .expect("update composio source");
- assert_eq!(updated_composio.id, upserted.id);
- assert_eq!(updated_composio.label, "Gmail updated");
-
- let github_reader = openhuman_core::openhuman::memory::sources::readers::github::GithubReader;
- let github_err = github_reader
- .list_items(
- &MemorySourceEntry {
- url: Some("https://example.com/not/github".to_string()),
- ..source_entry("src-gh", SourceKind::GithubRepo, "Bad repo")
- },
- &config,
- )
- .await
- .expect_err("invalid github url");
- assert!(github_err.contains("not a GitHub URL"));
- let item_err = github_reader
- .read_item(
- &MemorySourceEntry {
- url: Some("https://github.com/tinyhumansai/openhuman".to_string()),
- ..source_entry("src-gh-good", SourceKind::GithubRepo, "Repo")
- },
- "bad:123",
- &config,
- )
- .await
- .expect_err("invalid github item id");
- assert!(item_err.contains("invalid item id"));
-
- let feed_body = r#"<?xml version="1.0"?>
-<rss version="2.0"><channel><title>Round19</title>
-<item><title>First &amp; only</title><guid>guid-1</guid><description><![CDATA[<p>Hello</p>]]></description><pubDate>Fri, 29 May 2026 00:00:00 GMT</pubDate></item>
-</channel></rss>"#;
- let (feed_url, server_task) = one_response_server(feed_body, "application/rss+xml").await;
- let rss = MemorySourceEntry {
- url: Some(feed_url),
- max_items: Some(1),
- ..source_entry("src-rss", SourceKind::RssFeed, "Feed")
- };
- let rss_reader = openhuman_core::openhuman::memory::sources::readers::rss::RssReader::new();
- let rss_error = rss_reader
- .list_items(&rss, &config)
- .await
- .expect_err("loopback RSS feed must be rejected by the SSRF guard");
- assert!(rss_error.contains("public host"), "unexpected RSS error: {rss_error}");
- server_task.abort();
-
- memory_sources::reconcile::ensure_composio_sources().await;
- assert!(
- memory_sources::registry::remove_source("missing-source")
- .await
- .expect("remove missing is idempotent")
- == false
- );
- assert!(memory_sources::registry::remove_source("src-folder")
- .await
- .expect("remove folder"));
-}
diff --git a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
index aa725f596b..da23165511 100644
--- a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
@@ -156,143 +156,3 @@ fn source_entry(id: &str, kind: SourceKind) -> MemorySourceEntry {
}
}
-#[tokio::test]
-async fn round23_memory_sources_status_registry_and_readers_cover_remaining_edges() {
- let _lock = env_lock();
- ensure_memory_seams();
- let harness = setup();
- let config = harness.config().await;
-
- let folder_root = harness.root.join("docs");
- std::fs::create_dir_all(&folder_root).expect("docs");
- let folder = MemorySourceEntry {
- path: Some(folder_root.to_string_lossy().into_owned()),
- ..source_entry("round23-folder", SourceKind::Folder)
- };
- let added = memory_sources::registry::add_source(folder.clone())
- .await
- .expect("add folder source");
- assert_eq!(added.id, "round23-folder");
- let duplicate = memory_sources::registry::add_source(folder)
- .await
- .expect_err("duplicate source rejected");
- assert!(duplicate.contains("already exists"));
-
- let updated = memory_sources::registry::update_source(
- "round23-folder",
- MemorySourcePatch {
- label: Some("Round23 Folder Updated".to_string()),
- enabled: Some(false),
- glob: Some(Some("**/*.md".to_string())),
- ..MemorySourcePatch::default()
- },
- )
- .await
- .expect("update source");
- assert_eq!(updated.label, "Round23 Folder Updated");
- assert!(!updated.enabled);
- assert_eq!(updated.glob.as_deref(), Some("**/*.md"));
-
- let missing_update = memory_sources::registry::update_source(
- "missing-round23",
- MemorySourcePatch {
- label: Some("Missing".to_string()),
- ..MemorySourcePatch::default()
- },
- )
- .await
- .expect_err("missing source rejected");
- assert!(missing_update.contains("source 'missing-round23' not found"));
-
- let invalid = memory_sources::registry::add_source(MemorySourceEntry {
- url: None,
- ..source_entry("bad-rss", SourceKind::RssFeed)
- })
- .await
- .expect_err("invalid source rejected");
- assert!(invalid.contains("url is required"));
-
- let composio = memory_sources::upsert_composio_source(
- "gmail",
- "conn-round23-source-status",
- "Gmail Round23",
- )
- .await
- .expect("insert composio");
- let composio = memory_sources::registry::update_source(
- &composio.id,
- MemorySourcePatch {
- enabled: Some(true),
- ..MemorySourcePatch::default()
- },
- )
- .await
- .expect("enable composio source");
- let status = tinymemory_core::sources::status::source_status(&config, &composio)
- .await
- .expect("composio status");
- assert_eq!(status.source_id, composio.id);
- assert_eq!(status.chunks_synced, 0);
- assert_eq!(
- status.freshness,
- tinymemory_core::sources::status::FreshnessLabel::Idle
- );
-
- let statuses = memory_sources::status::status_list(&config)
- .await
- .expect("status list");
- assert!(statuses
- .iter()
- .any(|status| status.source_id == composio.id));
-
- let enabled_composio = memory_sources::registry::list_enabled_by_kind(SourceKind::Composio)
- .await
- .expect("enabled composio");
- assert_eq!(enabled_composio.len(), 1);
- assert_eq!(enabled_composio[0].id, composio.id);
-
- let composio_reader =
- openhuman_core::openhuman::memory::sources::readers::composio::ComposioReader;
- let items = composio_reader
- .list_items(&composio, &config)
- .await
- .expect("composio reader items");
- assert_eq!(items[0].id, "conn-round23-source-status");
- let content = composio_reader
- .read_item(&composio, "conn-round23-source-status", &config)
- .await
- .expect("composio reader content");
- assert_eq!(content.content_type, ContentType::Plaintext);
- assert!(content.body.contains("provider sync pipeline"));
-
- let twitter_reader = openhuman_core::openhuman::memory::sources::readers::twitter::TwitterReader;
- let missing_query = twitter_reader
- .list_items(
- &source_entry("tw-missing", SourceKind::TwitterQuery),
- &config,
- )
- .await
- .expect_err("missing twitter query rejected");
- assert!(missing_query.contains("non-empty query"));
- let configured_query = twitter_reader
- .list_items(
- &MemorySourceEntry {
- query: Some(" openhuman ".to_string()),
- since_days: Some(14),
- ..source_entry("tw-round23", SourceKind::TwitterQuery)
- },
- &config,
- )
- .await
- .expect_err("twitter credentials not configured");
- assert!(configured_query.contains("Query 'openhuman' is saved"));
- let read_err = twitter_reader
- .read_item(
- &source_entry("tw-round23", SourceKind::TwitterQuery),
- "tweet-1",
- &config,
- )
- .await
- .expect_err("twitter read not configured");
- assert!(read_err.contains("Individual tweet reading"));
-}
diff --git a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..afe4e372ed
--- /dev/null
+++ b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs
@@ -0,0 +1,183 @@
+//! Round 23 raw coverage focused on memory_sync gaps.
+//!
+//! Local-only: temp workspaces and no real provider network. Run
+//! single-threaded because HOME, OPENHUMAN_WORKSPACE, and config loading are
+//! process globals.
+//!
+//! # What this file used to cover, and what happened to it
+//!
+//! tinymemory v1.13.4 deleted the in-process Composio pipeline outright (72
+//! files, ~18.3k lines) — see
+//! `crate::openhuman::integrations::composio::providers`'s module docs for the
+//! full account. This file originally instantiated the deleted engine's
+//! `SlackProvider` / `NotionProvider` / `GmailProvider` directly against a
+//! loopback HTTP router standing in for the Composio execute API, and
+//! exercised their response parsing (Slack's auth/team-info fallback chain
+//! when the `users:read.email` scope is missing, Notion's cursor pagination
+//! into the memory tree, Gmail's nested-payload flattening and raw-HTML
+//! opt-out).
+//!
+//! That parsing did not move anywhere reachable from this crate: it lives
+//! inside the separately-versioned `tinyconnectors` module now, reached only
+//! over the module bus via `openhuman.composio_get_user_profile` /
+//! `run_sync_pass` (`integrations::composio::ops`). Driving that path for
+//! real means a live loaded module — a network download of a pinned
+//! release artifact plus a `dlopen`, which is exactly what this file's own
+//! "no real provider network" design rules out, and which the CLAUDE.md
+//! module-testing note says to run `#[ignore]`d with `OPENHUMAN_MODULE_PATH`
+//! instead of in the default suite. So the three provider-specific tests
+//! (`slack_profile_falls_back_to_auth_and_team_info_without_email_scope`,
+//! `notion_profile_prefers_bot_owner_and_sync_paginates_into_memory_tree`,
+//! `gmail_post_process_handles_nested_payloads_and_raw_html_opt_out`) test a
+//! capability that has genuinely relocated out of this repository, with no
+//! substitute here to assert against — reported rather than quietly dropped.
+//! `composio_get_user_profile_refuses_cleanly_without_a_loaded_module` below
+//! is what remains honestly testable of that call path from here: the
+//! module-load gate the deleted providers used to sit behind.
+//!
+//! What genuinely stayed in this crate — persisting a fetched profile as
+//! identity facets, loading them back, rendering them, and deleting them on
+//! disconnect — is `integrations::composio::identity_store`, this host's own
+//! port of the deleted engine's `sync::composio::providers::profile`
+//! (see that module's doc comment for exactly what carried over and what did
+//! not). `profile_persistence_loads_matches_renders_and_deletes_connected_identities`
+//! below is that same test, updated onto the new (async, `&Config`-taking)
+//! API. One piece of it could not be preserved: the deleted engine's
+//! per-toolkit `is_self_identity(prefix, kind, value)` has no replacement
+//! anywhere in `tinymemory-core` any more — only the cross-toolkit
+//! `is_self_identity_any_toolkit` survived (it backs the memory tree's entity
+//! matcher and was never toolkit-scoped to begin with). The toolkit-scoped
+//! assertions are gone from this test as a result; see the src-side gap note
+//! in the migration report.
+
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock};
+
+use serde_json::{json, Value};
+use tempfile::TempDir;
+
+use openhuman_core::openhuman::config::Config;
+use openhuman_core::openhuman::integrations::composio::identity_store::{
+ delete_connected_identity_facets, load_connected_identities, persist_provider_profile,
+};
+use openhuman_core::openhuman::integrations::composio::ops::composio_get_user_profile;
+use openhuman_core::openhuman::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+};
+use tinymemory_api::composio::{render_connected_identities_section, ProviderUserProfile};
+
+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
+
+fn ensure_memory_seams() {
+ MEMORY_SEAMS_INIT.get_or_init(|| {
+ std::thread::Builder::new()
+ .name("memory-sync-round23-raw-coverage-seams".to_string())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(|| {
+ })
+ .expect("spawn round23 memory sync seam installer")
+ .join()
+ .expect("round23 memory sync seam installer panicked");
+ });
+}
+
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ ENV_LOCK
+ .get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+}
+
+struct EnvGuard {
+ key: &'static str,
+ old: Option<String>,
+}
+
+impl EnvGuard {
+ fn set(key: &'static str, value: impl Into<String>) -> Self {
+ let old = std::env::var(key).ok();
+ unsafe { std::env::set_var(key, value.into()) };
+ Self { key, old }
+ }
+
+ fn set_path(key: &'static str, value: &std::path::Path) -> Self {
+ Self::set(key, value.to_string_lossy().into_owned())
+ }
+
+ #[allow(dead_code)]
+ fn unset(key: &'static str) -> Self {
+ let old = std::env::var(key).ok();
+ unsafe { std::env::remove_var(key) };
+ Self { key, old }
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ match &self.old {
+ Some(value) => unsafe { std::env::set_var(self.key, value) },
+ None => unsafe { std::env::remove_var(self.key) },
+ }
+ }
+}
+
+fn config_in(tmp: &TempDir) -> Config {
+ ensure_memory_seams();
+ let mut config = Config {
+ config_path: tmp.path().join("config.toml"),
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ ..Config::default()
+ };
+ config.secrets.encrypt = false;
+ config.memory_tree.embedding_endpoint = None;
+ config.memory_tree.embedding_model = None;
+ config.memory_tree.embedding_strict = false;
+ config
+}
+
+async fn persist_config(config: &Config) {
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace dir");
+ config.save().await.expect("save config");
+}
+
+fn store_session(config: &Config) {
+ AuthService::from_config(config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ "round23-session-token",
+ HashMap::new(),
+ true,
+ )
+ .expect("store app session token");
+}
+
+/// `composio_get_user_profile` resolves the connection's toolkit through the
+/// `tinyconnectors` module before it can fetch anything, so a build with
+/// `modules.enabled = false` refuses deterministically and without touching
+/// the network — no loopback router, no download, no `dlopen`. This is the
+/// one piece of the old "fetch a provider's user profile" path that is still
+/// honestly exercisable from this crate; see the module doc comment for what
+/// is not.
+#[tokio::test]
+async fn composio_get_user_profile_refuses_cleanly_without_a_loaded_module() {
+ let _guard = env_lock();
+ let tmp = TempDir::new().expect("tempdir");
+ let _workspace = EnvGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());
+ let _home = EnvGuard::set_path("HOME", tmp.path());
+
+ let mut config = config_in(&tmp);
+ config.modules.enabled = false;
+ persist_config(&config).await;
+ store_session(&config);
+
+ let result = composio_get_user_profile(&config, "conn-slack-23").await;
+ let error = result.expect_err("profile fetch must refuse without a loaded connectors module");
+ assert!(
+ error.contains("modules are disabled in configuration"),
+ "unexpected error: {error}"
+ );
+}
+
diff --git a/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..57a2f465fc
--- /dev/null
+++ b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
@@ -0,0 +1,734 @@
+//! Round 20 near-90 raw integration coverage closures.
+//!
+//! All fixtures are local and deterministic: temp workspaces, loopback HTTP,
+//! and a fake `gh` binary. Run with `--test-threads=1`; several covered
+//! surfaces resolve config/workspace through process environment.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration as StdDuration;
+
+use chrono::Utc;
+use openhuman_core::openhuman::desktop::app_state::{
+ snapshot, update_local_state, StoredAppStatePatch, StoredOnboardingTasks,
+};
+use openhuman_core::openhuman::config::rpc as config_rpc;
+use openhuman_core::openhuman::security::credentials::profiles::{
+ AuthProfile, AuthProfileKind, AuthProfilesStore,
+};
+use openhuman_core::openhuman::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+};
+use openhuman_core::openhuman::memory::{
+ ai_list_memory_files, ai_read_memory_file, ai_write_memory_file, clear_namespace,
+ context_query, context_recall, doc_delete, doc_list, doc_put, memory_delete_document,
+ memory_init, memory_list_documents, memory_list_namespaces, memory_query_namespace,
+ memory_recall_context, memory_recall_memories, namespace_list, ClearNamespaceParams,
+ DeleteDocParams, EmptyRequest, ListDocumentsRequest, ListMemoryFilesRequest, MemoryInitRequest,
+ PutDocParams, QueryNamespaceParams, QueryNamespaceRequest, ReadMemoryFileRequest,
+ RecallContextRequest, RecallMemoriesRequest, RecallNamespaceParams, WriteMemoryFileRequest,
+};
+use openhuman_core::openhuman::memory::sources::readers::SourceReader;
+// The engine's own source pipeline. `memory::sources::sync` is host-side now and
+// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
+// `src/` calls it any more (#5560).
+use openhuman_core::openhuman::memory::sources::{ContentType, MemorySourceEntry, SourceKind};
+use openhuman_core::openhuman::threads::ops as thread_ops;
+use openhuman_core::openhuman::threads::welcome_migration::migrate_welcome_agent_artifacts;
+use serde_json::{json, Value};
+use tempfile::{Builder, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+static ROUND20_ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
+
+struct EnvGuard {
+ key: &'static str,
+ old: Option<String>,
+}
+
+impl EnvGuard {
+ fn set(key: &'static str, value: impl Into<String>) -> Self {
+ let old = std::env::var(key).ok();
+ unsafe { std::env::set_var(key, value.into()) };
+ Self { key, old }
+ }
+
+ fn set_path(key: &'static str, path: &Path) -> Self {
+ Self::set(key, path.to_string_lossy().into_owned())
+ }
+
+ fn unset(key: &'static str) -> Self {
+ let old = std::env::var(key).ok();
+ unsafe { std::env::remove_var(key) };
+ Self { key, old }
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ match &self.old {
+ Some(value) => unsafe { std::env::set_var(self.key, value) },
+ None => unsafe { std::env::remove_var(self.key) },
+ }
+ }
+}
+
+struct Harness {
+ _tmp: TempDir,
+ root: PathBuf,
+ _guards: Vec<EnvGuard>,
+}
+
+impl Harness {
+ async fn config(&self) -> openhuman_core::openhuman::config::Config {
+ config_rpc::load_config_with_timeout()
+ .await
+ .expect("isolated config should load")
+ }
+
+ fn workspace_dir(&self) -> PathBuf {
+ self.root.join("workspace")
+ }
+
+ fn state_dir(&self) -> PathBuf {
+ self.workspace_dir().join("state")
+ }
+
+ fn app_state_file(&self) -> PathBuf {
+ self.state_dir().join("app-state.json")
+ }
+}
+
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ ROUND20_ENV_LOCK
+ .get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+fn ensure_memory_seams(config: Arc<openhuman_core::openhuman::config::Config>) {
+ std::thread::Builder::new()
+ .name("round20-memory-seams".to_string())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(move || {
+ #[cfg(feature = "modules")]
+ openhuman_core::openhuman::modules::memory::set_modules_policy(config);
+ })
+ .expect("spawn round20 memory seam installer")
+ .join()
+ .expect("round20 memory seam installer panicked");
+}
+
+fn tempdir() -> TempDir {
+ std::fs::create_dir_all("target").expect("create target");
+ Builder::new()
+ .prefix("near90-closure-round20-")
+ .tempdir_in("target")
+ .expect("round20 tempdir")
+}
+
+fn write_min_config(root: &Path, api_url: &str) {
+ std::fs::create_dir_all(root).expect("create config root");
+ let cfg = format!(
+ r#"api_url = "{api_url}"
+default_model = "round20-coverage-model"
+default_temperature = 0.2
+onboarding_completed = true
+chat_onboarding_completed = false
+
+[observability]
+analytics_enabled = false
+
+[secrets]
+encrypt = false
+
+[meet]
+auto_orchestrator_handoff = false
+
+[local_ai]
+enabled = false
+runtime_enabled = false
+opt_in_confirmed = false
+
+[memory]
+provider = "none"
+embedding_provider = "none"
+embedding_model = "none"
+embedding_dimensions = 0
+auto_save = false
+
+[memory_tree]
+embedding_strict = false
+"#
+ );
+ std::fs::write(root.join("config.toml"), &cfg).expect("write config.toml");
+ let _: openhuman_core::openhuman::config::Config =
+ toml::from_str(&cfg).expect("round20 config must match schema");
+}
+
+fn setup(api_url: &str) -> Harness {
+ let tmp = tempdir();
+ let root = tmp.path().join("openhuman");
+ write_min_config(&root, api_url);
+ let guards = vec![
+ EnvGuard::set_path("OPENHUMAN_WORKSPACE", &root),
+ EnvGuard::set_path("HOME", tmp.path()),
+ EnvGuard::unset("BACKEND_URL"),
+ EnvGuard::unset("VITE_BACKEND_URL"),
+ EnvGuard::unset("OPENHUMAN_API_URL"),
+ EnvGuard::unset("OPENHUMAN_CORE_RPC_URL"),
+ EnvGuard::unset("OPENHUMAN_CORE_PORT"),
+ EnvGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),
+ EnvGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),
+ EnvGuard::set("OPENHUMAN_MEMORY_EMBED_ENDPOINT", ""),
+ EnvGuard::set("OPENHUMAN_MEMORY_EMBED_MODEL", ""),
+ ];
+
+ Harness {
+ _tmp: tmp,
+ root,
+ _guards: guards,
+ }
+}
+
+fn source_entry(id: &str, kind: SourceKind) -> MemorySourceEntry {
+ MemorySourceEntry {
+ id: id.to_string(),
+ kind,
+ label: format!("{id} label"),
+ enabled: true,
+ toolkit: None,
+ connection_id: None,
+ path: None,
+ glob: None,
+ url: None,
+ branch: None,
+ paths: Vec::new(),
+ query: None,
+ since_days: None,
+ max_items: None,
+ max_commits: None,
+ max_issues: None,
+ max_prs: None,
+ selector: None,
+ max_tokens_per_sync: None,
+ max_cost_per_sync_usd: None,
+ sync_depth_days: None,
+ }
+}
+
+async fn auth_me_server(
+ status: &'static str,
+ body: &'static str,
+) -> (String, tokio::task::JoinHandle<()>) {
+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .expect("bind auth fixture");
+ let url = format!("http://{}", listener.local_addr().expect("listener addr"));
+ let task = tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let mut req = [0_u8; 2048];
+ let _ = stream.read(&mut req).await;
+ let response = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.shutdown().await;
+ }
+ });
+ (url, task)
+}
+
+#[tokio::test]
+async fn round20_app_state_quarantines_directory_state_and_uses_stored_user_on_http_error() {
+ let _lock = env_lock();
+ let (api_url, server) = auth_me_server("503 Service Unavailable", r#"{"error":"down"}"#).await;
+ let harness = setup(&api_url);
+ let config = harness.config().await;
+
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ "round20.remote.token",
+ HashMap::from([
+ ("user_id".to_string(), "stored-round20".to_string()),
+ (
+ "user_json".to_string(),
+ json!({"id":"stored-round20","fullName":"Stored Round20"}).to_string(),
+ ),
+ ]),
+ true,
+ )
+ .expect("seed app session");
+
+ let first = update_local_state(StoredAppStatePatch {
+ keyring_consent: None,
+ encryption_key: None,
+ onboarding_tasks: Some(Some(StoredOnboardingTasks {
+ accessibility_permission_granted: false,
+ local_model_consent_given: true,
+ local_model_download_started: false,
+ enabled_tools: vec!["github".to_string()],
+ connected_sources: vec!["rss".to_string()],
+ updated_at_ms: Some(20),
+ })),
+ })
+ .await
+ .expect("write tasks")
+ .value;
+ assert!(first.encryption_key.is_none());
+ assert_eq!(
+ first.onboarding_tasks.expect("tasks").enabled_tools,
+ vec!["github"]
+ );
+
+ let snap = snapshot().await.expect("snapshot").value;
+ assert_eq!(
+ snap.current_user.as_ref().and_then(|v| v.get("id")),
+ Some(&json!("stored-round20"))
+ );
+ assert_eq!(snap.session_token.as_deref(), Some("round20.remote.token"));
+ assert!(!snap.analytics_enabled);
+
+ std::fs::remove_file(harness.app_state_file()).expect("remove app-state file");
+ std::fs::create_dir_all(harness.app_state_file()).expect("directory at app-state path");
+ let recovered = snapshot()
+ .await
+ .expect("snapshot should quarantine unreadable app-state path")
+ .value;
+ assert!(recovered.local_state.onboarding_tasks.is_none());
+ assert!(!harness.app_state_file().exists());
+ assert!(
+ std::fs::read_dir(harness.state_dir())
+ .expect("state dir")
+ .filter_map(Result::ok)
+ .any(|entry| entry
+ .file_name()
+ .to_string_lossy()
+ .contains("json.corrupted")),
+ "directory app-state should be moved aside"
+ );
+
+ server.abort();
+}
+
+#[test]
+fn round20_credentials_profiles_cover_legacy_plaintext_errors_and_active_edges() {
+ let _lock = env_lock();
+ let harness = setup("http://127.0.0.1:9");
+ let state_dir = harness.root.join("profile-store");
+ let store = AuthProfilesStore::new(&state_dir, false);
+
+ let token = AuthProfile::new_token("linear", "team", "lin-round20".to_string());
+ store
+ .upsert_profile(token.clone(), false)
+ .expect("insert token");
+ let inactive = store.load().expect("load inactive token");
+ assert!(!inactive.active_profiles.contains_key("linear"));
+ store
+ .set_active_profile("linear", &token.id)
+ .expect("activate token");
+ assert_eq!(
+ store
+ .load()
+ .expect("load active")
+ .active_profiles
+ .get("linear"),
+ Some(&token.id)
+ );
+
+ let path = store.path().to_path_buf();
+ let now = Utc::now().to_rfc3339();
+ std::fs::write(
+ &path,
+ serde_json::to_string_pretty(&json!({
+ "schema_version": 1,
+ "updated_at": now,
+ "active_profiles": { "github": "legacy-oauth", "token": "legacy-token" },
+ "profiles": {
+ "legacy-token": {
+ "provider": "token",
+ "profile_name": "plain",
+ "kind": "token",
+ "token": "plain-secret",
+ "metadata": { "k": "v" },
+ "created_at": "bad-created",
+ "updated_at": "bad-updated"
+ },
+ "legacy-oauth": {
+ "provider": "github",
+ "profile_name": "oauth",
+ "kind": "oauth",
+ "access_token": "plain-access",
+ "refresh_token": "plain-refresh",
+ "id_token": "",
+ "expires_at": null,
+ "token_type": "Bearer",
+ "scope": "repo",
+ "metadata": {},
+ "created_at": "2026-05-29T00:00:00Z",
+ "updated_at": "2026-05-29T00:00:00Z"
+ }
+ }
+ }))
+ .expect("profile json"),
+ )
+ .expect("write legacy plaintext store");
+
+ let loaded = store.load().expect("load plaintext legacy profiles");
+ assert_eq!(
+ loaded
+ .profiles
+ .get("legacy-token")
+ .and_then(|profile| profile.token.as_deref()),
+ Some("plain-secret")
+ );
+ let oauth = loaded.profiles.get("legacy-oauth").expect("oauth loaded");
+ assert_eq!(oauth.kind, AuthProfileKind::OAuth);
+ assert_eq!(
+ oauth.token_set.as_ref().map(|tokens| (
+ tokens.access_token.as_str(),
+ tokens.refresh_token.as_deref(),
+ tokens.expires_at
+ )),
+ Some(("plain-access", Some("plain-refresh"), None))
+ );
+
+ let set_active_err = store
+ .set_active_profile("missing", "not-there")
+ .expect_err("missing active profile")
+ .to_string();
+ assert!(set_active_err.contains("Auth profile not found"));
+}
+
+#[tokio::test]
+async fn round20_memory_documents_files_and_envelopes_cover_success_and_failure_paths() {
+ let _lock = env_lock();
+ let harness = setup("http://127.0.0.1:9");
+ ensure_memory_seams(Arc::new(harness.config().await));
+
+ let init = memory_init(MemoryInitRequest {
+ jwt_token: Some("ignored-round20".to_string()),
+ })
+ .await
+ .expect("memory init")
+ .value
+ .data
+ .expect("init data");
+ assert!(init.initialized);
+ assert!(init.memory_dir.ends_with("/memory"));
+
+ ai_write_memory_file(WriteMemoryFileRequest {
+ relative_path: "notes/round20.md".to_string(),
+ content: "Round20 local file memory".to_string(),
+ })
+ .await
+ .expect("write memory file");
+ let read = ai_read_memory_file(ReadMemoryFileRequest {
+ relative_path: "notes/round20.md".to_string(),
+ })
+ .await
+ .expect("read memory file")
+ .value
+ .data
+ .expect("read data");
+ assert!(read.content.contains("local file memory"));
+ let traversal = ai_write_memory_file(WriteMemoryFileRequest {
+ relative_path: "../escape.md".to_string(),
+ content: "no".to_string(),
+ })
+ .await
+ .expect_err("traversal rejected");
+ assert!(traversal.contains("path traversal"));
+ let listed = ai_list_memory_files(ListMemoryFilesRequest {
+ relative_dir: "notes".to_string(),
+ })
+ .await
+ .expect("list notes")
+ .value
+ .data
+ .expect("list data");
+ assert_eq!(listed.files, vec!["round20.md"]);
+
+ // Use a deterministic namespace — random UUIDs can trigger PII detection.
+ let namespace = "round20-cov-test-ns".to_string();
+ let put = doc_put(PutDocParams {
+ namespace: namespace.clone(),
+ key: "launch-note".to_string(),
+ title: "Launch Note".to_string(),
+ content: "The Calypso launch depends on QA, design, and release owners.".to_string(),
+ source_type: "note".to_string(),
+ priority: "high".to_string(),
+ tags: vec!["round20".to_string()],
+ metadata: json!({"round": 20}),
+ category: "core".to_string(),
+ session_id: Some("session-round20".to_string()),
+ document_id: Some("doc-round20".to_string()),
+ })
+ .await
+ .expect("put doc")
+ .value;
+ assert_eq!(put.document_id, "doc-round20");
+
+ let docs = doc_list(None)
+ .await
+ .expect("doc list all")
+ .value
+ .get("documents")
+ .and_then(Value::as_array)
+ .cloned()
+ .expect("documents");
+ assert!(docs.iter().any(|doc| doc["documentId"] == "doc-round20"));
+ let namespaces = namespace_list().await.expect("namespace list").value;
+ assert!(namespaces.contains(&namespace));
+
+ let query = context_query(QueryNamespaceParams {
+ namespace: namespace.clone(),
+ query: "Calypso QA".to_string(),
+ limit: Some(3),
+ })
+ .await
+ .expect("context query")
+ .value;
+ assert!(query.contains("Calypso") || query.contains("launch"));
+ let recall = context_recall(RecallNamespaceParams {
+ namespace: namespace.clone(),
+ limit: Some(3),
+ })
+ .await
+ .expect("context recall")
+ .value;
+ assert!(recall.as_deref().unwrap_or_default().contains("Calypso"));
+
+ let envelope_docs = memory_list_documents(ListDocumentsRequest {
+ namespace: Some(namespace.clone()),
+ })
+ .await
+ .expect("memory list documents")
+ .value
+ .data
+ .expect("list documents data");
+ assert_eq!(envelope_docs.count, 1);
+ let envelope_namespaces = memory_list_namespaces(EmptyRequest {})
+ .await
+ .expect("memory namespaces")
+ .value
+ .data
+ .expect("namespaces data");
+ assert!(envelope_namespaces.namespaces.contains(&namespace));
+
+ let hidden_context = memory_query_namespace(QueryNamespaceRequest {
+ namespace: namespace.clone(),
+ query: "Calypso".to_string(),
+ include_references: Some(false),
+ document_ids: Some(vec!["doc-round20".to_string()]),
+ limit: Some(1),
+ max_chunks: Some(2),
+ })
+ .await
+ .expect("query namespace envelope")
+ .value
+ .data
+ .expect("query namespace data");
+ assert!(hidden_context.context.is_none());
+ assert!(hidden_context.llm_context_message.is_some());
+
+ let recall_context = memory_recall_context(RecallContextRequest {
+ namespace: namespace.clone(),
+ include_references: Some(true),
+ limit: None,
+ max_chunks: Some(1),
+ })
+ .await
+ .expect("recall context envelope")
+ .value
+ .data
+ .expect("recall context data");
+ assert!(recall_context.llm_context_message.is_some());
+
+ let memories = memory_recall_memories(RecallMemoriesRequest {
+ namespace: namespace.clone(),
+ min_retention: Some(0.0),
+ as_of: Some(0.0),
+ limit: Some(1),
+ max_chunks: None,
+ top_k: Some(1),
+ })
+ .await
+ .expect("recall memories")
+ .value
+ .data
+ .expect("memories data");
+ assert!(!memories.memories.is_empty());
+
+ let deleted =
+ memory_delete_document(openhuman_core::openhuman::memory::DeleteDocumentRequest {
+ namespace: namespace.clone(),
+ document_id: "doc-round20".to_string(),
+ })
+ .await
+ .expect("delete document envelope")
+ .value
+ .data
+ .expect("delete data");
+ assert!(deleted.deleted);
+ let second_delete = doc_delete(DeleteDocParams {
+ namespace: namespace.clone(),
+ document_id: "doc-round20".to_string(),
+ })
+ .await
+ .expect("direct delete missing")
+ .value;
+ assert_eq!(second_delete["deleted"], false);
+ let cleared = clear_namespace(ClearNamespaceParams { namespace })
+ .await
+ .expect("clear namespace")
+ .value;
+ assert!(cleared.cleared);
+
+ let _ = harness;
+}
+
+#[tokio::test]
+async fn round20_threads_fallback_title_delete_missing_and_welcome_noop_paths() {
+ let _lock = env_lock();
+ let harness = setup("http://127.0.0.1:9");
+
+ let created = thread_ops::thread_create_new(
+ openhuman_core::openhuman::memory::CreateConversationThreadRequest {
+ labels: None,
+ personality_id: None,
+ },
+ )
+ .await
+ .expect("create thread")
+ .value
+ .data
+ .expect("created data");
+
+ let user_message = openhuman_core::openhuman::memory::ConversationMessageRecord {
+ id: "round20-user-msg".to_string(),
+ content: "Please map the onboarding telemetry rollout across product analytics and QA."
+ .to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: Value::Null,
+ sender: "user".to_string(),
+ created_at: Utc::now().to_rfc3339(),
+ };
+ thread_ops::message_append(
+ openhuman_core::openhuman::memory::AppendConversationMessageRequest {
+ thread_id: created.id.clone(),
+ message: user_message,
+ },
+ )
+ .await
+ .expect("append user");
+
+ let fallback = thread_ops::thread_generate_title(
+ openhuman_core::openhuman::memory::GenerateConversationThreadTitleRequest {
+ thread_id: created.id.clone(),
+ assistant_message: None,
+ },
+ )
+ .await
+ .expect("fallback title")
+ .value
+ .data
+ .expect("fallback data");
+ assert!(!fallback.title.trim().is_empty());
+ assert_ne!(fallback.title, created.title);
+
+ let missing_update = thread_ops::message_update(
+ openhuman_core::openhuman::memory::UpdateConversationMessageRequest {
+ thread_id: created.id.clone(),
+ message_id: "missing-message".to_string(),
+ extra_metadata: Some(json!({"x": true})),
+ },
+ )
+ .await
+ .expect_err("missing message update fails");
+ assert!(missing_update.contains("message") || missing_update.contains("not found"));
+
+ let missing_delete = thread_ops::thread_delete(
+ openhuman_core::openhuman::memory::DeleteConversationThreadRequest {
+ thread_id: "missing-thread-round20".to_string(),
+ deleted_at: Utc::now().to_rfc3339(),
+ },
+ )
+ .await
+ .expect("missing thread delete is idempotent")
+ .value
+ .data
+ .expect("delete data");
+ assert!(!missing_delete.deleted);
+
+ std::fs::create_dir_all(harness.workspace_dir().join("session_raw")).expect("raw dir");
+ std::fs::write(
+ harness.workspace_dir().join("session_raw/ignore.jsonl"),
+ "{\"_meta\":{\"agent\":\"orchestrator\",\"thread_id\":\"t\"}}\n",
+ )
+ .expect("write non-welcome transcript");
+ let migration =
+ migrate_welcome_agent_artifacts(&harness.workspace_dir()).expect("noop migration");
+ assert_eq!(migration.threads_updated, 0);
+ assert_eq!(migration.transcripts_updated, 0);
+}
+
+fn write_fake_gh_round20(path: &PathBuf) {
+ let script = r#"#!/usr/bin/env bash
+set -euo pipefail
+if [[ "${1:-}" == "--version" ]]; then
+ echo "gh version 2.0.0"
+ exit 0
+fi
+if [[ "${1:-}" != "api" ]]; then
+ echo "unsupported gh command" >&2
+ exit 2
+fi
+case "${2:-}" in
+ repos/tinyhumansai/openhuman/commits\?*)
+ cat <<'JSON'
+[{"sha":"def456","commit":{"message":"Round20 commit fixture","author":{"name":"Ada","email":"[email protected]","date":"2026-05-29T00:00:00Z"},"committer":{"name":"Ada","email":"[email protected]","date":"2026-05-29T00:00:00Z"}}}]
+JSON
+ ;;
+ repos/tinyhumansai/openhuman/issues\?*)
+ cat <<'JSON'
+[{"number":20,"title":"Round20 issue","body":null,"state":"closed","user":null,"labels":[],"created_at":null,"updated_at":"2026-05-29T00:30:00Z","pull_request":null}]
+JSON
+ ;;
+ repos/tinyhumansai/openhuman/pulls\?*)
+ cat <<'JSON'
+[{"number":21,"title":"Round20 merged PR","body":null,"state":"closed","user":null,"labels":[],"created_at":null,"updated_at":"2026-05-29T01:00:00Z","merged_at":"2026-05-29T01:00:00Z","comments":0}]
+JSON
+ ;;
+ repos/tinyhumansai/openhuman/pulls/21)
+ cat <<'JSON'
+{"number":21,"title":"Round20 merged PR","body":null,"state":"closed","user":null,"labels":[],"created_at":null,"updated_at":"2026-05-29T01:00:00Z","merged_at":"2026-05-29T01:00:00Z","comments":0}
+JSON
+ ;;
+ repos/tinyhumansai/openhuman/issues/21/comments\?*)
+ cat <<'JSON'
+[]
+JSON
+ ;;
+ *)
+ echo "unexpected gh api path: ${2:-}" >&2
+ exit 3
+ ;;
+esac
+"#;
+ std::fs::write(path, script).expect("write fake gh");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = std::fs::metadata(path)
+ .expect("fake gh metadata")
+ .permissions();
+ perms.set_mode(0o755);
+ std::fs::set_permissions(path, perms).expect("chmod fake gh");
+ }
+}
diff --git a/tests/support/noop_memory.rs b/tests/support/noop_memory.rs
new file mode 100644
index 0000000000..b3cc13a9a5
--- /dev/null
+++ b/tests/support/noop_memory.rs
@@ -0,0 +1,87 @@
+//! A [`Memory`] that stores nothing, for integration targets that need one.
+//!
+//! Three targets build an `Agent` or a session that must be handed *a* memory
+//! and never read one back. They used to get it from the engine's factory with
+//! `backend: "none"` — an engine call whose entire purpose was to obtain
+//! something that does not store, and one of the last things keeping
+//! `tinymemory-core` on this crate's test critical path (openhuman#6161).
+//!
+//! It lives under `tests/support/` and is pulled in with `#[path]` because
+//! `memory::test_support::noop_memory` is `pub(crate)`: a `tests/*.rs` target
+//! links this crate as an ordinary dependency and cannot see crate-private
+//! items, however they are declared.
+
+#![allow(dead_code)]
+
+use std::sync::Arc;
+
+use openhuman_core::openhuman::memory::api::recall::RecallOpts;
+use openhuman_core::openhuman::memory::api::types::{
+ MemoryCategory, MemoryEntry, NamespaceSummary,
+};
+use openhuman_core::openhuman::memory::Memory;
+
+/// Accepts every write and answers empty.
+#[derive(Debug)]
+pub struct NoopMemory;
+
+#[async_trait::async_trait]
+impl Memory for NoopMemory {
+ fn name(&self) -> &str {
+ "none"
+ }
+
+ async fn store(
+ &self,
+ _namespace: &str,
+ _key: &str,
+ _content: &str,
+ _category: MemoryCategory,
+ _session_id: Option<&str>,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ async fn recall(
+ &self,
+ _query: &str,
+ _limit: usize,
+ _opts: RecallOpts<'_>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ Ok(Vec::new())
+ }
+
+ async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result<Option<MemoryEntry>> {
+ Ok(None)
+ }
+
+ async fn list(
+ &self,
+ _namespace: Option<&str>,
+ _category: Option<&MemoryCategory>,
+ _session_id: Option<&str>,
+ ) -> anyhow::Result<Vec<MemoryEntry>> {
+ Ok(Vec::new())
+ }
+
+ async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result<bool> {
+ Ok(false)
+ }
+
+ async fn namespace_summaries(&self) -> anyhow::Result<Vec<NamespaceSummary>> {
+ Ok(Vec::new())
+ }
+
+ async fn count(&self) -> anyhow::Result<usize> {
+ Ok(0)
+ }
+
+ async fn health_check(&self) -> bool {
+ true
+ }
+}
+
+/// The shorthand the `backend: "none"` call sites use.
+pub fn noop_memory() -> Arc<dyn Memory> {
+ Arc::new(NoopMemory)
+}