The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge remote-tracking branch 'pr7521/main' into mcp-embed-teardown-7513
Steven Enamakeldae811171a4d
diff --cc Cargo.lockindex 96d20e3891,c6a6d16e26..fac868d164--- a/Cargo.lock+++ b/Cargo.lock@@@ -7095,10 -9534,41 +9534,41 @@@ dependencies ="url",]+ [[package]]+ name = "tinymcp"-version = "0.18.7"++version = "0.19.1"+ dependencies = [+ "base64 0.23.1",+ "dirs 7.0.0",+ "futures-util",+ "parking_lot",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "sha2 0.11.0",+ "thiserror 2.0.20",+ "tinybox-bus 0.1.36 (git+https://github.com/tinyhumansai/tinybox?tag=v0.1.36)",+ "tinybus",+ "tinybus-module",+ "tinymcp-bus",+ "tinystoragedrivers-busproxy",+ "tinystoragedrivers-client",+ "tinystoragedrivers-core",+ "tinystoragedrivers-secrets",+ "tinytools",+ "tinytools-std",+ "tokio",+ "tracing",+ "url",+ "urlencoding",+ "uuid",+ ]+[[package]]name = "tinymcp-bus"- version = "0.14.3"-version = "0.18.7"++version = "0.19.1"dependencies = [+ "base64 0.23.1","schemars","serde","serde_json",diff --cc crates/openhuman-app/Cargo.lockindex 6e76f03b35,c7bd6c377c..bbdacf4c89--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -7099,8 -7169,9 +7169,9 @@@ dependencies =[[package]]name = "tinymcp-bus"- version = "0.14.3"-version = "0.18.7"++version = "0.19.1"dependencies = [+ "base64 0.23.1","schemars 1.2.2","serde","serde_json",diff --cc crates/openhuman-core/src/mcp/agent_cleanup.rsindex 866484b20b,0000000000..5229cd96d0mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/agent_cleanup.rs+++ b/crates/openhuman-core/src/mcp/agent_cleanup.rs@@@ -1,65 -1,0 +1,49 @@@+//! Captured cleanup of an agent's existing configured module object.+use super::*;++/// A retired agent's original MCP owner and its retryable close receipts.+/// Capturing this handle never creates a client or loads a module.+#[derive(Clone)]+pub struct AgentMcpCleanup {+ directory: PathBuf,+ client: Arc<McpConfiguredClient>,+}++/// Retire the existing configured client for this exact agent directory.+/// An absent entry requires no cleanup and leaves the module loader untouched.+pub fn take_agent_cleanup(workspace: &std::path::Path, agent_id: &str) -> Option<AgentMcpCleanup> {- let directory = workspace.join("agents").join(agent_id);- let clients = CLIENTS- .get()?- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let client = Arc::clone(clients.get(&directory)?);- client.retiring.store(true, Ordering::Release);++ let directory = super::lifecycle::client_key(&workspace.join("agents").join(agent_id));++ let client = super::lifecycle::table().retire(&directory)?;+ Some(AgentMcpCleanup { directory, client })+}++impl AgentMcpCleanup {+ /// Close the original object and evict it only after confirmed cleanup.+ /// The whole attempt, including lock acquisition and bus calls, has a+ /// 30-second deadline. Timeout returns `TransportFailed`; cancellation or+ /// error retains the same client and transition receipt for explicit retry.+ pub async fn finish(&self) -> Result<(), ModuleCallError> {+ tokio::time::timeout(TRANSITION_TIMEOUT, self.client.close())+ .await+ .map_err(|_| ModuleCallError::TransportFailed)??;+ self.evict();+ Ok(())+ }++ /// Finish an unused client without starting an asynchronous executor.+ /// An accepted call holding the lifecycle lock requires asynchronous drain.+ pub fn finish_if_idle(&self) -> bool {+ let Ok(state) = self.client.state.try_lock() else {+ return false;+ };- if !matches!(*state, State::Closed) {++ if !state.is_closed() {+ return false;+ }+ self.evict();+ true+ }++ fn evict(&self) {- let Some(clients) = CLIENTS.get() else {- return;- };- let mut clients = clients- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if clients- .get(&self.directory)- .is_some_and(|current| Arc::ptr_eq(current, &self.client))- {- clients.remove(&self.directory);- }++ super::lifecycle::table().evict(&self.directory, &self.client);+ }+}diff --cc crates/openhuman-core/src/mcp/host_cleanup.rsindex 3e9ff51749,0000000000..dfb6c62016mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/host_cleanup.rs+++ b/crates/openhuman-core/src/mcp/host_cleanup.rs@@@ -1,140 -1,0 +1,133 @@@+//! Process-local host cleanup fencing, also used when MCP is compiled out.- use crate::modules::client::ModuleCallError;+use std::{- collections::HashMap,+ path::PathBuf,- sync::{- atomic::{AtomicBool, Ordering},- Arc, Mutex, OnceLock,- },++ sync::{Arc, OnceLock},+};++use tinybus::module::ModuleCallError;++use tinymcp_bus::client_lifecycle::{CleanupReservation, ClientTable};+- pub(super) type CleanupAction = Arc<dyn Fn() -> bool + Send + Sync>;-- #[derive(Default)]- pub(super) struct CleanupReservation {- pub(super) after_close: Mutex<Option<CleanupAction>>,- pub(super) host_completion_pending: AtomicBool,++#[cfg(feature = "mcp")]++type CleanupClient = super::module_client::McpConfiguredClient;++#[cfg(not(feature = "mcp"))]++pub(super) struct CleanupClient;++#[cfg(not(feature = "mcp"))]++impl tinymcp_bus::client_lifecycle::Retire for CleanupClient {++ fn mark_retiring(&self) {}++ fn is_retiring(&self) -> bool {++ false++ }++}++static CLIENTS: OnceLock<ClientTable<CleanupClient>> = OnceLock::new();++pub(super) fn table() -> &'static ClientTable<CleanupClient> {++ CLIENTS.get_or_init(ClientTable::new)+}+- pub(super) static CLEANUP_RESERVATIONS: OnceLock<Mutex<HashMap<PathBuf, Arc<CleanupReservation>>>> =- OnceLock::new();++pub(super) fn directory_key(directory: &std::path::Path) -> PathBuf {++ #[cfg(feature = "mcp")]++ {++ super::module_client::lifecycle::client_key(directory)++ }++ #[cfg(not(feature = "mcp"))]++ {++ let mut missing = Vec::new();++ let mut ancestor = directory;++ loop {++ if let Ok(real) = ancestor.canonicalize() {++ return missing++ .iter()++ .rev()++ .fold(real, |path, part| path.join(part));++ }++ match (ancestor.parent(), ancestor.file_name()) {++ (Some(parent), Some(name)) => {++ missing.push(name.to_owned());++ ancestor = parent;++ }++ _ => return directory.to_path_buf(),++ }++ }++ }++}+- #[cfg(not(feature = "mcp"))]+pub(super) fn directory_pending(workspace: &std::path::Path, agent_id: &str) -> bool {- CLEANUP_RESERVATIONS.get().is_some_and(|reservations| {- reservations- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .contains_key(&workspace.join("agents").join(agent_id))- })++ table().close_pending(&directory_key(&workspace.join("agents").join(agent_id)))+}++/// Run captured cleanup on the process module executor when modules are enabled.+/// Without modules, the caller must keep its current Tokio runtime alive.+/// This creates no configured client and loads no MCP artifact.+pub fn spawn_agent_cleanup<F>(+ future: F,+) -> Result<tokio::task::JoinHandle<F::Output>, ModuleCallError>+where+ F: std::future::Future + Send + 'static,+ F::Output: Send + 'static,+{+ #[cfg(feature = "modules")]+ {- crate::modules::host::spawn_cleanup(future).map_err(|_| ModuleCallError::TransportFailed)++ crate::modules::runtime::spawn_cleanup(future).map_err(|_| ModuleCallError::TransportFailed)+ }+ #[cfg(not(feature = "modules"))]+ {+ tokio::runtime::Handle::try_current()+ .map(|handle| handle.spawn(future))+ .map_err(|_| ModuleCallError::Unavailable)+ }+}++/// A process-local directory reservation with no runtime guard or callback.+/// Dropping the token retains the fence; only confirmed host completion clears it.+#[derive(Clone)]+pub struct AgentDirectoryCleanup {+ directory: PathBuf,+ reservation: Arc<CleanupReservation>,+}++/// Reserve an agent's directory until host-owned cleanup succeeds.+/// This never creates a client or loads a module.+pub fn reserve_agent_directory(+ workspace: &std::path::Path,+ agent_id: &str,+) -> AgentDirectoryCleanup {- let directory = workspace.join("agents").join(agent_id);- let mut reservations = CLEANUP_RESERVATIONS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let reservation = Arc::clone(- reservations- .entry(directory.clone())- .or_insert_with(|| Arc::new(CleanupReservation::default())),- );- reservation- .host_completion_pending- .store(true, Ordering::Release);++ let directory = directory_key(&workspace.join("agents").join(agent_id));++ let reservation = table().reserve_host_completion(&directory);+ AgentDirectoryCleanup {+ directory,+ reservation,+ }+}++impl AgentDirectoryCleanup {+ /// Release this exact reservation after module close and host purge succeed.+ /// An independently registered canonical callback keeps its own reservation.+ pub fn complete(&self) {- let after_close = self- .reservation- .after_close- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let mut reservations = CLEANUP_RESERVATIONS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if reservations- .get(&self.directory)- .is_some_and(|current| Arc::ptr_eq(current, &self.reservation))- {- self.reservation- .host_completion_pending- .store(false, Ordering::Release);- if after_close.is_none() {- reservations.remove(&self.directory);- }- }++ table().complete_host_cleanup(&self.directory, &self.reservation);+ }+}++/// An opaque cleanup handle for a build with no MCP client capability.+/// Such a build cannot create the handle or hold MCP resources.+#[cfg(not(feature = "mcp"))]+#[derive(Clone)]+pub struct AgentMcpCleanup {+ _unconstructible: (),+}++#[cfg(not(feature = "mcp"))]+impl AgentMcpCleanup {+ /// There are no MCP resources in this compiled-out capability.+ pub async fn finish(&self) -> Result<(), ModuleCallError> {+ Ok(())+ }++ /// There are no MCP resources to drain or retire.+ pub fn finish_if_idle(&self) -> bool {+ true+ }+}++/// A build without MCP cannot contain a configured MCP client.+#[cfg(not(feature = "mcp"))]+pub fn take_agent_cleanup(_workspace: &std::path::Path, _id: &str) -> Option<AgentMcpCleanup> {+ None+}diff --cc crates/openhuman-core/src/mcp/module_client.rsindex dc46de5004,3c03fbac08..3c4a7b1b1e--- a/crates/openhuman-core/src/mcp/module_client.rs+++ b/crates/openhuman-core/src/mcp/module_client.rs@@@ -120,15 -93,115 +93,12 @@@ pub(crate) trait McpModulePort: Send +}}-struct TinyMcpPort {- root: ModuleClient,-}--#[async_trait]-impl McpModulePort for TinyMcpPort {- async fn open_configured(- &self,- data_dir: &str,- config: &McpClientConfig,- ) -> Result<OpenConfiguredResponse, ModuleCallError> {- self.root- .call_confidential(- MODULE,- names::methods::OPEN_CONFIGURED,- (OpenConfiguredRequest {- data_dir: data_dir.to_owned(),- client: config.clone(),- },),- )- .await- }-- async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError> {- self.root- .call(MODULE, names::methods::CLOSE, (data_dir.to_owned(),))- .await- }-- async fn transition_status(- &self,- transition_id: &str,- ) -> Result<TransitionStatus, ModuleCallError> {- self.root- .call(- MODULE,- names::methods::TRANSITION_STATUS,- (transition_id.to_owned(),),- )- .await- }-- async fn call_object(- &self,- object_path: &str,- member: &str,- args: Value,- confidential: bool,- ) -> Result<Value, ModuleCallError> {- #[cfg(feature = "modules")]- {- let object = self.root.object_client(MODULE, object_path).await?;- if confidential {- object.call_confidential(member, args).await- } else {- object.call(member, args).await- }- }- #[cfg(not(feature = "modules"))]- {- let _ = (object_path, member, args, confidential);- Err(ModuleCallError::Unavailable)- }- }+#[path = "module_port.rs"]+mod module_port;+use module_port::TinyMcpPort;- #[path = "cached_cleanup.rs"]- mod cached_cleanup;- async fn prepare_agent_tools(- &self,- request: PrepareAgentToolsRequest,- ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {- self.root- .call(MODULE, names::methods::PREPARE_AGENT_TOOLS, (request,))- .await- }-- async fn validate_server_arguments(- &self,- request: ValidateServerArgumentsRequest,- ) -> Result<ServerArgumentsValidation, ModuleCallError> {- self.root- .call_confidential(- MODULE,- names::methods::VALIDATE_SERVER_ARGUMENTS,- (request,),- )- .await- }-- async fn normalize_tool_arguments(- &self,- arguments: Option<Value>,- ) -> Result<Map<String, Value>, ModuleCallError> {- self.root- .call_confidential(- MODULE,- names::methods::NORMALIZE_TOOL_ARGUMENTS,- (arguments,),- )- .await- }--- async fn transform_text(- &self,- request: tinymcp_bus::TransformTextRequest,- ) -> Result<String, ModuleCallError> {- self.root- .call_confidential(MODULE, names::methods::TRANSFORM_TEXT, (request,))- .await- }-}+#[path = "agent_cleanup.rs"]+pub(crate) mod agent_cleanup;/// One workspace's serialized TinyMCP lifecycle and private object proxy.pub(crate) struct McpConfiguredClient {@@@ -138,186 -211,9 +108,9 @@@retiring: AtomicBool,}- impl McpConfiguredClient {- /// The process-owned configured object for this workspace. Entries remain- /// reachable until `close` confirms cleanup; workspace/config switching is- /// serialized by the client itself.- pub(crate) fn for_config(config: &Config) -> Result<Arc<Self>, ModuleCallError> {- if SHUTTING_DOWN.load(Ordering::Acquire) {- ModuleClient::report_unavailable(MODULE);- return Err(ModuleCallError::Unavailable);- }- if !config.modules.enabled {- ModuleClient::report_unavailable(MODULE);- return Err(ModuleCallError::Unavailable);- }- if current_agent_context_is_removed() {- ModuleClient::report_unavailable(MODULE);- return Err(ModuleCallError::Unavailable);- }- let data_dir = crate::core::runtime::agent_scope_dir(config);- if Self::cleanup_pending(&data_dir) {- return Err(ModuleCallError::Unavailable);- }- #[cfg(test)]- {- let mut hook = AFTER_CONTEXT_CHECK- .get_or_init(|| Mutex::new(None))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if hook- .as_ref()- .is_some_and(|(expected, _)| expected == &data_dir)- {- if let Some((_, sender)) = hook.take() {- let _ = sender.send(());- }- }- }- let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));- let mut clients = clients- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- // The cleanup reservation can be installed after the first check but- // before this cache lock is acquired. Recheck before creating a client.- if current_agent_context_is_removed() || Self::cleanup_pending(&data_dir) {- ModuleClient::report_unavailable(MODULE);- return Err(ModuleCallError::Unavailable);- }- if let Some(client) = clients.get(&data_dir) {- if client.retiring.load(Ordering::Acquire) {- return Err(ModuleCallError::Unavailable);- }- return Ok(Arc::clone(client));- }- let client = Arc::new(Self::new(&data_dir, config)?);- clients.insert(data_dir, Arc::clone(&client));- Ok(client)- }-- /// A snapshot of configured workspaces currently retained by the host.- /// The supervisor only drains open objects; it never creates a workspace.- pub(crate) fn open_clients() -> Vec<(PathBuf, Arc<Self>)> {- CLIENTS- .get()- .map(|clients| {- clients- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .iter()- .map(|(workspace, client)| (workspace.clone(), Arc::clone(client)))- .collect()- })- .unwrap_or_default()- }-- /// Drain observations from the module-owned supervisor for an open child.- /// An object that is opening or closing is skipped and will be revisited- /// on the next host poll.- pub(crate) async fn drain_supervisor_events(- &self,- limit: usize,- ) -> Result<Option<SupervisorBatch>, ModuleCallError> {- let state = self.state.lock().await;- if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {- return Err(ModuleCallError::Unavailable);- }- let State::Open(object) = &*state else {- return Ok(None);- };- let args = serde_json::to_value((limit,)).map_err(|_| ModuleCallError::ModuleFault)?;- let reply = self- .port- .call_object(- &object.object_path,- names::methods::DRAIN_SUPERVISOR_EVENTS,- args,- false,- )- .await?;- serde_json::from_value(reply)- .map(Some)- .map_err(|_| ModuleCallError::ModuleFault)- }-- /// Register this runtime's cleanup. The flag is reset by the drained hook,- /// so a later embedded-runtime start can register a fresh one.- pub(crate) fn register_shutdown_hook() {- if SHUTDOWN_REGISTERED.swap(true, Ordering::AcqRel) {- return;- }- SHUTTING_DOWN.store(false, Ordering::Release);- crate::core::shutdown::register(|| async {- SHUTTING_DOWN.store(true, Ordering::Release);- let clients = CLIENTS- .get()- .map(|clients| {- clients- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .values()- .cloned()- .collect::<Vec<_>>()- })- .unwrap_or_default();- for client in clients {- if client.retiring.load(Ordering::Acquire) {- let data_dir = PathBuf::from(&client.data_dir);- let reservation = Self::reservation_for(&data_dir);- Self::close_retired_client(data_dir, client, reservation).await;- } else if let Err(error) = client.close().await {- tracing::warn!(?error, "[mcp] workspace cleanup is still pending");- }- }- Self::retry_orphaned_cleanups();- SHUTDOWN_REGISTERED.store(false, Ordering::Release);- });- }-- pub(crate) fn new(- data_dir: &std::path::Path,- config: &Config,- ) -> Result<Self, ModuleCallError> {- let data_dir = data_dir- .to_str()- .ok_or(ModuleCallError::IncompatibleContract)?- .to_owned();- Ok(Self::with_port(- data_dir,- Box::new(TinyMcpPort::new(ModuleClient::new(config.clone()))),- ))- }-- #[cfg(test)]- pub(crate) fn install_test_port(- config: &Config,- port: Box<dyn McpModulePort>,- ) -> Result<Arc<Self>, ModuleCallError> {- let data_dir = crate::core::runtime::agent_scope_dir(config);- let client = Arc::new(Self::with_port(- data_dir- .to_str()- .ok_or(ModuleCallError::IncompatibleContract)?- .to_owned(),- port,- ));- let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));- clients- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .insert(data_dir, Arc::clone(&client));- Ok(client)- }-- fn with_port(data_dir: String, port: Box<dyn McpModulePort>) -> Self {- Self {- data_dir,- port,- state: tokio::sync::Mutex::new(State::Closed),- retiring: AtomicBool::new(false),- }- }-mod lifecycle;++pub(super) mod lifecycle;+ impl McpConfiguredClient {/// Calls one member on this workspace's private configured object.pub(crate) async fn call<R: DeserializeOwned>(&self,@@@ -700,6 -531,12 +428,16 @@@ fn current_agent_context_is_removed() -#[path = "module_client_tests.rs"]mod tests;+ impl Retire for McpConfiguredClient {+ fn mark_retiring(&self) {+ self.retiring.store(true, Ordering::Release);+ }++ fn is_retiring(&self) -> bool {+ self.retiring.load(Ordering::Acquire)+ }+ }+++#[cfg(all(test, feature = "modules"))]+#[path = "module_client_owner_tests.rs"]+mod owner_tests;diff --cc crates/openhuman-core/src/mcp/module_client/lifecycle.rsindex 0000000000,78d95ac1e8..9234dd0ffemode 000000,100644..100644--- a/crates/openhuman-core/src/mcp/module_client/lifecycle.rs+++ b/crates/openhuman-core/src/mcp/module_client/lifecycle.rs@@@ -1,0 -1,274 +1,269 @@@+ //! Configured-client cache admission, retirement and acknowledged cleanup.+ //!+ //! The cache, cleanup reservations and open/close receipt machine live in+ //! `tinymcp_bus::client_lifecycle`; this adapter supplies the host policy+ //! (module gate, removed-agent context, shutdown) and performs the bus calls.++ use super::*;-use std::sync::OnceLock;+ use tinymcp_bus::client_lifecycle::{AdmitError, CleanupReservation, ClientTable};+-static CLIENTS: OnceLock<ClientTable<McpConfiguredClient>> = OnceLock::new();-+ pub(super) fn table() -> &'static ClientTable<McpConfiguredClient> {- CLIENTS.get_or_init(ClientTable::new)++ super::super::host_cleanup::table()+ }++ impl McpConfiguredClient {+ /// The process-owned configured object for this workspace. Entries remain+ /// reachable until `close` confirms cleanup; workspace/config switching is+ /// serialized by the client itself.+ pub(crate) fn for_config(config: &Config) -> Result<Arc<Self>, ModuleCallError> {+ if SHUTTING_DOWN.load(Ordering::Acquire) {+ crate::modules::report::unavailable(MODULE);+ return Err(ModuleCallError::Unavailable);+ }+ if !config.modules.enabled {+ crate::modules::report::unavailable(MODULE);+ return Err(ModuleCallError::Unavailable);+ }+ if current_agent_context_is_removed() {+ crate::modules::report::unavailable(MODULE);+ return Err(ModuleCallError::Unavailable);+ }+ let data_dir = crate::core::runtime::agent_scope_dir(config);+ let key = client_key(&data_dir);+ // The table rechecks removal and pending cleanup under its lock, so a+ // reservation installed after the first check cannot be bypassed.+ table()+ .admit(&key, current_agent_context_is_removed, || {+ Self::new(&data_dir, config).map(Arc::new)+ })+ .map_err(|error| match error {+ AdmitError::Create(error) => error,+ _ => {+ crate::modules::report::unavailable(MODULE);+ ModuleCallError::Unavailable+ }+ })+ }++ /// A snapshot of configured workspaces currently retained by the host.+ /// The supervisor only drains open objects; it never creates a workspace.+ pub(crate) fn open_clients() -> Vec<(PathBuf, Arc<Self>)> {+ table().snapshot()+ }++ /// Drain observations from the module-owned supervisor for an open child.+ /// An object that is opening or closing is skipped and will be revisited+ /// on the next host poll.+ pub(crate) async fn drain_supervisor_events(+ &self,+ limit: usize,+ ) -> Result<Option<SupervisorBatch>, ModuleCallError> {+ let state = self.state.lock().await;+ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {+ return Err(ModuleCallError::Unavailable);+ }+ let Some(object) = state.open_object() else {+ return Ok(None);+ };+ let args = serde_json::to_value((limit,)).map_err(|_| ModuleCallError::ModuleFault)?;+ let reply = self+ .port+ .call_object(+ &object.object_path,+ names::methods::DRAIN_SUPERVISOR_EVENTS,+ args,+ false,+ )+ .await?;+ serde_json::from_value(reply)+ .map(Some)+ .map_err(|_| ModuleCallError::ModuleFault)+ }++ /// Register this runtime's cleanup. The flag is reset by the drained hook,+ /// so a later embedded-runtime start can register a fresh one.+ pub(crate) fn register_shutdown_hook() {+ if SHUTDOWN_REGISTERED.swap(true, Ordering::AcqRel) {+ return;+ }+ SHUTTING_DOWN.store(false, Ordering::Release);+ crate::core::shutdown::register(|| async {+ SHUTTING_DOWN.store(true, Ordering::Release);+ for (data_dir, client) in table().snapshot() {+ if client.retiring.load(Ordering::Acquire) {+ let reservation = table().reservation_for(&data_dir);+ Self::close_retired_client(data_dir, client, reservation).await;+ } else if let Err(error) = client.close().await {+ tracing::warn!(?error, "[mcp] workspace cleanup is still pending");+ }+ }+ table().retry_orphaned();+ SHUTDOWN_REGISTERED.store(false, Ordering::Release);+ });+ }++ pub(crate) fn new(+ data_dir: &std::path::Path,+ config: &Config,+ ) -> Result<Self, ModuleCallError> {+ let data_dir = data_dir+ .to_str()+ .ok_or(ModuleCallError::IncompatibleContract)?+ .to_owned();+ Ok(Self::with_port(+ data_dir,- Box::new(TinyMcpPort {- root: crate::modules::client(config.clone()),- }),++ Box::new(TinyMcpPort::new(crate::modules::client(config.clone()))),+ ))+ }++ #[cfg(test)]+ pub(crate) fn install_test_port(+ config: &Config,+ port: Box<dyn McpModulePort>,+ ) -> Result<Arc<Self>, ModuleCallError> {+ let data_dir = crate::core::runtime::agent_scope_dir(config);+ let client = Arc::new(Self::with_port(+ data_dir+ .to_str()+ .ok_or(ModuleCallError::IncompatibleContract)?+ .to_owned(),+ port,+ ));+ table().insert(client_key(&data_dir), Arc::clone(&client));+ Ok(client)+ }++ pub(super) fn with_port(data_dir: String, port: Box<dyn McpModulePort>) -> Self {+ Self {+ data_dir,+ port,+ state: tokio::sync::Mutex::new(ConfiguredLifecycle::new()),+ retiring: AtomicBool::new(false),+ }+ }++ #[cfg(test)]+ pub(crate) fn with_test_port(data_dir: String, port: Box<dyn McpModulePort>) -> Self {+ Self::with_port(data_dir, port)+ }++ /// Close an already-open agent-scoped client without creating one. A+ /// failed close remains in the cache, marked unavailable, so shutdown or+ /// a later cleanup attempt can retry the module's retained transition.+ pub(crate) async fn close_agent_data_dir(data_dir: &std::path::Path) -> bool {+ let key = client_key(data_dir);+ let reservation = table().reservation_for(&key);+ let Some(client) = table().retire(&key) else {+ return table().finish_cleanup(&key, None, &reservation);+ };+ if let Some(cleaned) = Self::finish_if_closed(&key, &client, &reservation) {+ return cleaned;+ }+ Self::close_retired_client(key, client, reservation).await+ }++ /// Marks the exact cached client unavailable before scheduling cleanup.+ /// If no Tokio runtime is active, the retired client remains cached for the+ /// registered shutdown hook to close later.+ pub(crate) fn schedule_agent_close_data_dir(data_dir: &std::path::Path) {+ let key = client_key(data_dir);+ let reservation = table().reservation_for(&key);+ let Some(client) = table().retire(&key) else {+ table().finish_cleanup(&key, None, &reservation);+ return;+ };+ if Self::finish_if_closed(&key, &client, &reservation).is_some() {+ return;+ }+ Self::spawn_close(key, client, reservation, "agent client close");+ }++ /// Retires the exact scoped client and runs `after_close` only after the+ /// module acknowledges its close. The path remains unavailable until the+ /// callback succeeds, so a replacement cannot reuse files being purged.+ pub(crate) fn schedule_agent_close_and_cleanup(+ data_dir: &std::path::Path,+ after_close: CleanupAction,+ ) {+ let key = client_key(data_dir);+ let reservation = table().reservation_with_action(&key, after_close);+ let Some(client) = table().retire(&key) else {+ if !table().finish_cleanup(&key, None, &reservation) {+ tracing::warn!("[mcp] agent cleanup remains pending for retry");+ }+ return;+ };+ if Self::finish_if_closed(&key, &client, &reservation).is_some() {+ return;+ }+ Self::spawn_close(key, client, reservation, "agent close and cleanup");+ }++ fn spawn_close(+ key: PathBuf,+ client: Arc<Self>,+ reservation: Arc<CleanupReservation>,+ what: &'static str,+ ) {+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {+ return;+ };+ runtime.spawn(async move {+ if !Self::close_retired_client(key, client, reservation).await {+ tracing::warn!("[mcp] {what} remains pending for retry");+ }+ });+ }++ pub(crate) fn agent_close_pending(data_dir: &std::path::Path) -> bool {+ table().close_pending(&client_key(data_dir))+ }++ fn finish_if_closed(+ data_dir: &std::path::Path,+ client: &Arc<Self>,+ reservation: &Arc<CleanupReservation>,+ ) -> Option<bool> {+ table().finish_if_closed(data_dir, client, reservation, || {+ client.state.try_lock().is_ok_and(|state| state.is_closed())+ })+ }++ pub(super) async fn close_retired_client(+ data_dir: PathBuf,+ client: Arc<Self>,+ reservation: Arc<CleanupReservation>,+ ) -> bool {+ match client.close().await {+ Ok(()) => table().finish_cleanup(&data_dir, Some(&client), &reservation),+ Err(error) => {+ tracing::warn!(?error, "[mcp] agent client close remains pending");+ false+ }+ }+ }+ }++ /// The table key for an agent data directory, stable across spellings of the+ /// same folder (symlinks, `..`, case on case-insensitive volumes). The longest+ /// existing ancestor is canonicalized and the rest re-appended, so a directory+ /// that a purge has already removed keeps the key it was admitted under.-fn client_key(data_dir: &std::path::Path) -> PathBuf {++pub(crate) fn client_key(data_dir: &std::path::Path) -> PathBuf {+ let mut missing = Vec::new();+ let mut ancestor = data_dir;+ loop {+ if let Ok(real) = ancestor.canonicalize() {+ return missing+ .iter()+ .rev()+ .fold(real, |path, part| path.join(part));+ }+ match (ancestor.parent(), ancestor.file_name()) {+ (Some(parent), Some(name)) => {+ missing.push(name.to_owned());+ ancestor = parent;+ }+ _ => return data_dir.to_path_buf(),+ }+ }+ }diff --cc crates/openhuman-core/src/mcp/module_client_cleanup_tests.rsindex 120643bfa6,0000000000..1cdb2fdcbdmode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/module_client_cleanup_tests.rs+++ b/crates/openhuman-core/src/mcp/module_client_cleanup_tests.rs@@@ -1,418 -1,0 +1,127 @@@+use super::*;+- #[tokio::test]- async fn agent_cleanup_closes_only_the_cached_agent_and_keeps_siblings_open() {- let target_workspace = tempfile::tempdir().expect("target workspace");- let sibling_workspace = tempfile::tempdir().expect("sibling workspace");- let mut target_config = Config::default();- target_config.workspace_dir = target_workspace.path().to_path_buf();- target_config.modules.enabled = true;- let mut sibling_config = Config::default();- sibling_config.workspace_dir = sibling_workspace.path().to_path_buf();- sibling_config.modules.enabled = true;-- let target_port = FakePort::default();- let target_closed = Arc::clone(&target_port.closed);- let target = McpConfiguredClient::install_test_port(&target_config, Box::new(target_port))- .expect("install target client");- let sibling_port = FakePort::default();- let sibling_closed = Arc::clone(&sibling_port.closed);- let sibling = McpConfiguredClient::install_test_port(&sibling_config, Box::new(sibling_port))- .expect("install sibling client");-- target- .call::<bool>(&configured("target"), "ConnectedOverview", ())- .await- .unwrap();- sibling- .call::<bool>(&configured("sibling"), "ConnectedOverview", ())- .await- .unwrap();-- assert!(McpConfiguredClient::close_agent_data_dir(target_workspace.path()).await);- assert_eq!(- target_closed.lock().unwrap().as_slice(),- [target_workspace.path().to_str().unwrap()]- );- assert!(sibling_closed.lock().unwrap().is_empty());- assert!(McpConfiguredClient::for_config(&sibling_config).is_ok());- assert_eq!(- target- .call::<bool>(&configured("target"), "ConnectedOverview", ())- .await,- Err(ModuleCallError::Unavailable),- "an old client cannot reopen after acknowledged retirement"- );- }-- #[tokio::test]- async fn failed_agent_close_stays_retired_and_can_be_retried() {- let workspace = tempfile::tempdir().expect("workspace");- let mut config = Config::default();- config.workspace_dir = workspace.path().to_path_buf();- config.modules.enabled = true;-- let port = FakePort::default();- port.fail_first_close- .store(true, std::sync::atomic::Ordering::SeqCst);- let closed = Arc::clone(&port.closed);- let client =- McpConfiguredClient::install_test_port(&config, Box::new(port)).expect("install client");- client- .call::<bool>(&configured("server"), "ConnectedOverview", ())- .await- .unwrap();-- assert!(!McpConfiguredClient::close_agent_data_dir(workspace.path()).await);- assert!(McpConfiguredClient::agent_close_pending(workspace.path()));- assert!(matches!(- McpConfiguredClient::for_config(&config),- Err(ModuleCallError::Unavailable)- ));- assert_eq!(closed.lock().unwrap().len(), 1);-- assert!(McpConfiguredClient::close_agent_data_dir(workspace.path()).await);- assert!(!McpConfiguredClient::agent_close_pending(workspace.path()));- assert_eq!(closed.lock().unwrap().len(), 2);- assert!(McpConfiguredClient::for_config(&config).is_ok());- }-- #[tokio::test]- async fn agent_id_stays_unavailable_until_its_cached_module_close_is_acknowledged() {- let workspace = tempfile::tempdir().expect("workspace");- let alpha_dir = workspace.path().join("agents").join("alpha");- let beta_dir = workspace.path().join("agents").join("beta");- let mut alpha_config = Config::default();- alpha_config.workspace_dir = alpha_dir;- alpha_config.modules.enabled = true;- let mut beta_config = Config::default();- beta_config.workspace_dir = beta_dir;- beta_config.modules.enabled = true;-- let alpha_port = FakePort::default();- alpha_port- .block_first_close- .store(true, std::sync::atomic::Ordering::SeqCst);- let alpha = McpConfiguredClient::install_test_port(&alpha_config, Box::new(alpha_port.clone()))- .expect("install alpha client");- alpha- .call::<bool>(&configured("alpha"), "ConnectedOverview", ())- .await- .unwrap();- let beta = McpConfiguredClient::install_test_port(&beta_config, Box::new(FakePort::default()))- .expect("install beta client");- beta.call::<bool>(&configured("beta"), "ConnectedOverview", ())- .await- .unwrap();-- let workspace_path = workspace.path().to_path_buf();- let closing =- tokio::spawn(async move { crate::mcp::host::close_agent(&workspace_path, "alpha").await });- alpha_port.close_started.notified().await;- assert!(crate::mcp::host::agent_close_pending(- workspace.path(),- "alpha"- ));- assert!(!crate::mcp::host::agent_close_pending(- workspace.path(),- "beta"- ));- assert!(matches!(- McpConfiguredClient::for_config(&alpha_config),- Err(ModuleCallError::Unavailable)- ));- assert!(McpConfiguredClient::for_config(&beta_config).is_ok());-- alpha_port.release_close.notify_one();- assert!(closing.await.unwrap());- assert!(!crate::mcp::host::agent_close_pending(- workspace.path(),- "alpha"- ));- assert!(McpConfiguredClient::for_config(&alpha_config).is_ok());- }-- #[tokio::test]- async fn deferred_agent_purge_waits_for_module_close_and_keeps_the_id_reserved() {- let workspace = tempfile::tempdir().expect("workspace");- let agent_dir = workspace.path().join("agents").join("alpha");- std::fs::create_dir_all(&agent_dir).expect("agent home");- std::fs::write(agent_dir.join("transcript.jsonl"), "kept until close").unwrap();- let mut config = Config::default();- config.workspace_dir = agent_dir.clone();- config.modules.enabled = true;-- let port = FakePort::default();- port.block_first_close- .store(true, std::sync::atomic::Ordering::SeqCst);- let close_started = Arc::clone(&port.close_started);- let release_close = Arc::clone(&port.release_close);- let client = McpConfiguredClient::install_test_port(&config, Box::new(port))- .expect("install module client");- client- .call::<bool>(&configured("agent"), "ConnectedOverview", ())- .await- .unwrap();-- McpConfiguredClient::schedule_agent_close_and_cleanup(- &agent_dir,- Arc::new({- let agent_dir = agent_dir.clone();- move || std::fs::remove_dir_all(&agent_dir).is_ok() || !agent_dir.exists()- }),- );- close_started.notified().await;-- assert!(agent_dir.join("transcript.jsonl").exists());- assert!(McpConfiguredClient::agent_close_pending(&agent_dir));- assert!(matches!(- McpConfiguredClient::for_config(&config),- Err(ModuleCallError::Unavailable)- ));-- release_close.notify_one();- tokio::time::timeout(Duration::from_secs(1), async {- while McpConfiguredClient::agent_close_pending(&agent_dir) {- tokio::task::yield_now().await;- }- })- .await- .expect("close and deferred cleanup finish");- assert!(!agent_dir.exists());- assert!(McpConfiguredClient::for_config(&config).is_ok());- }-- #[test]- fn closed_client_cleanup_finishes_without_a_tokio_runtime() {- let workspace = tempfile::tempdir().expect("workspace");- let agent_dir = workspace.path().join("agents").join("closed");- std::fs::create_dir_all(&agent_dir).unwrap();- let mut config = Config::default();- config.workspace_dir = agent_dir.clone();- config.modules.enabled = true;- McpConfiguredClient::install_test_port(&config, Box::new(FakePort::default()))- .expect("install closed client");-- McpConfiguredClient::schedule_agent_close_and_cleanup(- &agent_dir,- Arc::new({- let agent_dir = agent_dir.clone();- move || std::fs::remove_dir_all(&agent_dir).is_ok() || !agent_dir.exists()- }),- );-- assert!(!agent_dir.exists());- assert!(!McpConfiguredClient::agent_close_pending(&agent_dir));- }-- #[tokio::test]- async fn a_removed_agent_context_cannot_reopen_its_evicted_client() {- use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};- use crate::tools::toolpacks::ToolGroups;-- let workspace = tempfile::tempdir().expect("workspace");- let mut config = Config::default();- config.workspace_dir = workspace.path().to_path_buf();- config.modules.enabled = true;- let scope = Arc::new(crate::security::approval::ApprovalScope::default());- let mut overrides = crate::agent::host_overrides::HostOverrides::default();- overrides.approval_scope = Some(Arc::clone(&scope));- let overrides = Arc::new(overrides);- let context = CoreContext::for_test(DomainSet::full(), Some(workspace.path().to_path_buf()))- .derive_with(- ContextOverlay::new(config.clone(), DomainSet::kernel(), ToolGroups::none())- .session_agent("agent")- .host_overrides(overrides),- );- scope.close("agent_removed");-- CoreContext::scope(context, async {- assert!(matches!(- McpConfiguredClient::for_config(&config),- Err(ModuleCallError::Unavailable)- ));- })- .await;- }-- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn a_removed_context_waiting_for_the_client_cache_cannot_reopen_it() {- use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};- use crate::tools::toolpacks::ToolGroups;-- let workspace = tempfile::tempdir().expect("workspace");- let scoped_dir = workspace.path().join("agents").join("agent");- let mut config = Config::default();- config.workspace_dir = workspace.path().to_path_buf();- config.modules.enabled = true;- let scope = Arc::new(crate::security::approval::ApprovalScope::default());- let mut overrides = crate::agent::host_overrides::HostOverrides::default();- overrides.approval_scope = Some(Arc::clone(&scope));- let context = CoreContext::for_test(DomainSet::full(), Some(workspace.path().to_path_buf()))- .derive_with(- ContextOverlay::new(config.clone(), DomainSet::kernel(), ToolGroups::none())- .session_agent("agent")- .host_overrides(Arc::new(overrides)),- );-- let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));- let clients_lock = clients.lock().unwrap();- let (checked, checked_rx) = tokio::sync::oneshot::channel();- *AFTER_CONTEXT_CHECK- .get_or_init(|| Mutex::new(None))- .lock()- .unwrap() = Some((scoped_dir.clone(), checked));- let request = tokio::spawn(CoreContext::scope(context, async move {- McpConfiguredClient::for_config(&config)- }));-- tokio::time::timeout(Duration::from_secs(10), checked_rx)- .await- .expect("request passed the initial context check")- .unwrap();- scope.close("agent_removed");- drop(clients_lock);-- let admitted = request.await.unwrap().is_ok();- if admitted {- clients.lock().unwrap().remove(&scoped_dir);- }- assert!(!admitted, "removed context must not create a cached client");- assert!(!clients.lock().unwrap().contains_key(&scoped_dir));- }-+#[tokio::test]+async fn delayed_agent_close_cannot_evict_a_replacement_cache_entry() {+ let workspace = tempfile::tempdir().expect("workspace");+ let mut config = Config::default();+ config.workspace_dir = workspace.path().to_path_buf();+ config.modules.enabled = true;++ let old_port = FakePort::default();+ let old_closed = Arc::clone(&old_port.closed);+ let old = McpConfiguredClient::install_test_port(&config, Box::new(old_port))+ .expect("install old client");+ old.call::<bool>(&configured("server"), "ConnectedOverview", ())+ .await+ .unwrap();+ let cleanup_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let callback_flag = Arc::clone(&cleanup_ran);- let reservation = McpConfiguredClient::reservation_with_action(++ let reservation = lifecycle::table().reservation_with_action(+ workspace.path(),+ Arc::new(move || {+ callback_flag.store(true, std::sync::atomic::Ordering::SeqCst);+ true+ }),+ );- let captured = McpConfiguredClient::retire_cached_client(workspace.path())++ let captured = lifecycle::table()++ .retire(workspace.path())+ .expect("retirement captures the exact old client");++ let replacement_port = FakePort::default();+ let replacement_closed = Arc::clone(&replacement_port.closed);+ let replacement = Arc::new(McpConfiguredClient::with_port(+ workspace.path().to_string_lossy().into_owned(),+ Box::new(replacement_port),+ ));- CLIENTS- .get()- .expect("old client initialized the cache")- .lock()- .unwrap()- .insert(workspace.path().to_path_buf(), Arc::clone(&replacement));++ lifecycle::table().insert(workspace.path().to_path_buf(), Arc::clone(&replacement));++ assert!(+ !McpConfiguredClient::close_retired_client(+ workspace.path().to_path_buf(),+ captured,+ Arc::clone(&reservation),+ )+ .await,+ "a stale close completion cannot claim the replacement entry"+ );+ assert!(!cleanup_ran.load(std::sync::atomic::Ordering::SeqCst));+ assert_eq!(old_closed.lock().unwrap().len(), 1);+ assert!(replacement_closed.lock().unwrap().is_empty());- let current = CLIENTS- .get()++ let current = lifecycle::table()++ .snapshot()++ .into_iter()++ .find(|(path, _)| path == workspace.path())+ .unwrap()- .lock()- .unwrap()- .get(workspace.path())- .cloned()- .expect("replacement remains cached");++ .1;+ assert!(Arc::ptr_eq(¤t, &replacement));- CLEANUP_RESERVATIONS- .get()- .unwrap()- .lock()- .unwrap()- .remove(workspace.path());++ lifecycle::table().evict(workspace.path(), &replacement);++ lifecycle::table().finish_cleanup(workspace.path(), None, &reservation);+}++#[tokio::test]+async fn failed_cleanup_actions_retain_and_retry_cached_and_orphaned_paths() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ let workspace = tempfile::tempdir().expect("workspace");+ let agent_dir = workspace.path().join("agents").join("alpha");+ std::fs::create_dir_all(&agent_dir).unwrap();+ std::fs::write(agent_dir.join("state.json"), "retained until cleanup").unwrap();+ let mut config = Config::default();+ config.workspace_dir = agent_dir.clone();+ config.modules.enabled = true;+ let client = McpConfiguredClient::install_test_port(&config, Box::new(FakePort::default()))+ .expect("install client");+ client+ .call::<bool>(&configured("alpha"), "ConnectedOverview", ())+ .await+ .unwrap();++ let attempts = Arc::new(AtomicUsize::new(0));+ let callback_attempts = Arc::clone(&attempts);+ let home = agent_dir.clone();+ let action: CleanupAction = Arc::new(move || {+ if callback_attempts.fetch_add(1, Ordering::SeqCst) == 0 {+ return false;+ }+ std::fs::remove_dir_all(&home).is_ok() || !home.exists()+ });- let reservation = McpConfiguredClient::reservation_with_action(&agent_dir, action);- let captured = McpConfiguredClient::retire_cached_client(&agent_dir).unwrap();++ let reservation = lifecycle::table().reservation_with_action(&agent_dir, action);++ let captured = lifecycle::table().retire(&agent_dir).unwrap();+ assert!(+ !McpConfiguredClient::close_retired_client(agent_dir.clone(), captured, reservation,).await+ );+ assert!(agent_dir.join("state.json").exists());+ assert!(McpConfiguredClient::agent_close_pending(&agent_dir));+ assert!(matches!(+ McpConfiguredClient::for_config(&config),+ Err(ModuleCallError::Unavailable)+ ));+ assert!(McpConfiguredClient::close_agent_data_dir(&agent_dir).await);+ assert!(!agent_dir.exists());+ assert!(McpConfiguredClient::for_config(&config).is_ok());++ let orphan_dir = workspace.path().join("agents").join("orphan");+ std::fs::create_dir_all(&orphan_dir).unwrap();+ let orphan_attempts = Arc::new(AtomicUsize::new(0));+ let callback_attempts = Arc::clone(&orphan_attempts);+ let orphan_home = orphan_dir.clone();- let reservation = McpConfiguredClient::reservation_with_action(++ let reservation = lifecycle::table().reservation_with_action(+ &orphan_dir,+ Arc::new(move || {+ if callback_attempts.fetch_add(1, Ordering::SeqCst) == 0 {+ return false;+ }+ std::fs::remove_dir_all(&orphan_home).is_ok() || !orphan_home.exists()+ }),+ );+ assert!(!McpConfiguredClient::finish_cleanup(+ &orphan_dir,+ None,+ reservation,+ ));+ assert!(McpConfiguredClient::agent_close_pending(&orphan_dir));+ assert!(orphan_dir.exists());- McpConfiguredClient::retry_orphaned_cleanups();++ lifecycle::table().retry_orphaned();+ assert!(!McpConfiguredClient::agent_close_pending(&orphan_dir));+ assert!(!orphan_dir.exists());+}diff --cc crates/openhuman-core/src/mcp/module_client_owner_tests.rsindex fece60a8c9,0000000000..d0eb350325mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/module_client_owner_tests.rs+++ b/crates/openhuman-core/src/mcp/module_client_owner_tests.rs@@@ -1,428 -1,0 +1,391 @@@+use super::*;+use std::sync::atomic::AtomicUsize;+use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};++#[derive(Clone, Default)]+struct LifecycleFixture {+ closes: Arc<AtomicUsize>,+ polls: Arc<AtomicUsize>,+ block_close_poll: Arc<AtomicBool>,+ close_poll_started: Arc<tokio::sync::Notify>,+ release_close_poll: Arc<tokio::sync::Notify>,+ fail_close: Arc<AtomicBool>,+ block_close: Arc<AtomicBool>,+ close_started: Arc<tokio::sync::Notify>,+ release_close: Arc<tokio::sync::Notify>,+}++#[tinybus::interface(name = "ai.tinyhumans.tinymcp.Mcp")]+impl LifecycleFixture {+ async fn close(&self, _data_dir: String) -> tinybus::Result<Option<String>> {+ self.closes.fetch_add(1, Ordering::SeqCst);+ if self.block_close.swap(false, Ordering::SeqCst) {+ self.close_started.notify_one();+ self.release_close.notified().await;+ }+ if self.fail_close.load(Ordering::SeqCst) {+ return Err(tinybus::Error::failed("fixture cleanup unavailable"));+ }+ Ok(Some("original-close".into()))+ }++ async fn transition_status(&self, receipt: String) -> tinybus::Result<TransitionStatus> {+ self.polls.fetch_add(1, Ordering::SeqCst);+ if receipt == "original-close" && self.block_close_poll.swap(false, Ordering::SeqCst) {+ self.close_poll_started.notify_one();+ self.release_close_poll.notified().await;+ }+ Ok(TransitionStatus::Complete)+ }+}++#[tokio::test]+async fn failed_agent_cleanup_retains_the_retired_owner_and_can_retry() {+ let scratch = tempfile::tempdir().unwrap();+ let directory = scratch.path().join("agents/worker");+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let service = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let fixture = LifecycleFixture::default();+ service+ .serve_at(+ ObjectPath::new(names::OBJECT_PATH).unwrap(),+ fixture.clone(),+ )+ .await+ .unwrap();+ service.request_name(names::INTERFACE).await.unwrap();- let port = TinyMcpPort::new(ModuleClient::fixture(++ let port = TinyMcpPort::new(crate::modules::ops::fixture_client(+ caller+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)+ .unwrap(),+ ));+ port.transition_status("original-open").await.unwrap();+ let client = Arc::new(McpConfiguredClient::with_port(+ directory.to_str().unwrap().into(),+ Box::new(port),+ ));- *client.state.lock().await = State::Open(OpenObject {++ *client.state.lock().await = opened_state(tinymcp_bus::client_lifecycle::OpenObject {+ config: McpClientConfig::default(),+ object_path: "/test/original-child".into(),+ });- CLIENTS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap()- .insert(directory.clone(), Arc::clone(&client));++ lifecycle::table().insert(directory.clone(), Arc::clone(&client));+ let cleanup = agent_cleanup::take_agent_cleanup(scratch.path(), "worker").unwrap();+ fixture.fail_close.store(true, Ordering::SeqCst);+ assert_eq!(cleanup.finish().await, Err(ModuleCallError::ModuleFault));- assert!(Arc::ptr_eq(- CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .get(&directory)- .unwrap(),- &client- ));++ assert!(Arc::ptr_eq(cached(&directory).as_ref().unwrap(), &client));+ assert!(matches!(- &*client.state.lock().await,- State::StartingClose(_)++ client.state.lock().await.close_step(),++ Step::CallClose+ ));+ assert_eq!(+ client+ .call::<Value>(&McpClientConfig::default(), "NeverReopen", ())+ .await,+ Err(ModuleCallError::Unavailable)+ );+ fixture.fail_close.store(false, Ordering::SeqCst);+ cleanup.finish().await.unwrap();- assert!(!CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .contains_key(&directory));++ assert!(!cached(&directory).is_some());+ // Retrying the old completed handle cannot evict a later owner.+ let successor = Arc::new(McpConfiguredClient::new(&directory, &Config::default()).unwrap());- CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .insert(directory.clone(), Arc::clone(&successor));++ lifecycle::table().insert(directory.clone(), Arc::clone(&successor));+ assert!(cleanup.finish_if_idle());+ assert!(Arc::ptr_eq(- CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .get(&directory)- .unwrap(),++ cached(&directory).as_ref().unwrap(),+ &successor+ ));- CLIENTS.get().unwrap().lock().unwrap().remove(&directory);++ lifecycle::table().evict(&directory, cached(&directory).as_ref().unwrap());+}++#[test]+fn an_absent_agent_cleanup_does_not_create_a_configured_client() {+ let scratch = tempfile::tempdir().unwrap();+ assert!(agent_cleanup::take_agent_cleanup(scratch.path(), "never-opened").is_none());- assert!(CLIENTS.get().is_none_or(|clients| !clients- .lock()- .unwrap()- .contains_key(&scratch.path().join("agents/never-opened"))));++ assert!(cached(&scratch.path().join("agents/never-opened")).is_none());+}++#[tokio::test]+async fn an_old_closed_context_cannot_create_the_reused_agents_first_client() {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};+ use crate::tools::toolpacks::ToolGroups;+ let scratch = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = scratch.path().into();+ let parent = CoreContext::for_test(DomainSet::full(), Some(config.workspace_dir.clone()));+ let old_scope = Arc::new(crate::security::approval::ApprovalScope::default());+ let mut old_overrides = crate::agent::host_overrides::HostOverrides::default();+ old_overrides.approval_scope = Some(Arc::clone(&old_scope));+ let old_overrides = Arc::new(old_overrides);+ let mut overlay = ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())+ .session_agent("worker");+ overlay.host_overrides = Some(old_overrides);+ let old_context = parent.derive_with(overlay);+ old_scope.close("agent_removed");+ CoreContext::scope(old_context, async {+ assert!(matches!(+ McpConfiguredClient::for_config(&config),+ Err(ModuleCallError::Unavailable)+ ));+ })+ .await;+ let directory = config.workspace_dir.join("agents/worker");- assert!(CLIENTS- .get()- .is_none_or(|clients| !clients.lock().unwrap().contains_key(&directory)));++ assert!(cached(&directory).is_none());+ let mut new_overlay =+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())+ .session_agent("worker");+ let mut new_overrides = crate::agent::host_overrides::HostOverrides::default();+ new_overrides.approval_scope =+ Some(Arc::new(crate::security::approval::ApprovalScope::default()));+ new_overlay.host_overrides = Some(Arc::new(new_overrides));+ CoreContext::scope(parent.derive_with(new_overlay), async {+ McpConfiguredClient::for_config(&config)+ .expect("the new instance has an open lifecycle scope");+ })+ .await;+ assert!(+ agent_cleanup::take_agent_cleanup(&config.workspace_dir, "worker")+ .unwrap()+ .finish_if_idle()+ );+}++#[tokio::test]+async fn cancelled_close_retries_its_receipt_on_the_original_owner() {+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let original = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let replacement = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let original_fixture = LifecycleFixture::default();+ let replacement_fixture = LifecycleFixture::default();+ for (connection, fixture) in [+ (&original, original_fixture.clone()),+ (&replacement, replacement_fixture.clone()),+ ] {+ connection+ .serve_at(ObjectPath::new(names::OBJECT_PATH).unwrap(), fixture)+ .await+ .unwrap();+ }+ original.request_name(names::INTERFACE).await.unwrap();- let port = TinyMcpPort::new(ModuleClient::fixture(++ let port = TinyMcpPort::new(crate::modules::ops::fixture_client(+ caller+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)+ .unwrap(),+ ));+ assert_eq!(+ port.transition_status("original-open").await,+ Ok(TransitionStatus::Complete)+ );+ let client = Arc::new(McpConfiguredClient::with_port(+ "/test/agent".into(),+ Box::new(port),+ ));- *client.state.lock().await = State::Open(OpenObject {++ *client.state.lock().await = opened_state(tinymcp_bus::client_lifecycle::OpenObject {+ config: McpClientConfig::default(),+ object_path: "/test/original-child".into(),+ });+ original_fixture+ .block_close_poll+ .store(true, Ordering::SeqCst);+ let closing = tokio::spawn({+ let client = Arc::clone(&client);+ async move { client.close().await }+ });+ tokio::time::timeout(+ Duration::from_secs(10),+ original_fixture.close_poll_started.notified(),+ )+ .await+ .expect("close receipt reaches the original module");+ closing.abort();+ assert!(closing.await.unwrap_err().is_cancelled());+ original_fixture.release_close_poll.notify_one();- assert!(- matches!(&*client.state.lock().await, State::Closing { transition_id, .. } if transition_id == "original-close")++ assert_eq!(++ client.state.lock().await.close_step(),++ Step::PollClose("original-close".into())+ );+ original.release_name(names::INTERFACE).await.unwrap();+ replacement.request_name(names::INTERFACE).await.unwrap();+ client.close().await.unwrap();+ assert_eq!(original_fixture.closes.load(Ordering::SeqCst), 1);+ assert_eq!(+ original_fixture.polls.load(Ordering::SeqCst),+ 3,+ "retry must poll the retained receipt on the original owner"+ );+ assert_eq!(replacement_fixture.closes.load(Ordering::SeqCst), 0);+ assert_eq!(replacement_fixture.polls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn cleanup_receipts_stay_with_the_original_module_after_alias_replacement() {+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let original = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let replacement = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let original_fixture = LifecycleFixture::default();+ let replacement_fixture = LifecycleFixture::default();+ for (connection, fixture) in [+ (&original, original_fixture.clone()),+ (&replacement, replacement_fixture.clone()),+ ] {+ connection+ .serve_at(ObjectPath::new(names::OBJECT_PATH).unwrap(), fixture)+ .await+ .unwrap();+ }+ original.request_name(names::INTERFACE).await.unwrap();- let root = ModuleClient::fixture(++ let root = crate::modules::ops::fixture_client(+ caller+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)+ .unwrap(),+ );+ let port = TinyMcpPort::new(root);+ // Resolve the original owner through a real bus call. No secret is sent+ // to these deliberately unattested lifecycle fixtures.+ assert_eq!(+ port.transition_status("original-open").await,+ Ok(TransitionStatus::Complete)+ );+ let client = McpConfiguredClient::with_port("/test/agent".into(), Box::new(port));- *client.state.lock().await = State::Open(OpenObject {++ *client.state.lock().await = opened_state(tinymcp_bus::client_lifecycle::OpenObject {+ config: McpClientConfig::default(),+ object_path: "/test/original-child".into(),+ });+ original.release_name(names::INTERFACE).await.unwrap();+ replacement.request_name(names::INTERFACE).await.unwrap();++ client.close().await.unwrap();+ assert_eq!(+ original_fixture.closes.load(Ordering::SeqCst),+ 1,+ "cleanup must address the original module instance"+ );+ assert_eq!(+ original_fixture.polls.load(Ordering::SeqCst),+ 2,+ "the close receipt must be polled on its original owner"+ );+ assert_eq!(replacement_fixture.closes.load(Ordering::SeqCst), 0);+ assert_eq!(replacement_fixture.polls.load(Ordering::SeqCst), 0);+}++#[tokio::test(start_paused = true)]+async fn a_blocked_close_has_an_overall_cleanup_deadline_and_keeps_the_owner_for_retry() {+ let scratch = tempfile::tempdir().unwrap();+ let directory = scratch.path().join("agents/blocked-close");+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let service = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let fixture = LifecycleFixture::default();+ service+ .serve_at(+ ObjectPath::new(names::OBJECT_PATH).unwrap(),+ fixture.clone(),+ )+ .await+ .unwrap();+ service.request_name(names::INTERFACE).await.unwrap();+ let port = TinyMcpPort::new(- ModuleClient::fixture(++ crate::modules::ops::fixture_client(+ caller+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)+ .unwrap(),+ )+ .with_timeout(Duration::from_secs(120)),+ );+ port.transition_status("original-open").await.unwrap();+ let client = Arc::new(McpConfiguredClient::with_port(+ directory.to_str().unwrap().into(),+ Box::new(port),+ ));+ // The acknowledged object isolates lifecycle routing from module admission.- *client.state.lock().await = State::Open(OpenObject {++ *client.state.lock().await = opened_state(tinymcp_bus::client_lifecycle::OpenObject {+ config: McpClientConfig::default(),+ object_path: "/test/original-child".into(),+ });- CLIENTS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap()- .insert(directory.clone(), Arc::clone(&client));++ lifecycle::table().insert(directory.clone(), Arc::clone(&client));+ let cleanup = agent_cleanup::take_agent_cleanup(scratch.path(), "blocked-close").unwrap();+ fixture.block_close.store(true, Ordering::SeqCst);+ let attempt = cleanup.clone();+ let mut task = tokio::spawn(async move { attempt.finish().await });+ fixture.close_started.notified().await;+ let outcome = tokio::time::timeout(Duration::from_secs(31), &mut task).await;+ if outcome.is_err() {+ task.abort();+ let _ = task.await;+ fixture.release_close.notify_one();- CLIENTS.get().unwrap().lock().unwrap().remove(&directory);++ lifecycle::table().evict(&directory, cached(&directory).as_ref().unwrap());+ }+ let result = outcome.expect("cleanup must return within 30 seconds even when Close has a 120-second operation timeout")+ .expect("cleanup task must complete normally");+ assert_eq!(result, Err(ModuleCallError::TransportFailed));+ assert!(matches!(- &*client.state.lock().await,- State::StartingClose(_)- ));- assert!(Arc::ptr_eq(- CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .get(&directory)- .unwrap(),- &client++ client.state.lock().await.close_step(),++ Step::CallClose+ ));++ assert!(Arc::ptr_eq(cached(&directory).as_ref().unwrap(), &client));+ assert!(client.retiring.load(Ordering::Acquire));+ // Retry the captured owner; timing out must not evict its close intent.+ fixture.release_close.notify_one();+ cleanup.finish().await.unwrap();+ assert_eq!(fixture.closes.load(Ordering::SeqCst), 2);- assert!(!CLIENTS- .get()- .unwrap()- .lock()- .unwrap()- .contains_key(&directory));++ assert!(!cached(&directory).is_some());+}++#[test]+fn orphaned_shutdown_cleanup_keeps_a_host_directory_reservation_until_confirmed() {+ let scratch = tempfile::tempdir().unwrap();+ let directory = scratch.path().join("agents/purge-pending");+ let token = crate::mcp::host::reserve_agent_directory(scratch.path(), "purge-pending");- McpConfiguredClient::retry_orphaned_cleanups();++ lifecycle::table().retry_orphaned();+ assert!(McpConfiguredClient::agent_close_pending(&directory));- let reservation = McpConfiguredClient::reservation_for(&directory);- assert!(!McpConfiguredClient::finish_cleanup(- &directory,- None,- reservation- ));++ let reservation = lifecycle::table().reservation_for(&directory);++ assert!(!lifecycle::table().finish_cleanup(&directory, None, &reservation));+ assert!(McpConfiguredClient::agent_close_pending(&directory));+ token.complete();+ assert!(!McpConfiguredClient::agent_close_pending(&directory));+}++++fn cached(directory: &std::path::Path) -> Option<Arc<McpConfiguredClient>> {++ lifecycle::table()++ .snapshot()++ .into_iter()++ .find(|(path, _)| path == directory)++ .map(|(_, client)| client)++}++fn opened_state(object: tinymcp_bus::client_lifecycle::OpenObject) -> ConfiguredLifecycle {++ let mut state = ConfiguredLifecycle::new();++ state.open_step(&object.config);++ state.open_replied(Ok(OpenConfiguredResponse {++ object_path: object.object_path,++ transition_id: "fixture-open".into(),++ }));++ state.open_polled(TransitionStatus::Complete);++ state++}diff --cc crates/openhuman-core/src/mcp/module_client_tests.rsindex 086e39aebc,7471665336..94b58d88f9--- a/crates/openhuman-core/src/mcp/module_client_tests.rs+++ b/crates/openhuman-core/src/mcp/module_client_tests.rs@@@ -528,5 -530,85 +530,88 @@@ async fn non_utf8_workspace_paths_are_r}#[cfg(test)]- #[path = "module_client_cleanup_tests.rs"]+ #[path = "module_client/cleanup_tests.rs"]mod cleanup_tests;++ /// A port that models TinyMCP's module-wide lifecycle gate: a second+ /// `open_configured` while another workspace's transition is still pending is+ /// refused instead of queued.+ #[derive(Clone, Default)]+ struct SingleTransitionPort {+ pending: Arc<std::sync::atomic::AtomicBool>,+ }++ #[async_trait]+ impl McpModulePort for SingleTransitionPort {+ async fn open_configured(+ &self,+ data_dir: &str,+ _config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ if self.pending.swap(true, std::sync::atomic::Ordering::SeqCst) {+ return Err(ModuleCallError::ModuleFault);+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ Ok(OpenConfiguredResponse {+ object_path: format!("/workspace{data_dir}"),+ transition_id: "open".to_owned(),+ })+ }++ async fn close(&self, _data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ Ok(None)+ }++ async fn transition_status(+ &self,+ _transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ tokio::time::sleep(Duration::from_millis(5)).await;+ self.pending+ .store(false, std::sync::atomic::Ordering::SeqCst);+ Ok(TransitionStatus::Complete)+ }++ async fn call_object(+ &self,+ _object_path: &str,+ _member: &str,+ _args: Value,+ _confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ Ok(Value::Bool(true))+ }++ async fn prepare_agent_tools(+ &self,+ _request: PrepareAgentToolsRequest,+ ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {+ Ok(Vec::new())+ }++ async fn validate_server_arguments(+ &self,+ _request: ValidateServerArgumentsRequest,+ ) -> Result<ServerArgumentsValidation, ModuleCallError> {+ Err(ModuleCallError::IncompatibleContract)+ }+ }++ #[tokio::test]+ async fn concurrent_workspaces_open_one_at_a_time_through_the_module_lifecycle_gate() {+ let port = SingleTransitionPort::default();+ let first = McpConfiguredClient::with_port("/private/a".to_owned(), Box::new(port.clone()));+ let second = McpConfiguredClient::with_port("/private/b".to_owned(), Box::new(port));+ let config = configured("server");++ let (a, b) = tokio::join!(+ first.call::<bool>(&config, "ConnectedOverview", ()),+ second.call::<bool>(&config, "ConnectedOverview", ()),+ );++ assert!(a.expect("first workspace opens"));+ assert!(b.expect("second workspace opens"));+ }++++#[path = "module_client_cleanup_tests.rs"]++mod captured_cleanup_tests;diff --cc crates/openhuman-core/src/mcp/module_port.rsindex 76480c0475,0000000000..da229ccde3mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/module_port.rs+++ b/crates/openhuman-core/src/mcp/module_port.rs@@@ -1,149 -1,0 +1,149 @@@+//! Bus adapter pinned to the module instance that starts its lifecycle.+use super::*;+#[cfg(feature = "modules")]- use crate::modules::client::ModuleObjectClient;++use tinybus::module::ModuleObjectClient;++pub(super) struct TinyMcpPort {+ root: ModuleClient,+ #[cfg(feature = "modules")]+ pinned: tokio::sync::OnceCell<ModuleObjectClient>,+}++impl TinyMcpPort {+ pub(super) fn new(root: ModuleClient) -> Self {+ Self {+ root,+ #[cfg(feature = "modules")]+ pinned: tokio::sync::OnceCell::new(),+ }+ }++ #[cfg(feature = "modules")]+ async fn pinned(&self) -> Result<&ModuleObjectClient, ModuleCallError> {+ self.pinned+ .get_or_try_init(|| async {+ self.root+ .object_client(MODULE, names::OBJECT_PATH)+ .await?+ .pin_owner()+ .await+ })+ .await+ }++ async fn root_call<R: DeserializeOwned>(+ &self,+ member: &str,+ args: impl Serialize,+ confidential: bool,+ ) -> Result<R, ModuleCallError> {+ #[cfg(feature = "modules")]+ {+ let root = self.pinned().await?;+ if confidential {+ root.call_confidential(member, args).await+ } else {+ root.call(member, args).await+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ if confidential {+ self.root.call_confidential(MODULE, member, args).await+ } else {+ self.root.call(MODULE, member, args).await+ }+ }+ }+}++#[async_trait]+impl McpModulePort for TinyMcpPort {+ async fn open_configured(+ &self,+ data_dir: &str,+ config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ self.root_call(+ names::methods::OPEN_CONFIGURED,+ (OpenConfiguredRequest {+ data_dir: data_dir.to_owned(),+ client: config.clone(),+ },),+ true,+ )+ .await+ }++ async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ self.root_call(names::methods::CLOSE, (data_dir.to_owned(),), false)+ .await+ }++ async fn transition_status(+ &self,+ transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ self.root_call(+ names::methods::TRANSITION_STATUS,+ (transition_id.to_owned(),),+ false,+ )+ .await+ }++ async fn call_object(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ #[cfg(feature = "modules")]+ {+ let object = self.pinned().await?.object_at(object_path)?;+ if confidential {+ object.call_confidential(member, args).await+ } else {+ object.call(member, args).await+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = (object_path, member, args, confidential);+ Err(ModuleCallError::Unavailable)+ }+ }++ async fn prepare_agent_tools(+ &self,+ request: PrepareAgentToolsRequest,+ ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {+ self.root_call(names::methods::PREPARE_AGENT_TOOLS, (request,), false)+ .await+ }++ async fn validate_server_arguments(+ &self,+ request: ValidateServerArgumentsRequest,+ ) -> Result<ServerArgumentsValidation, ModuleCallError> {+ self.root_call(names::methods::VALIDATE_SERVER_ARGUMENTS, (request,), true)+ .await+ }++ async fn normalize_tool_arguments(+ &self,+ arguments: Option<Value>,+ ) -> Result<Map<String, Value>, ModuleCallError> {+ self.root_call(names::methods::NORMALIZE_TOOL_ARGUMENTS, (arguments,), true)+ .await+ }++ async fn transform_text(+ &self,+ request: tinymcp_bus::TransformTextRequest,+ ) -> Result<String, ModuleCallError> {+ self.root_call(names::methods::TRANSFORM_TEXT, (request,), true)+ .await+ }+}diff --cc crates/openhuman-core/src/modules/runtime.rsindex 0000000000,796fcb66b8..bf04ae50b5mode 000000,100644..100644--- a/crates/openhuman-core/src/modules/runtime.rs+++ b/crates/openhuman-core/src/modules/runtime.rs@@@ -1,0 -1,118 +1,132 @@@+ //! The process-wide module runtime and the host callbacks it serves.+ //!+ //! The runtime itself (a dedicated thread with its own broker, connection and+ //! loader) is `tinybus::module::ModuleRuntime`; this file only decides when it+ //! starts and which host objects are served on its bus before any module can+ //! load.+ //!+ //! # Why modules get their own bus+ //!+ //! The core already runs a bus — `core::bus::BUS`, a `OnceBus<DomainEvent>` — but+ //! it cannot be reused here. `OnceBus::init_in_process` constructs its `Broker`+ //! internally and never hands it out, and the module host needs a `Broker` to+ //! attach loaded modules to. So modules run on a second in-process broker, and a+ //! module on it can serve requests but cannot publish a `DomainEvent`.+ //!+ //! # What loading a module means+ //!+ //! `dlopen` runs code before anything can inspect it. tinybus's ABI descriptor,+ //! manifest and digest gates decide whether a module is *admitted*, not whether+ //! it is *safe*: once loaded it can read and write this process's memory, and a+ //! native fault in it takes the core down. tinybus also never unloads a library,+ //! so a module that fails is failed until restart, which is why the resolver+ //! caches failures instead of retrying (see [`super::ops`]).+ //!+ //! Admission is deliberately permissive, tinybus's default. Strict mode also+ //! refuses a module whose rustc version string differs from the host's, and+ //! released artifacts are built by CI on whatever toolchain that runner had, so+ //! strict mode refused the real published artifact outright. Everything that+ //! protects the address space is still enforced: the ABI revision, the+ //! descriptor layout, the target triple, pointer width, endianness, feature bits+ //! and the refusal of a `panic=abort` module.+ //!+ //! Everything here is created once and lives for the process. There is no+ //! shutdown path because there is nothing a shutdown could reclaim.++ use std::sync::OnceLock;++ use tinybus::module::{ModuleRuntime, RuntimeNames};++ /// The module bus, built once on first use.+ static RUNTIME: OnceLock<Result<ModuleRuntime, String>> = OnceLock::new();++ /// Host callbacks installed on the runtime's bus, once.+ static CALLBACKS: tokio::sync::OnceCell<Result<(), String>> = tokio::sync::OnceCell::const_new();++ /// The process-wide module runtime, standing it up on first use.+ ///+ /// # Errors+ ///+ /// Returns an error if the broker's in-memory transport cannot be connected, or+ /// a host callback cannot be served. The outcome is cached: a runtime that+ /// failed to start does not start on a later call.+ pub async fn runtime() -> tinybus::Result<&'static ModuleRuntime> {- let started = RUNTIME.get_or_init(|| {- let names = RuntimeNames {- thread: "openhuman-module-bus".to_string(),- worker: "openhuman-module-worker".to_string(),- };- ModuleRuntime::start(&names, None).map_err(|error| error.to_string())- });- let runtime = started- .as_ref()- .map_err(|error| tinybus::Error::Transport(error.clone()))?;++ let runtime = runtime_now()?;+ CALLBACKS+ .get_or_init(|| async {+ // On the module runtime, not the caller's: the callbacks serve+ // objects that must outlive whichever runtime asked first.+ match runtime.spawn(install_callbacks(runtime)).await {+ Ok(Ok(())) => Ok(()),+ Ok(Err(error)) => Err(error.to_string()),+ Err(error) => Err(format!("the module callbacks did not finish: {error}")),+ }+ })+ .await+ .as_ref()+ .map_err(|error| tinybus::Error::Transport(error.clone()))?;+ Ok(runtime)+ }+++/// Schedule host lifecycle cleanup without loading a module or installing callbacks.++pub(crate) fn spawn_cleanup<F>(future: F) -> tinybus::Result<tokio::task::JoinHandle<F::Output>>++where++ F: std::future::Future + Send + 'static,++ F::Output: Send + 'static,++{++ Ok(runtime_now()?.spawn(future))++}++++fn runtime_now() -> tinybus::Result<&'static ModuleRuntime> {++ let started = RUNTIME.get_or_init(|| {++ let names = RuntimeNames {++ thread: "openhuman-module-bus".to_string(),++ worker: "openhuman-module-worker".to_string(),++ };++ ModuleRuntime::start(&names, None).map_err(|error| error.to_string())++ });++ let runtime = started++ .as_ref()++ .map_err(|error| tinybus::Error::Transport(error.clone()))?;++ Ok(runtime)++}+++ /// Serve the host objects modules call back into, before any module loads.+ async fn install_callbacks(runtime: &'static ModuleRuntime) -> tinybus::Result<()> {+ let connection = runtime.connection();++ // The summary callback exists for the module alone; with the component off+ // the module never loads, so nothing would call it.+ let host = crate::core::runtime::DispatchCtx::host_default();+ if host.components().juice {+ super::tokenjuice_host::install(connection).await?;+ } else {+ tracing::debug!("[modules] juice component off; MlHost not served");+ }+ super::site_memory_host::install(connection).await?;+ super::storage_host::install(connection, runtime.host()).await?;+ #[cfg(feature = "tinymemes")]+ {+ if host.components().memes {+ crate::tinymemes::service::install(connection).await?;+ } else {+ tracing::debug!("[modules] memes component off; Host callbacks not served");+ }+ }+ #[cfg(feature = "web3")]+ super::wallet_host::install(connection).await?;+ Ok(())+ }++ /// Whether the module runtime has been stood up.+ ///+ /// Lets status reporting answer without starting a broker as a side effect of+ /// being asked a question.+ #[must_use]+ pub fn is_started() -> bool {+ RUNTIME.get().is_some_and(Result::is_ok)+ }++ #[cfg(test)]+ #[path = "runtime_tests.rs"]+ mod tests;diff --cc crates/openhuman-embed/src/agent/mcp_cleanup_tests.rsindex 78fdf0daa5,0000000000..bddc37905cmode 100644,000000..100644--- a/crates/openhuman-embed/src/agent/mcp_cleanup_tests.rs+++ b/crates/openhuman-embed/src/agent/mcp_cleanup_tests.rs@@@ -1,390 -1,0 +1,390 @@@+use super::*;++fn pending(home: std::path::PathBuf) -> PendingCleanup {+ PendingCleanup {+ cleanup: None,+ directory: openhuman_core::mcp::host::reserve_agent_directory(+ home.parent().unwrap(),+ home.file_name().unwrap().to_str().unwrap(),+ ),+ instance: Weak::new(),+ home,+ purge: true,+ retry_running: Default::default(),+ }+}++#[test]+fn confirmed_cleanup_purges_before_releasing_a_dead_agent_reservation() {+ let scratch = tempfile::tempdir().unwrap();+ let home = scratch.path().join("worker");+ std::fs::create_dir(&home).unwrap();+ std::fs::write(home.join("kept-until-cleanup"), "fixture").unwrap();+ let pending = pending(home.clone());+ let registry = crate::runtime::AgentMap::default();+ {+ let mut agents = registry.lock().unwrap();+ agents.insert("worker".into(), pending.instance.clone());+ agents.pending.insert("worker".into(), pending.clone());+ }+ finish_removal(®istry, "worker", &pending).unwrap();+ assert!(!home.exists());+ let agents = registry.lock().unwrap();+ assert!(!agents.contains_key("worker"));+ assert!(!agents.pending.contains_key("worker"));+}++#[test]+fn a_failed_purge_keeps_the_dead_agent_reservation_and_purge_intent() {+ let scratch = tempfile::tempdir().unwrap();+ let home = scratch.path().join("worker");+ std::fs::write(&home, "a file cannot be purged as a directory").unwrap();+ let pending = pending(home.clone());+ let registry = crate::runtime::AgentMap::default();+ {+ let mut agents = registry.lock().unwrap();+ agents.insert("worker".into(), pending.instance.clone());+ agents.pending.insert("worker".into(), pending.clone());+ }+ assert!(matches!(+ finish_removal(®istry, "worker", &pending),+ Err(AgentError::Workspace { .. })+ ));+ assert!(home.exists());+ let agents = registry.lock().unwrap();+ assert!(agents.contains_key("worker"));+ assert!(agents.pending.get("worker").unwrap().purge);+}++#[test]+fn an_already_released_reservation_does_not_purge_a_home() {+ let scratch = tempfile::tempdir().unwrap();+ let home = scratch.path().join("worker");+ std::fs::create_dir(&home).unwrap();+ finish_removal(+ &crate::runtime::AgentMap::default(),+ "worker",+ &pending(home.clone()),+ )+ .unwrap();+ assert!(home.exists());+}++#[test]+fn the_last_runtime_guard_keeps_admission_reserved_through_cleanup_completion() {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async {+ let runtime = crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Ephemeral)+ .build()+ .await+ .expect("a real isolated runtime can be built");+ let guard = runtime.guard();+ let weak = Arc::downgrade(&guard);+ drop(runtime);+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let worker = std::thread::spawn(move || {+ let mut guard = Some(guard);+ let result = complete_with_guard(&mut guard, || {+ entered_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ Err::<(), ()>(())+ });+ result.is_err() && guard.is_some()+ });+ entered_rx.recv().unwrap();+ let guard_is_live = weak.upgrade().is_some();+ let admission_is_reserved =+ crate::runtime::RUNTIME_LIVE.load(std::sync::atomic::Ordering::Acquire);+ release_tx.send(()).unwrap();+ let retry_guard_is_retained = worker.join().unwrap();+ assert!(retry_guard_is_retained, "a failed completion may retry and must retain runtime admission until the task ends");+ assert!(+ guard_is_live,+ "completion must retain the last real workspace/runtime guard"+ );+ assert!(+ admission_is_reserved,+ "another runtime must remain excluded while cleanup completion is blocked"+ );+ assert!(weak.upgrade().is_none());+ assert!(!crate::runtime::RUNTIME_LIVE.load(std::sync::atomic::Ordering::Acquire));+ })+ .await+ .unwrap();+ });+}++#[test]+fn exhausted_cleanup_releases_runtime_admission_but_preserves_the_ephemeral_workspace() {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async {+ let runtime = crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Ephemeral)+ .build()+ .await+ .unwrap();+ let root = runtime.workspace_dir().to_path_buf();+ let home = root.join("agents/unresolved");+ std::fs::create_dir_all(&home).unwrap();+ std::fs::write(home.join("module-state"), "must survive unconfirmed close").unwrap();+ let guard = runtime.guard();+ let weak = Arc::downgrade(&guard);+ drop(runtime);+ let attempts = std::sync::atomic::AtomicUsize::new(0);+ retry_cleanup(+ guard,+ || {+ attempts.fetch_add(1, Ordering::SeqCst);+ async {+ Err(AgentError::McpCleanup(- openhuman_core::modules::client::ModuleCallError::ModuleFault,++ tinybus::module::ModuleCallError::ModuleFault,+ ))+ }+ },+ || panic!("unconfirmed close must never purge"),+ )+ .await;+ let home_was_preserved = home.join("module-state").exists();+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(attempts.load(Ordering::SeqCst), 3);+ assert!(+ weak.upgrade().is_none(),+ "exhaustion must release the process guard"+ );+ assert!(!crate::runtime::RUNTIME_LIVE.load(Ordering::Acquire));+ assert!(+ home_was_preserved,+ "failed cleanup must preserve the ephemeral workspace after the last guard drops"+ );+ })+ .await+ .unwrap();+ });+}++fn workspace_cleanup_control(cancel: bool) {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async move {+ let runtime = crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Ephemeral)+ .build()+ .await+ .unwrap();+ let root = runtime.workspace_dir().to_path_buf();+ let guard = runtime.guard();+ let weak = Arc::downgrade(&guard);+ drop(runtime);+ let cleanup = retry_cleanup(guard, || async { Ok(()) }, || Ok(()));+ if cancel {+ // Executor rejection or an unpolled task must preserve its home.+ drop(cleanup);+ } else {+ cleanup.await;+ }+ let workspace_exists = root.exists();+ let _ = std::fs::remove_dir_all(&root);+ assert!(weak.upgrade().is_none());+ assert!(!crate::runtime::RUNTIME_LIVE.load(Ordering::Acquire));+ assert_eq!(+ workspace_exists, cancel,+ "only confirmed cleanup may remove the ephemeral workspace"+ );+ })+ .await+ .unwrap();+ });+}++#[test]+fn confirmed_cleanup_still_removes_the_last_owners_ephemeral_workspace() {+ workspace_cleanup_control(false);+}++#[test]+fn cancelling_an_unpolled_cleanup_preserves_its_ephemeral_workspace() {+ workspace_cleanup_control(true);+}++#[test]+fn a_failed_purge_fences_the_same_directory_after_its_original_runtime_is_gone() {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async {+ let scratch = tempfile::tempdir().unwrap();+ let make_runtime = || {+ crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Dir(scratch.path().into()))+ .access(crate::Access::full())+ };+ let spec = || {+ crate::AgentSpec::new("worker")+ .provider(+ crate::Provider::openai_compatible("http://127.0.0.1:1", "fixture")+ .model("fixture"),+ )+ .access(crate::Access::full())+ };+ let runtime = make_runtime().build().await.unwrap();+ let agent = runtime.agent(spec()).unwrap();+ let home = scratch.path().join("agents/worker");+ std::fs::remove_dir_all(&home).unwrap();+ std::fs::write(&home, "force purge failure").unwrap();+ // No MCP entry means close is already confirmed. This pins the+ // independent host purge fence; bus receipts have their own tests.+ assert!(matches!(+ runtime.remove_agent("worker").purge().await,+ Err(AgentError::Workspace { .. })+ ));+ drop(agent);+ drop(runtime);+ assert!(!crate::runtime::RUNTIME_LIVE.load(Ordering::Acquire));+ // Repair the filesystem fault without completing the old purge.+ std::fs::remove_file(&home).unwrap();+ std::fs::create_dir_all(&home).unwrap();+ std::fs::write(home.join("old-state"), "must remain reserved").unwrap();+ let successor_runtime = make_runtime().build().await.unwrap();+ let successor = successor_runtime.agent(spec());+ let rejected = matches!(successor, Err(AgentError::CleanupPending));+ drop(successor);+ drop(successor_runtime);+ assert!(+ rejected,+ "failed purge must reserve this directory across runtime replacement"+ );+ assert_eq!(+ std::fs::read_to_string(home.join("old-state")).unwrap(),+ "must remain reserved"+ );+ })+ .await+ .unwrap();+ });+}++#[test]+fn repairing_and_retrying_purge_on_the_original_runtime_releases_the_directory() {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async {+ let scratch = tempfile::tempdir().unwrap();+ let runtime = crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Dir(scratch.path().into()))+ .access(crate::Access::full())+ .build()+ .await+ .unwrap();+ let spec = || {+ crate::AgentSpec::new("worker")+ .provider(+ crate::Provider::openai_compatible("http://127.0.0.1:1", "fixture")+ .model("fixture"),+ )+ .access(crate::Access::full())+ };+ let agent = runtime.agent(spec()).unwrap();+ let home = scratch.path().join("agents/worker");+ std::fs::remove_dir_all(&home).unwrap();+ std::fs::write(&home, "force purge failure").unwrap();+ assert!(matches!(+ runtime.remove_agent("worker").purge().await,+ Err(AgentError::Workspace { .. })+ ));+ drop(agent);+ assert!(openhuman_core::mcp::host::agent_close_pending(+ scratch.path(),+ "worker"+ ));+ std::fs::remove_file(&home).unwrap();+ std::fs::create_dir_all(&home).unwrap();+ std::fs::write(home.join("old-state"), "to purge").unwrap();+ runtime.remove_agent("worker").purge().await.unwrap();+ assert!(!home.exists());+ assert!(!openhuman_core::mcp::host::agent_close_pending(+ scratch.path(),+ "worker"+ ));+ let successor = runtime+ .agent(spec())+ .expect("confirmed purge releases the public id");+ drop(successor);+ drop(runtime);+ })+ .await+ .unwrap();+ });+}++#[test]+fn dropping_an_agent_without_an_mcp_entry_keeps_normal_ephemeral_cleanup() {+ let executor = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .worker_threads(1)+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)+ .build()+ .unwrap();+ executor.block_on(async {+ tokio::spawn(async {+ let runtime = crate::Runtime::builder()+ .config(openhuman_core::config::Config::default())+ .workspace(crate::Workspace::Ephemeral)+ .access(crate::Access::full())+ .build()+ .await+ .unwrap();+ let root = runtime.workspace_dir().to_path_buf();+ let agent = runtime+ .agent(+ crate::AgentSpec::new("unused")+ .provider(+ crate::Provider::openai_compatible("http://127.0.0.1:1", "fixture")+ .model("fixture"),+ )+ .access(crate::Access::full()),+ )+ .unwrap();+ drop(agent);+ drop(runtime);+ assert!(!root.exists());+ assert!(!openhuman_core::mcp::host::agent_close_pending(+ &root, "unused"+ ));+ })+ .await+ .unwrap();+ });+}diff --cc crates/openhuman-embed/src/agent/mod.rsindex 34a981adb2,27836dd694..1ed2a3c968--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@@ -108,10 -107,6 +108,10 @@@ pub enum AgentError/// A named built-in definition does not exist.#[error("unknown built-in agent definition {0:?}")]UnknownDefinition(String),+ /// The agent is removed, but its original MCP owner still needs cleanup.+ /// Its id and home remain reserved while detached cleanup retries.+ #[error("agent MCP cleanup is still pending: {0}")]- McpCleanup(#[source] openhuman_core::modules::client::ModuleCallError),++ McpCleanup(#[source] tinybus::module::ModuleCallError),}/// The assembled state behind an [`Agent`], shared by every clone of it anddiff --cc crates/openhuman-embed/src/harness/error.rsindex bfb29aadf2,81f43c2f30..f0b3c4fb51--- a/crates/openhuman-embed/src/harness/error.rs+++ b/crates/openhuman-embed/src/harness/error.rs@@@ -51,10 -51,6 +51,10 @@@ pub enum HarnessError)]AlreadyRunning,+ /// Removing an agent failed to confirm cleanup of its captured MCP owner.+ #[error("MCP cleanup remains pending: {0}")]- McpCleanup(#[source] openhuman_core::modules::client::ModuleCallError),++ McpCleanup(#[source] tinybus::module::ModuleCallError),+/// A builder input could not be honoured.#[error("{0}")]Invalid(String),diff --cc crates/openhuman-embed/src/harness/workspace.rsindex 6240b9e4bc,5df506a78e..e93b4ec202--- a/crates/openhuman-embed/src/harness/workspace.rs+++ b/crates/openhuman-embed/src/harness/workspace.rs@@@ -92,7 -95,43 +95,59 @@@ pub(crate) struct ResolvedWorkspace/// operator's real `~/.openhuman` credentials while looking hermetic.pub(crate) config_path: PathBuf,/// `None` for `Dir` / `Inherit`; those directories outlive the runtime.- pub(crate) _temp: Option<tempfile::TempDir>,+ pub(crate) _temp: Option<std::sync::Arc<EphemeralRoot>>,+ }++ /// The temp root of an ephemeral workspace, removed when its last holder+ /// drops: the runtime, or a deferred agent cleanup that must keep the files+ /// until the MCP module acknowledges its close. Shared on its own so that+ /// cleanup never has to hold the whole runtime (and its process slot).-pub(crate) struct EphemeralRoot(Option<tempfile::TempDir>);++pub(crate) struct EphemeralRoot {++ temp: Option<tempfile::TempDir>,++ preserve: std::sync::atomic::AtomicBool,++}++impl EphemeralRoot {++ pub(crate) fn preserve(&self) {++ self.preserve++ .store(true, std::sync::atomic::Ordering::Release);++ }++}++ impl Drop for EphemeralRoot {+ fn drop(&mut self) {- let Some(temp) = self.0.take() else {++ let Some(temp) = self.temp.take() else {+ return;+ };+ // Take ownership of the temp path and remove it with a short retry.+ // The core's memory/session writers keep running a moment after a+ // turn returns and can recreate workspace subdirectories while+ // `TempDir`'s own drop-time removal is racing them, leaving an empty+ // directory behind. A bounded retry lets those writes settle before+ // giving up.+ let root = temp.keep();++ if self.preserve.load(std::sync::atomic::Ordering::Acquire) {++ log::warn!(++ "[embed][runtime] unresolved cleanup; preserved ephemeral workspace at {}",++ root.display()++ );++ return;++ }+ let mut quiet_passes = 0;+ for _ in 0..20 {+ match std::fs::remove_dir_all(&root) {+ Ok(()) => quiet_passes += 1,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ quiet_passes += 1;+ }+ Err(_) => quiet_passes = 0,+ }+ if quiet_passes >= 5 {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ let _ = std::fs::remove_dir_all(&root);+ }}impl ResolvedWorkspace {@@@ -138,7 -177,7 +193,10 @@@workspace_dir,action_dir,config_path: root.join("config.toml"),- _temp: Some(temp),- _temp: Some(std::sync::Arc::new(EphemeralRoot(Some(temp)))),++ _temp: Some(std::sync::Arc::new(EphemeralRoot {++ temp: Some(temp),++ preserve: Default::default(),++ })),})}Workspace::Dir(dir) => {diff --cc crates/openhuman-embed/src/runtime/mod.rsindex 65e56691ee,c408687504..de0ec13459--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@@ -245,40 -255,10 +254,15 @@@ impl Drop for CoreGuard.unwrap_or_else(std::sync::PoisonError::into_inner).take(),);- // For an ephemeral workspace, take ownership of the temp path and- // remove it with a short retry. The core's memory/session writers keep- // running a moment after a turn returns and can recreate workspace- // subdirectories while `TempDir`'s own drop-time removal is racing- // them, leaving an empty directory behind. A bounded retry lets those- // writes settle before giving up.- if let Some(temp) = self.workspace._temp.take() {- let root = temp.keep();- if self- .preserve_ephemeral_workspace- .load(std::sync::atomic::Ordering::Acquire)- {- log::warn!(- "[embed][runtime] unresolved cleanup; preserved ephemeral workspace at {}",- root.display()- );- } else {- let mut quiet_passes = 0;- for _ in 0..20 {- match std::fs::remove_dir_all(&root) {- Ok(()) => quiet_passes += 1,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- quiet_passes += 1;- }- Err(_) => quiet_passes = 0,- }- if quiet_passes >= 5 {- break;- }- std::thread::sleep(std::time::Duration::from_millis(50));- }- let _ = std::fs::remove_dir_all(&root);- // An ephemeral workspace is removed here unless a deferred agent- // cleanup still holds it (see `EphemeralRoot`); either way the process- // slot below is released now.++ if self++ .preserve_ephemeral_workspace++ .load(std::sync::atomic::Ordering::Acquire)++ {++ if let Some(root) = &self.workspace._temp {++ root.preserve();+ }+ }+ drop(self.workspace._temp.take());RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);log::debug!("[embed][runtime] released");}diff --cc scripts/ci/process-statics.jsonindex 0000000000,0ee65285ae..9f664d3a2bmode 000000,100644..100644--- a/scripts/ci/process-statics.json+++ b/scripts/ci/process-statics.json@@@ -1,0 -1,292 +1,302 @@@+ [+ {+ "file": "crates/openhuman-core/src/mcp/ui/cache.rs",+ "scope": "",+ "name": "STORE",+ "type": "LazyLock<Mutex<Store>>",+ "count": 1,+ "category": "B",+ "reason": "Every entry key is prefixed with the calling tenant's profile and agent scope through tenant_key, and a SaaS call with no tenant scope gets an isolated key that never matches.",+ "verification": "mcp/ui/cache_tests.rs: entries_are_not_shared_across_tenants"+ },+ {+ "file": "crates/openhuman-core/src/mcp/module_client.rs",+ "scope": "",+ "name": "LIFECYCLE_GATE",+ "type": "tokio::sync::Mutex<()>",+ "count": 1,+ "category": "A",+ "reason": "Serializes TinyMCP open/close transitions, which the module admits one at a time process-wide; it guards no data and carries no tenant state.",+ "verification": "mcp/module_client_tests.rs: concurrent_workspaces_open_one_at_a_time_through_the_module_lifecycle_gate"+ },+ {+ "file": "crates/openhuman-core/src/tinymemes/callbacks.rs",+ "scope": "",+ "name": "REGISTRY",+ "type": "LazyLock<Mutex<HashMap<String,Entry>>>",+ "count": 1,+ "category": "B",+ "reason": "Keyed by a random per-remix correlation id; each entry holds the registering caller's config and CoreContext, which every callback re-enters. Callbacks are accepted only from the module peer (bus name owner) for a live id, and the entry is retired by End, a failed call, or an age sweep.",+ "verification": "tinymemes/service_tests.rs: only_the_module_may_call_back_and_only_for_a_live_remix"+ },+ {+ "file": "crates/openhuman-core/src/tinymemes/service.rs",+ "scope": "",+ "name": "FOREGROUND",+ "type": "std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String,std::sync::Arc<tokio::sync::Mutex<()>>>>, >",+ "count": 1,+ "category": "B",+ "reason": "Holds only unit mutexes. The key is the workspace directory, so different workspaces never share or wait on a lock and no tenant data is stored.",+ "verification": "tinymemes/service_tests.rs: foreground_remixes_share_a_lock_per_workspace_and_never_across_workspaces"+ },+ {+ "file": "crates/openhuman-core/src/modules/wallet_backend.rs",+ "scope": "",+ "name": "HANDLERS",+ "type": "HookSlot<WalletBackendHandler>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of handlers the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "modules/wallet_backend_tests.rs: a_registered_handler_answers_the_call"+ },+ {+ "file": "crates/openhuman-core/src/modules/runtime.rs",+ "scope": "",+ "name": "RUNTIME",+ "type": "OnceLock<Result<ModuleRuntime,String>>",+ "count": 1,+ "category": "A",+ "reason": "The single tinybus module bus (broker, loader, connection) for the process; tinybus never unloads a module, so there is exactly one. Carries no tenant data: tenant scope is resolved per call by the host callbacks it serves.",+ "verification": "modules/runtime_tests.rs: the_module_bus_is_a_singleton_and_serves_proxies"+ },+ {+ "file": "crates/openhuman-core/src/modules/runtime.rs",+ "scope": "",+ "name": "CALLBACKS",+ "type": "tokio::sync::OnceCell<Result<(),String>>",+ "count": 1,+ "category": "A",+ "reason": "Records that the host callback objects were served on the module bus once, before any module loads; infrastructure only.",+ "verification": "modules/runtime_tests.rs: wallet_host_callback_is_served_before_the_module_is_loaded"+ },+ {+ "file": "crates/openhuman-core/src/modules/report.rs",+ "scope": "",+ "name": "REPORTER",+ "type": "OnceLock<Arc<FailureReporter>>",+ "count": 1,+ "category": "A",+ "reason": "Deduplicates terminal module outcomes per (module id, reason) so a broken install is one Sentry event per process; keys are registry ids only and no tenant data is held.",+ "verification": "modules/report_tests.rs: terminal_reports_are_sanitized_and_deduplicated"+ },+ {+ "file": "crates/openhuman-core/src/modules/registry.rs",+ "scope": "",+ "name": "TABLE",+ "type": "std::sync::OnceLock<Vec<tinybus::module::ReleaseRecord>>",+ "count": 1,+ "category": "A",+ "reason": "The compiled module registry in the shape the tinybus resolver consumes; constants only.",+ "verification": "modules/ops_tests.rs: list_reports_every_registry_entry"+ },+ {+ "file": "crates/openhuman-core/src/modules/ops.rs",+ "scope": "",+ "name": "LOGGED",+ "type": "OnceLock<Mutex<std::collections::HashSet<&'static str>>>",+ "count": 1,+ "category": "A",+ "reason": "Registry ids whose serving source was already logged, so each is logged once; holds static ids only.",+ "verification": "modules/ops_tests.rs: status_reports_the_source_that_serves_a_module"+ },+ {+ "file": "crates/openhuman-core/src/web_chat/ops/test_hooks.rs",+ "scope": "",+ "name": "TEST_PARK_AFTER_RUN",+ "type": "std::sync::atomic::AtomicBool",+ "count": 1,+ "category": "A",+ "reason": "A debug/test-only hook flag (`cfg(any(test, debug_assertions))`) that parks `run_chat_task` after its run so the idle guard can be exercised end to end; it holds no tenant data and is off unless a test sets it.",+ "verification": "tests/agent_harness_e2e.rs: idle_guard_local::stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary"+ },+ {+ "file": "crates/openhuman-core/src/modules/connectors.rs",+ "scope": "",+ "name": "ROUTE_TURN",+ "type": "tokio::sync::Mutex<()>",+ "count": 1,+ "category": "A",+ "reason": "Test-only (cfg(test)): serializes each TinyConnectors call with the route it sets, because libtest runs a crate's tests in one process and the module's route is process-global; it guards no data and carries no tenant state.",+ "verification": "flows/tinyflows/caps/tools/composio_tests.rs: backend_dispatch_forwards_the_workflow_connection_id"+ },+ {+ "file": "crates/openhuman-core/src/agent/session_store/mod.rs",+ "scope": "",+ "name": "OPEN_WORKSPACE_STORES",+ "type": "LazyLock<Mutex<HashMap<(std::path::PathBuf,String),tinyagents_session::port::WorkspaceStores>>, >",+ "count": 1,+ "category": "D",+ "reason": "Holds open the workspace transcript stores used when no host session store is installed. Each entry is a handle to the SQLite store under one workspace, keyed by that workspace and the session store key (agent_key_for: <profile>~<agent> for a SaaS profile), so two profiles or agents never share an entry; the store under the workspace is the authoritative data. release_workspace_defaults drops them all for a data reset, release_workspace those of one workspace.",+ "verification": "threads/ops/edit_tests.rs: a_profile_prefixed_key_round_trips_through_edit_and_regenerate; agent/session_store/mod_tests.rs: without_a_store_transcripts_come_from_the_workspace_store_not_files"+ },+ {+ "file": "crates/openhuman-core/src/agent/session_store/rebound.rs",+ "scope": "",+ "name": "PROCESS",+ "type": "LazyLock<StoreRegistry>",+ "count": 1,+ "category": "A",+ "reason": "The process's registry of weak handles to the rebindable session-store providers a host installed, so a workspace switch (storage::rebind) can point each at the new backend. It holds no records and no tenant state, only Weak references; the stores' data lives in the storage backend. A test builds its own StoreRegistry, so rebinding one never moves another's stores.",+ "verification": "agent/session_store/rebound_tests.rs: a_registry_rebind_leaves_other_registries_alone"+ },+ {+ "file": "crates/openhuman-core/src/agent/artifacts/publisher_slot.rs",+ "scope": "",+ "name": "PUBLISHERS",+ "type": "HookSlot<ArtifactPublisherFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "agent/artifacts/publisher_slot_tests.rs: the_first_factory_that_answers_serves_sharing"+ },+ {+ "file": "crates/openhuman-core/src/channels/callback_slot.rs",+ "scope": "",+ "name": "CALLBACKS",+ "type": "HookSlot<ChannelCallback>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "channels/callback_slot_tests.rs: the_first_registered_callback_serves_requests"+ },+ {+ "file": "crates/openhuman-core/src/config/enrichers.rs",+ "scope": "",+ "name": "ENRICHERS",+ "type": "HookSlot<ConfigEnricher>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "config/enrichers_tests.rs: enrichers_run_in_registration_order"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CHAT_MODELS",+ "type": "HookSlot<ChatModelEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_chat_model_serves_the_managed_provider_for_a_thread"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "EMBEDDINGS",+ "type": "HookSlot<EmbeddingFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_embedding_factory_builds_the_managed_embedding_model"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CATALOGS",+ "type": "HookSlot<CatalogEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_catalog_answers_the_model_listing_for_its_provider"+ },+ {+ "file": "crates/openhuman-core/src/integrations/composio/client/factory.rs",+ "scope": "",+ "name": "ROUTE_BUILDERS",+ "type": "HookSlot<ComposioRouteBuilder>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "integrations/composio/client/factory_tests.rs: a_registered_route_builder_resolves_the_backend_mode"+ },+ {+ "file": "crates/openhuman-core/src/modules/connectors.rs",+ "scope": "",+ "name": "MODULE_PROXY_TARGETS",+ "type": "HookSlot<ProxyTargetResolver>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of handlers the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "modules/connectors_tests.rs: the_backend_route_is_unavailable_without_a_registered_target"+ },+ {+ "file": "crates/openhuman-core/src/memory/engine_registry.rs",+ "scope": "",+ "name": "ENGINES",+ "type": "HookSlot<EngineEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "memory/engine_registry_tests.rs: the_layout_root_reaches_the_registered_builder"+ },+ {+ "file": "crates/openhuman-core/src/tools/sources.rs",+ "scope": "",+ "name": "TOOL_SOURCES",+ "type": "HookSlot<ToolSourceEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "tools/sources_tests.rs: registered_sources_append_in_registration_order_after_built_ins"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "STT_PROVIDERS",+ "type": "HookSlot<SttProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_stt_slug_is_built_with_the_effective_model"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "TTS_PROVIDERS",+ "type": "HookSlot<TtsProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_tts_provider_gets_the_resolved_voice_and_returns_reply_speech"+ },+ {+ "file": "crates/openhuman-core/src/voice/live/registry.rs",+ "scope": "",+ "name": "LIVE_PROVIDERS",+ "type": "HookSlot<LiveProviderEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/live/registry_tests.rs: a_registered_provider_is_listed_after_the_built_in_ones"+ },+ {+ "file": "crates/openhuman-core/src/core/slots.rs",+ "scope": "",+ "name": "TEST_GLOBALS",+ "type": "std::cell::RefCell<HashMap<&'static str,Box<dyn Any>>>",+ "count": 1,+ "category": "A",+ "reason": "cfg(test) only: replaces a slot's process table with a per-thread one so a test's fake registration cannot reach a test on another thread. Not compiled into any shipped build.",+ "verification": "core/slots_tests.rs: entries_keep_registration_order_and_re_registering_keeps_position"+ },+ {+ "file": "crates/openhuman-core/src/threads/artifact_rows.rs",+ "scope": "",+ "name": "ARTIFACT_ROW_HANDLE",+ "type": "OnceLock<SubscriptionHandle>",+ "count": 1,+ "category": "A",+ "reason": "Keeps the one process-wide event-bus subscription that writes artifact rows alive and makes registration idempotent; it holds no data, and each event names the workspace and thread its row is written to.",+ "verification": "threads/artifact_rows_tests.rs: recording_an_artifact_twice_writes_one_row"++ },++ {++ "file": "crates/openhuman-core/src/mcp/host_cleanup.rs",++ "scope": "",++ "name": "CLIENTS",++ "type": "OnceLock<ClientTable<CleanupClient>>",++ "count": 1,++ "category": "B",++ "reason": "The canonical TinyMCP client table is keyed by the resolved agent directory. Host completion and exact-client eviction preserve the same directory fence across close and purge; no runtime guard is retained in the table.",++ "verification": "mcp/module_client_owner_tests.rs: orphaned_shutdown_cleanup_keeps_a_host_directory_reservation_until_confirmed; mcp/module_client/cleanup_tests.rs: a_pending_close_fences_the_folder_under_another_spelling"+ }+ ]diff --cc vendor/tinybusindex 9062dd8daa,d621ed0aaa..247e4d031b--- a/vendor/tinybus+++ b/vendor/tinybus@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 9062dd8daa6f7d8fa9fbb3eafc144f0e0f9d82f2-Subproject commit d621ed0aaa1c7b1bc5d0bf0d0abb10927a26bdaa++Subproject commit 247e4d031ba32dd4e6cad857725f2337fc851d98diff --cc vendor/tinymcpindex 10b03d1ab0,c68c1fe32b..06c02a6b75--- a/vendor/tinymcp+++ b/vendor/tinymcp@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 10b03d1ab00ecbd08bd41d5e83a5c350cbd7e357-Subproject commit c68c1fe32bdcec15bcf2ec4aa3e8d10c613d7b0d++Subproject commit 06c02a6b75fb53739245effce47941b39a131f57