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 'origin/main' into epic-8055-closeout-recovery
Steven Enamakel267f5ecc9f9b
diff --cc crates/openhuman-core/src/core/events.rsindex 64d5f72f8e,43b2db8693..2639488bd6--- a/crates/openhuman-core/src/core/events.rs+++ b/crates/openhuman-core/src/core/events.rs@@@ -369,10 -369,18 +369,13 @@@ pub enum DomainEventjob_id: String,success: bool,output: String,- },- /// A cron job requests delivery of its output to a channel.- CronDeliveryRequested {- job_id: String,- channel: String,- target: String,- output: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ tenant: Option<crate::core::runtime::Tenant>,},- /// A proactive message for the user's active channel.++ /// A proactive message (morning briefing, welcome, cron output, etc.)+ /// needs to be delivered to the user. The channels module routes it to+ /// the user's active channel.ProactiveMessageRequested {/// Identifies the source (e.g. `"cron:morning_briefing"`, `"cron:welcome"`).source: String,diff --cc crates/openhuman-core/src/core/events/variant_names.rsindex 0000000000,d0dc541e62..0404bcbb1fmode 000000,100644..100644--- a/crates/openhuman-core/src/core/events/variant_names.rs+++ b/crates/openhuman-core/src/core/events/variant_names.rs@@@ -1,0 -1,125 +1,124 @@@+ //! [`DomainEvent::variant_name`]: the stable name of each variant.++ use super::DomainEvent;++ impl DomainEvent {+ /// Stable variant name without payload (avoids Debug format coupling).+ pub fn variant_name(&self) -> &'static str {+ match self {+ Self::AgentTurnStarted { .. } => "AgentTurnStarted",+ Self::AgentTurnCompleted { .. } => "AgentTurnCompleted",+ Self::ConversationTurnCommitted { .. } => "ConversationTurnCommitted",+ Self::AgentError { .. } => "AgentError",+ Self::SubagentSpawned { .. } => "SubagentSpawned",+ Self::SubagentCompleted { .. } => "SubagentCompleted",+ Self::SubagentFailed { .. } => "SubagentFailed",+ Self::SubagentAwaitingUser { .. } => "SubagentAwaitingUser",+ Self::AgentOrchestrationSpawned { .. } => "AgentOrchestrationSpawned",+ Self::AgentOrchestrationCompleted { .. } => "AgentOrchestrationCompleted",+ Self::AgentOrchestrationFailed { .. } => "AgentOrchestrationFailed",+ Self::AgentOrchestrationClosed { .. } => "AgentOrchestrationClosed",+ Self::RunQueueMessageQueued { .. } => "RunQueueMessageQueued",+ Self::RunQueueFollowupDispatched { .. } => "RunQueueFollowupDispatched",+ Self::RunQueueInterrupted { .. } => "RunQueueInterrupted",+ Self::RunQueueMessageDelivered { .. } => "RunQueueMessageDelivered",+ Self::RunQueueSteerRequeued { .. } => "RunQueueSteerRequeued",+ Self::MonitorStatusChanged { .. } => "MonitorStatusChanged",+ Self::MonitorLine { .. } => "MonitorLine",+ Self::MemoryStored { .. } => "MemoryStored",+ Self::MemoryRecalled { .. } => "MemoryRecalled",+ Self::ChannelInboundMessage { .. } => "ChannelInboundMessage",+ Self::ChannelMessageReceived { .. } => "ChannelMessageReceived",+ Self::ChannelMessageProcessed { .. } => "ChannelMessageProcessed",+ Self::ChannelReactionReceived { .. } => "ChannelReactionReceived",+ Self::ChannelReactionSent { .. } => "ChannelReactionSent",+ Self::ChannelConnected { .. } => "ChannelConnected",+ Self::ChannelDisconnected { .. } => "ChannelDisconnected",+ Self::CronJobTriggered { .. } => "CronJobTriggered",+ Self::CronJobCompleted { .. } => "CronJobCompleted",- Self::CronDeliveryRequested { .. } => "CronDeliveryRequested",+ Self::ProactiveMessageRequested { .. } => "ProactiveMessageRequested",+ Self::CronSystemJobDue { .. } => "CronSystemJobDue",+ Self::FlowRunProgress { .. } => "FlowRunProgress",+ Self::FlowRunStarted { .. } => "FlowRunStarted",+ Self::FlowRunFinished { .. } => "FlowRunFinished",+ Self::FlowChanged { .. } => "FlowChanged",+ Self::WorkflowLoaded { .. } => "WorkflowLoaded",+ Self::WorkflowStopped { .. } => "WorkflowStopped",+ Self::WorkflowStartFailed { .. } => "WorkflowStartFailed",+ Self::WorkflowExecuted { .. } => "WorkflowExecuted",+ Self::WorkflowsChanged { .. } => "WorkflowsChanged",+ Self::ToolExecutionStarted { .. } => "ToolExecutionStarted",+ Self::ToolExecutionCompleted { .. } => "ToolExecutionCompleted",+ Self::WorkspacePrepared { .. } => "WorkspacePrepared",+ Self::WorkspaceViolation { .. } => "WorkspaceViolation",+ Self::WorkspaceCleanup { .. } => "WorkspaceCleanup",+ Self::WebhookIncomingRequest { .. } => "WebhookIncomingRequest",+ Self::WebhookReceived { .. } => "WebhookReceived",+ Self::WebhookRegistered { .. } => "WebhookRegistered",+ Self::WebhookUnregistered { .. } => "WebhookUnregistered",+ Self::WebhookProcessed { .. } => "WebhookProcessed",+ Self::ComposioTriggerReceived { .. } => "ComposioTriggerReceived",+ Self::ComposioConnectionCreated { .. } => "ComposioConnectionCreated",+ Self::ComposioConnectionDeleted { .. } => "ComposioConnectionDeleted",+ Self::ComposioIntegrationsChanged { .. } => "ComposioIntegrationsChanged",+ Self::ComposioActionExecuted { .. } => "ComposioActionExecuted",+ Self::ComposioConfigChanged { .. } => "ComposioConfigChanged",+ Self::TriggerEvaluated { .. } => "TriggerEvaluated",+ Self::TriggerEscalated { .. } => "TriggerEscalated",+ Self::TriggerEscalationFailed { .. } => "TriggerEscalationFailed",+ Self::NotificationIngested { .. } => "NotificationIngested",+ Self::NotificationTriaged { .. } => "NotificationTriaged",+ Self::InboundEventDropped { .. } => "InboundEventDropped",+ Self::InboundDeferred { .. } => "InboundDeferred",+ Self::InboundDeadLettered { .. } => "InboundDeadLettered",+ Self::DevicePaired { .. } => "DevicePaired",+ Self::DeviceRevoked { .. } => "DeviceRevoked",+ Self::DevicePeerOnline { .. } => "DevicePeerOnline",+ Self::DevicePeerOffline { .. } => "DevicePeerOffline",+ Self::DeviceTunnelFrame { .. } => "DeviceTunnelFrame",+ Self::SystemStartup { .. } => "SystemStartup",+ Self::SystemShutdown { .. } => "SystemShutdown",+ Self::SystemRestartRequested { .. } => "SystemRestartRequested",+ Self::SystemShutdownRequested { .. } => "SystemShutdownRequested",+ Self::AutonomyConfigChanged => "AutonomyConfigChanged",+ Self::AgentPathsChanged => "AgentPathsChanged",+ Self::ActiveWorkspaceChanged { .. } => "ActiveWorkspaceChanged",+ Self::HealthChanged { .. } => "HealthChanged",+ Self::HealthRestarted { .. } => "HealthRestarted",+ Self::KeyringConsentRequired => "KeyringConsentRequired",+ Self::KeyringDecryptFailed { .. } => "KeyringDecryptFailed",+ Self::SessionExpired { .. } => "SessionExpired",+ Self::CredentialChanged { .. } => "CredentialChanged",+ Self::ApprovalRequested { .. } => "ApprovalRequested",+ Self::ApprovalDecided { .. } => "ApprovalDecided",+ Self::FlowApprovalRequested { .. } => "FlowApprovalRequested",+ Self::PlanReviewRequested { .. } => "PlanReviewRequested",+ Self::PlanReviewDecided { .. } => "PlanReviewDecided",+ Self::ExternalTransferPending { .. } => "ExternalTransferPending",+ Self::ApprovalGateOverrideIgnored { .. } => "ApprovalGateOverrideIgnored",+ Self::ApprovalGateDisabled { .. } => "ApprovalGateDisabled",+ Self::ArtifactReady { .. } => "ArtifactReady",+ Self::ArtifactFailed { .. } => "ArtifactFailed",+ Self::ArtifactPending { .. } => "ArtifactPending",+ Self::McpServerInstalled { .. } => "McpServerInstalled",+ Self::McpServerConnected { .. } => "McpServerConnected",+ Self::McpServerDisconnected { .. } => "McpServerDisconnected",+ Self::McpClientToolExecuted { .. } => "McpClientToolExecuted",+ Self::McpToolRejected { .. } => "McpToolRejected",+ Self::McpServerProbeTimedOut { .. } => "McpServerProbeTimedOut",+ Self::McpServerTransportDropped { .. } => "McpServerTransportDropped",+ Self::McpServerReconnected { .. } => "McpServerReconnected",+ Self::McpServerReconnectFailed { .. } => "McpServerReconnectFailed",+ Self::McpServerParked { .. } => "McpServerParked",+ Self::EmbeddingModelUnhealthy { .. } => "EmbeddingModelUnhealthy",+ Self::ProviderApiKeyRejected { .. } => "ProviderApiKeyRejected",+ Self::TaskSourceFetched { .. } => "TaskSourceFetched",+ Self::TaskSourceTaskIngested { .. } => "TaskSourceTaskIngested",+ Self::TaskSourceFetchFailed { .. } => "TaskSourceFetchFailed",+ Self::ThreadGoalUpdated { .. } => "ThreadGoalUpdated",+ Self::ThreadGoalCleared { .. } => "ThreadGoalCleared",+ Self::ThreadTodosChanged { .. } => "ThreadTodosChanged",+ Self::ThreadRunModeChanged { .. } => "ThreadRunModeChanged",+ }+ }+ }diff --cc crates/openhuman-core/src/memory/engine_tests.rsindex 2676c28ec3,29081d1480..4c01a4f6e7--- a/crates/openhuman-core/src/memory/engine_tests.rs+++ b/crates/openhuman-core/src/memory/engine_tests.rs@@@ -1,8 -1,22 +1,23 @@@use super::*;use crate::memory::test_fixtures::config_in;-+use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};+ struct ClearInstalledHostEngine;++ impl Drop for ClearInstalledHostEngine {+ fn drop(&mut self) {+ clear_host_engine();+ }+ }++ struct RemoveTestEngine(std::path::PathBuf);++ impl Drop for RemoveTestEngine {+ fn drop(&mut self) {+ remove_test_engine(&self.0);+ }+ }+fn off_reason(binding: Binding) -> String {match binding {Binding::Off { reason, .. } => reason,@@@ -10,6 -24,143 +25,159 @@@}}+ async fn assert_host_scrubbing(+ bound: BoundEngine,+ reference: &tinymemory_api::conformance::ReferenceEngine,+ ) {+ const SECRET: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";+ const PHONE: &str = "+15551234567";+ const BARE_NUMBER: &str = "79927398713";++ bound+ .engine+ .store(tinymemory_api::StoreItem::document(+ format!("contact {PHONE}; key={SECRET}; reference {BARE_NUMBER}"),+ tinymemory_api::MemoryMeta::default(),+ ))+ .await+ .expect("the bound engine accepts the test item");++ let saved = reference+ .list(tinymemory_api::ListRequest::new(+ tinymemory_api::MetaFilter::default(),+ 5,+ ))+ .await+ .expect("reference engine lists the saved item");+ let text = saved+ .items+ .iter()+ .find(|hit| hit.text.contains(BARE_NUMBER))+ .map(|hit| hit.text.as_str())+ .expect("the corroborated host policy preserves an unqualified number");++ assert!(+ !text.contains(SECRET),+ "credentials are scrubbed before store"+ );+ assert!(+ !text.contains(PHONE),+ "phone numbers are scrubbed before store"+ );+ }++ #[tokio::test]+ async fn installed_host_engine_binding_uses_the_host_scrub_policy() {+ const CHILD_FLAG: &str = "OPENHUMAN_MEMORY_HOST_POLICY_CHILD";+ const CHILD_MARKER: &str = "HOST_ENGINE_POLICY_CHILD_EXECUTED";++ if std::env::var_os(CHILD_FLAG).as_deref() != Some(std::ffi::OsStr::new("1")) {+ let exact_test =+ "memory::engine::tests::installed_host_engine_binding_uses_the_host_scrub_policy";+ let child = std::process::Command::new(std::env::current_exe().unwrap())+ .arg("--exact")+ .arg(exact_test)+ .arg("--nocapture")+ .env(CHILD_FLAG, "1")+ .output()+ .expect("test child starts");+ let stdout = String::from_utf8_lossy(&child.stdout);+ let stderr = String::from_utf8_lossy(&child.stderr);+ assert!(+ child.status.success(),+ "host-engine child failed: stdout={stdout}\nstderr={stderr}"+ );+ assert_eq!(+ stdout.matches(CHILD_MARKER).count(),+ 1,+ "the exact child test must execute once: stdout={stdout}\nstderr={stderr}"+ );+ return;+ }++ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());++ clear_host_engine();+ let _cleanup = ClearInstalledHostEngine;+ install_host_engine(reference.clone());+ let bound = resolve(&config)+ .engine()+ .expect("installed host engine binds");+ assert_host_scrubbing(bound, &reference).await;+ println!("{CHILD_MARKER}");+ }++ #[tokio::test]+ async fn test_engine_binding_uses_the_host_scrub_policy() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());++ let _cleanup = RemoveTestEngine(config.workspace_dir.clone());+ install_test_engine(&config.workspace_dir, reference.clone());+ let bound = resolve(&config).engine().expect("test engine binds");+ assert_host_scrubbing(bound, &reference).await;+ }++ #[tokio::test]+ async fn profile_engine_binding_uses_the_host_scrub_policy() {+ let tmp = tempfile::tempdir().unwrap();+ let profile_id = "6512ab0f6512ab0f6512ab0f";+ let mut config = config_in(&tmp);+ config.memory.agent_id = Some(profile_id.to_string());+ config.memory.root = Some(format!("user:{profile_id}"));+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());+ let capabilities = Arc::new(crate::profiles::capabilities::ProfileCapabilities::new(+ None,+ None,+ None,+ Default::default(),+ Vec::new(),+ Some(reference.clone()),+ ));+ let mut overrides = crate::agent::host_overrides::HostOverrides::default();+ overrides.profile_capabilities = Some(capabilities);+ let parent = crate::core::runtime::CoreContext::for_test(+ crate::core::runtime::DomainSet::full(),+ Some(config.workspace_dir.clone()),+ );+ let profile = parent.derive_with(+ crate::core::runtime::ContextOverlay::new(+ config.clone(),+ crate::core::runtime::DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .profile(profile_id)+ .host_overrides(Arc::new(overrides)),+ );++ crate::core::runtime::CoreContext::scope(profile, async {+ let bound = resolve(&config)+ .engine()+ .expect("profile engine binds with its forced root");+ assert_host_scrubbing(bound, &reference).await;+ })+ .await;+ }+++#[test]++fn a_local_session_token_is_not_a_tinyhumans_credential() {++ let tmp = tempfile::tempdir().unwrap();++ let config = config_in(&tmp);++ AuthService::from_config(&config)++ .store_provider_token(++ APP_SESSION_PROVIDER,++ DEFAULT_AUTH_PROFILE_NAME,++ "desktop.test.local",++ std::collections::HashMap::new(),++ true,++ )++ .unwrap();++ assert!(!has_key(&config, TINYHUMANS_ENGINE));++}++#[test]fn tinyhumans_with_nothing_registered_is_unavailable() {let tmp = tempfile::tempdir().unwrap();diff --cc crates/openhuman-core/src/memory/error_tests.rsindex 59ab83b3c3,5b38ac396a..19bf78d181--- a/crates/openhuman-core/src/memory/error_tests.rs+++ b/crates/openhuman-core/src/memory/error_tests.rs@@@ -192,3 -101,3 +192,18 @@@ fn typed_insufficient_credits_maps_withassert_eq!(error.message, "insufficient credits: HTTP 402");assert!(error.expected_user_state);}++++++#[test]++fn upstream_unavailable_is_transient_not_account_wide() {++ use tinymemory_api::Error as E;++++ assert!(E::Off("disabled".into()).is_account_wide());++ assert!(E::Unauthorized("bad key".into()).is_account_wide());++ assert!(E::InsufficientCredits("top up".into()).is_account_wide());++ assert!(!E::Unavailable("timeout".into()).is_account_wide());++ assert!(E::Unavailable("timeout".into()).is_transient());++ assert!(!E::InvalidRequest("bad filter".into()).is_account_wide());++ assert!(!E::Conflict("duplicate".into()).is_account_wide());++ assert!(!E::Engine("corrupt index".into()).is_account_wide());++}diff --cc crates/openhuman-core/src/memory/lifecycle/jobs.rsindex c9a5bc1e64,ad5e5e5030..6827688bd0--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs@@@ -50,12 -54,14 +54,14 @@@ struct FileQueueStoreimpl QueueStore for FileQueueStore {fn load(&self) -> QueueState {- crate::memory::state_store::load(&self.workspace_dir, STATE)- .unwrap_or_else(|error| {- match super::super::state_store::load(&self.workspace_dir, STATE) {++ match super::super::state_store::load_workspace_strict(&self.workspace_dir, STATE) {+ Ok(Some(queue)) => queue,+ Ok(None) => QueueState::default(),+ Err(error) => {tracing::warn!(%error, "[memory:jobs] reading the queue failed");- None- })- .unwrap_or_default()+ QueueState::default()+ }+ }}fn save(&self, state: &QueueState) -> std::result::Result<(), String> {diff --cc crates/openhuman-core/src/memory/lifecycle/jobs_tests.rsindex 3fa4344b5b,c5327f5a4f..da76292ee0--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs@@@ -47,10 -47,13 +47,10 @@@ fn corrupt_legacy_job_queue_is_skipped_assert_eq!(store.load(), QueueState::default());assert!(- !file.exists(),- "corrupt queue must not be silently replaced"- );- assert_eq!(- std::fs::read(file.with_extension("json.corrupt")).unwrap(),- b"{\"pending\":["+ file.exists(),- "the one-time state import must leave the legacy file untouched"++ "the read-only legacy import must leave corrupt bytes in place");+ assert_eq!(std::fs::read(file).unwrap(), b"{\"pending\":[");}#[tokio::test]diff --cc crates/openhuman-core/src/memory/mod.rsindex b4083c32b2,e5e072fd19..99b582cad2--- a/crates/openhuman-core/src/memory/mod.rs+++ b/crates/openhuman-core/src/memory/mod.rs@@@ -27,8 -26,10 +26,11 @@@ pub mod deletionpub mod engine;pub mod engine_registry;pub mod error;++pub use error::{MemoryError, MemoryResult};pub mod explore;- pub mod guard;+ #[cfg(test)]+ #[path = "guard_tests.rs"]+ mod guard;pub mod import;pub mod layout_migration;pub mod lifecycle;diff --cc crates/openhuman-core/src/memory/ops.rsindex 6ab05b4c42,dc3874091b..fcc9a470be--- a/crates/openhuman-core/src/memory/ops.rs+++ b/crates/openhuman-core/src/memory/ops.rs@@@ -498,16 -498,11 +498,15 @@@ fn channel_key(channel: &str) -> Strinchannel.trim().to_ascii_lowercase()}- /// Reads only the legacy map written by prior releases. Corrupt JSON is- /// skipped and left untouched; current code never creates or updates it.+ /// Reads only the legacy map written by prior releases. Corrupt JSON keeps the+ /// existing quarantine behavior; current code never creates or updates it.#[cfg(feature = "channels")]fn legacy_channel_threads(workspace: &Path, channel: &str) -> BTreeSet<String> {- // Prefer the state-store value: layout migration may already have- // removed the legacy file after importing it. The direct file fallback- // below preserves the legacy lookup when storage cannot be opened. As- // with StateKv's best-effort import, malformed JSON is skipped without- // moving or rewriting the source file.- if let Ok(Some(all)) = crate::memory::state_store::load::<BTreeMap<String, BTreeSet<String>>>(- let all = match super::state_store::load::<BTreeMap<String, BTreeSet<String>>>(++ // Prefer the workspace state value, which may have imported and removed++ // the old file. If no value is available (including a failed import),++ // retain the legacy read path. Malformed JSON is skipped without moving++ // or rewriting its source.++ if let Ok(Some(all)) = super::state_store::load::<BTreeMap<String, BTreeSet<String>>>(workspace,"channel_threads",) {diff --cc crates/openhuman-core/src/memory/ops_tests.rsindex 75b54b1dd7,c41743a6fe..a431819594--- a/crates/openhuman-core/src/memory/ops_tests.rs+++ b/crates/openhuman-core/src/memory/ops_tests.rs@@@ -15,27 -15,6 +15,28 @@@ fn learn_params(text: &str) -> LearnPar}}+#[cfg(feature = "channels")]+#[test]+fn corrupt_legacy_channel_threads_are_skipped_without_modifying_the_source() {+ let tmp = tempfile::tempdir().unwrap();+ let workspace = tmp.path().join("workspace");+ let memory_dir = workspace.join("memory");+ std::fs::create_dir_all(&memory_dir).unwrap();+ let legacy_file = memory_dir.join("channel_threads.json");+ let corrupt = br#"{"discord":["unfinished"}"#;+ std::fs::write(&legacy_file, corrupt).unwrap();++ let threads = legacy_channel_threads(&workspace, "discord");++ assert!(threads.is_empty(), "invalid legacy state is skipped");+ assert_eq!(std::fs::read(&legacy_file).unwrap(), corrupt);+ assert!(+ !legacy_file.with_extension("json.corrupt").exists(),+ "a state read must not move or quarantine the legacy file"+ );+}+++#[cfg(feature = "channels")]#[tokio::test]async fn reserved_thread_matching_uses_module_identity_boundaries() {diff --cc crates/openhuman-core/src/memory/sources/state.rsindex bc4dbd0a80,60643d70b4..71e47f2d84--- a/crates/openhuman-core/src/memory/sources/state.rs+++ b/crates/openhuman-core/src/memory/sources/state.rs@@@ -16,13 -16,19 +16,19 @@@ static LOCK: LazyLock<Mutex<()>> = Lazyconst STATE: &str = "sources_state";+ fn path(workspace_dir: &Path) -> PathBuf {+ crate::memory::state_store::legacy_path(workspace_dir, STATE)+ }+fn read_all(workspace_dir: &Path) -> BTreeMap<String, SourceState> {- crate::memory::state_store::load(workspace_dir, STATE)- .unwrap_or_else(|error| {- tracing::warn!(error = %error, "[memory:sources] reading sync state failed");- None- })- .unwrap_or_default()- match crate::memory::state_store::load(workspace_dir, STATE) {++ match crate::memory::state_store::load_strict(workspace_dir, STATE) {+ Ok(Some(state)) => state,+ Ok(None) => BTreeMap::new(),+ Err(error) => {+ tracing::warn!(%error, "[memory:sources] reading sync state failed");+ BTreeMap::new()+ }+ }}fn write_all(workspace_dir: &Path, all: &BTreeMap<String, SourceState>) {diff --cc crates/openhuman-core/src/memory/sources/state_tests.rsindex 709db41e62,fab1ef3af4..2688479c94--- a/crates/openhuman-core/src/memory/sources/state_tests.rs+++ b/crates/openhuman-core/src/memory/sources/state_tests.rs@@@ -2,18 -2,21 +2,16 @@@ use super::*use tinymemory_integrations::sources::SourceStatus;#[test]-fn corrupt_source_state_file_is_set_aside() {+fn corrupt_legacy_source_state_is_skipped_and_left_in_place() {let tmp = tempfile::tempdir().unwrap();- let file = path(tmp.path());+ let file = crate::memory::state_store::legacy_path(tmp.path(), "sources_state");std::fs::create_dir_all(file.parent().unwrap()).unwrap();-- std::fs::write(&file, b"{\"source-1\":").unwrap();++ let corrupt = b"{\"source-1\":";++ std::fs::write(&file, corrupt).unwrap();assert!(load(tmp.path()).is_empty());-- assert!(- file.exists(),- "state import leaves the legacy file in place"- !file.exists(),- "corrupt state must not be silently replaced"-- );- assert_eq!(std::fs::read(file).unwrap(), b"{\"source-1\":");- assert_eq!(- std::fs::read(file.with_extension("json.corrupt")).unwrap(),- b"{\"source-1\":"- );++ assert!(file.exists(), "the read-only legacy load must not move the file");++ assert_eq!(std::fs::read(file).unwrap(), corrupt);}#[test]diff --cc crates/openhuman-core/src/memory/state_store.rsindex 87a24a8aec,df09b52747..79f098be76--- a/crates/openhuman-core/src/memory/state_store.rs+++ b/crates/openhuman-core/src/memory/state_store.rs@@@ -31,6 -35,248 +35,263 @@@ fn open(workspace_dir: &Path, name: &stOk(kv)}+ fn open_quarantining<T: DeserializeOwned>(workspace_dir: &Path, name: &str) -> Result<StateKv> {+ let kv = StateKv::open(workspace_dir, OWNER, NS)?;+ kv.import_file_quarantining::<T>(name, &legacy_path(workspace_dir, name))?;+ Ok(kv)+ }++ fn profile_layout_for_workspace(+ workspace_dir: &Path,+ ) -> Option<crate::config::schema::ProfileLayout> {+ use crate::config::schema::profile_layout::{PROFILE_WORKSPACE_DIR, USERS_DIR};++ if let Some(profile) = crate::config::schema::ProfileLayout::of_workspace(workspace_dir) {+ return Some(profile);+ }+ if workspace_dir.file_name()? != std::ffi::OsStr::new(PROFILE_WORKSPACE_DIR) {+ return None;+ }+ let profile_dir = workspace_dir.parent()?;+ if profile_dir.parent()?.file_name()? != std::ffi::OsStr::new(USERS_DIR) {+ return None;+ }+ Some(crate::config::schema::ProfileLayout::at(+ profile_dir.to_path_buf(),+ ))+ }++ fn stable_workspace_identity(workspace_dir: &Path) -> Result<PathBuf> {+ // Layout v1 and v2 use `workspace/` and `files/` under the same profile.+ // Hash the canonical profile directory when known, so a layout migration+ // does not change the queue's scope. For ordinary/custom workspaces use a+ // lexically normalized absolute path; filesystem canonicalization would+ // change identity when a not-yet-created workspace first appears.+ let path = profile_layout_for_workspace(workspace_dir)+ .map(|profile| profile.dir)+ .unwrap_or_else(|| workspace_dir.to_path_buf());+ let absolute = if path.is_absolute() {+ path+ } else {+ std::env::current_dir()?.join(path)+ };+ let mut normalized = PathBuf::new();+ for component in absolute.components() {+ match component {+ std::path::Component::CurDir => {}+ std::path::Component::ParentDir => {+ normalized.pop();+ }+ component => normalized.push(component.as_os_str()),+ }+ }+ Ok(normalized)+ }++ fn workspace_scope(workspace_dir: &Path) -> Result<crate::storage::Scope> {+ let path = stable_workspace_identity(workspace_dir)?;+ let digest = sha2::Sha256::digest(path.to_string_lossy().as_bytes());+ let suffix = digest+ .iter()+ .take(12)+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ Ok(crate::storage::scope_for_module(+ None,+ &format!("memory-workspace-{suffix}"),+ )?)+ }++ fn open_workspace_quarantining<T: DeserializeOwned>(+ workspace_dir: &Path,+ name: &str,+ ) -> Result<StateKv> {+ let scope = workspace_scope(workspace_dir)?;+ let backend = crate::storage::local::backend_for(workspace_dir)?;+ open_workspace_quarantining_on::<T>(workspace_dir, &backend, &scope, name)+ }++ fn open_workspace_quarantining_on<T: DeserializeOwned>(+ workspace_dir: &Path,+ backend: &std::sync::Arc<dyn crate::storage::StorageBackend>,+ scope: &crate::storage::Scope,+ name: &str,+ ) -> Result<StateKv> {+ let kv = StateKv::on_backend(backend, scope, OWNER, NS)?;+ kv.import_file_quarantining::<T>(name, &legacy_path(workspace_dir, name))?;+ if name == "pending_deletions" {+ migrate_existing_queue_scopes(+ workspace_dir,+ backend,+ scope,+ &kv,+ active_workspace_matches(workspace_dir),+ )?;+ }+ Ok(kv)+ }++ fn active_workspace_matches(workspace_dir: &Path) -> bool {+ let dispatch = crate::core::runtime::DispatchCtx::ambient();+ let active_workspace = dispatch+ .resolved()+ .and_then(|context| context.workspace_dir().ok());+ active_workspace+ .as_deref()+ .and_then(|active| stable_workspace_identity(active).ok())+ .zip(stable_workspace_identity(workspace_dir).ok())+ .is_some_and(|(active, requested)| active == requested)+ }++ fn legacy_queue_scopes(workspace_dir: &Path, include_local: bool) -> Vec<crate::storage::Scope> {+ let known_profile = profile_layout_for_workspace(workspace_dir)+ .and_then(|profile| profile.dir.file_name()?.to_str().map(str::to_owned));+ let mut scopes = Vec::new();+ if include_local {+ scopes.push(crate::storage::Scope::local());+ }+ if let Some(profile) = &known_profile {+ scopes.push(crate::storage::scope_for_profile(profile));+ }++ // A task may still carry the old profile/agent scope for a custom+ // workspace that the profile-layout helper cannot identify. Only inspect+ // that task's own scope, and when the path did identify a profile require+ // it to match; never enumerate other tenants on a shared backend.+ let dispatch = crate::core::runtime::DispatchCtx::ambient();+ if active_workspace_matches(workspace_dir) {+ if let Ok(tenant) = dispatch.tenant() {+ match (tenant.profile, tenant.agent) {+ (Some(profile), _)+ if known_profile.as_ref().is_none_or(|known| known == &profile) =>+ {+ scopes.push(crate::storage::scope_for_profile(&profile));+ }+ (None, Some(agent)) if known_profile.is_none() => {+ scopes.push(crate::storage::scope_for_agent(&agent));+ }+ _ => {}+ }+ }+ }++ scopes.sort_by(|left, right| left.as_str().cmp(right.as_str()));+ scopes.dedup();+ scopes+ }++ fn queue_migration_marker(scope: &crate::storage::Scope) -> String {+ let digest = sha2::Sha256::digest(scope.as_str().as_bytes());+ let suffix = digest+ .iter()+ .take(8)+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ format!("{QUEUE_MIGRATION_PREFIX}_{suffix}")+ }++ fn migrate_existing_queue_scopes(+ workspace_dir: &Path,+ backend: &std::sync::Arc<dyn crate::storage::StorageBackend>,+ target_scope: &crate::storage::Scope,+ target: &StateKv,+ include_local: bool,+ ) -> Result<()> {+ // The per-source marker records that migration has run, but each queue+ // access still checks the eligible source value. A concurrently running+ // older host may append after a pass; the next access must see that owed+ // work. Once removed, a normally drained value is absent from the source,+ // so it cannot be resurrected after a restart.+ for source_scope in legacy_queue_scopes(workspace_dir, include_local) {+ if &source_scope == target_scope {+ continue;+ }+ let marker = queue_migration_marker(&source_scope);+ let source = StateKv::on_backend(backend, &source_scope, OWNER, NS)?;+ let Some(previous) =+ source.get::<Vec<super::deletion::PendingDeletion>>("pending_deletions")?+ else {+ if target.get::<String>(&marker)?.as_deref() != Some("complete") {+ target.put(&marker, &"complete")?;+ }+ continue;+ };+ if previous.is_empty() {+ if target.get::<String>(&marker)?.as_deref() != Some("complete") {+ target.put(&marker, &"complete")?;+ }+ continue;+ }+ let transferred = previous.clone();+ target.update::<Vec<super::deletion::PendingDeletion>, _>(+ "pending_deletions",+ move |pending| {+ let mut changed = false;+ for deletion in &previous {+ if !pending.contains(deletion) {+ pending.push(deletion.clone());+ changed = true;+ }+ }+ ((), changed)+ },+ )?;+ source.update::<Vec<super::deletion::PendingDeletion>, _>(+ "pending_deletions",+ move |pending| {+ let before = pending.len();+ pending.retain(|deletion| !transferred.contains(deletion));+ let changed = before != pending.len();+ ((), changed)+ },+ )?;+ target.put(&marker, &"complete")?;+ }+ Ok(())+ }++ /// A workspace-owned state value in a deterministic local module scope. Use+ /// this for queues that must remain readable after the ambient profile scope+ /// has ended, while remaining isolated from other workspaces on shared storage.+ pub(crate) fn load_workspace<T: DeserializeOwned + Send + 'static>(+ workspace_dir: &Path,+ name: &str,+ ) -> Result<Option<T>> {+ open_workspace_quarantining::<T>(workspace_dir, name)?.get(name)+ }+++/// Reads a workspace-owned state value without quarantining malformed legacy++/// bytes. Host-owned readers use this when the legacy file is a read-only++/// compatibility source; the returned error is logged and the original file++/// remains available for diagnosis or a later explicit migration.++pub(crate) fn load_workspace_strict<T: DeserializeOwned + Send + 'static>(++ workspace_dir: &Path,++ name: &str,++) -> Result<Option<T>> {++ let scope = workspace_scope(workspace_dir)?;++ let backend = crate::storage::local::backend_for(workspace_dir)?;++ let kv = StateKv::on_backend(&backend, &scope, OWNER, NS)?;++ kv.import_file_strict(name, &legacy_path(workspace_dir, name))?;++ kv.get(name)++}+++ /// Stores a workspace-owned state value in its deterministic local module scope.+ pub(crate) fn save_workspace<T>(workspace_dir: &Path, name: &str, value: &T) -> Result<()>+ where+ T: Serialize + DeserializeOwned + Send + 'static,+ {+ open_workspace_quarantining::<T>(workspace_dir, name)?.put(name, value)+ }++ /// Removes a workspace-owned state value from its deterministic local module scope.+ pub(crate) fn remove_workspace<T: DeserializeOwned + Send + 'static>(+ workspace_dir: &Path,+ name: &str,+ ) -> Result<()> {+ open_workspace_quarantining::<T>(workspace_dir, name)?.delete(name)?;+ Ok(())+ }+/// [`open`] for a value a damaged legacy file must not reset.fn open_strict(workspace_dir: &Path, name: &str) -> Result<StateKv> {let kv = StateKv::open(workspace_dir, OWNER, NS)?;diff --cc docs/TEST-COVERAGE-MATRIX.mdindex 19211a3bbc,9830c57e3c..7d2a90f58a--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@@ -426,11 -426,11 +426,11 @@@ The thread JSONL store moved to `tinyag### 9.5 Flow Pre-authorization (save+enable approval card)-| ID | Feature | Layer | Test path(s) | Status | Notes |-| ----- | ------------------------------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 9.5.1 | Approval manifest computation | RU | `crates/openhuman-core/src/flows/ops_tests.rs::{approval_manifest_lists_gated_nodes_and_skips_curated_reads,approval_manifest_marks_blocked_classes_under_readonly_tier,approval_manifest_dedupes_repeated_tools_and_flags_dynamic_slugs,approval_manifest_discloses_agent_ref_nodes_only}` | ✅ | `compute_approval_manifest` mirrors runtime gating: curated Composio reads excluded, tier-Blocked classes informational, trust-key dedupe, dynamic `=` slugs and `agent_ref` nodes disclosed. `flows.approval_manifest` RPC joins against existing `flow_tool_trust`. |+| ID | Feature | Layer | Test path(s) | Status | Notes |+| ----- | ------------------------------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 9.5.1 | Approval manifest computation | RU | `crates/openhuman-core/src/flows/ops_approval_manifest_and_catalog_tests.rs::{approval_manifest_lists_gated_nodes_and_skips_curated_reads,approval_manifest_marks_blocked_classes_under_readonly_tier,approval_manifest_dedupes_repeated_tools_and_flags_dynamic_slugs,approval_manifest_discloses_agent_ref_nodes_only}`, `tests/tinyflows_published_prompt_e2e.rs::published_module_public_import_uses_authoring_bus_in_a_cold_process` | ✅ | `compute_approval_manifest` mirrors runtime gating: curated Composio reads excluded, tier-Blocked classes informational, trust-key dedupe, dynamic `=` slugs and `agent_ref` nodes disclosed. The published-module E2E also verifies Catalog.ApprovalManifest migration and host classification over TinyBus. `flows.approval_manifest` RPC joins against existing `flow_tool_trust`. || 9.5.2 | Flow trust store (list / delete / preauth audit) | RU | `crates/openhuman-core/src/security/approval/store.rs::tests::{list_flow_trust_returns_sorted_grants_scoped_to_flow,delete_flow_trust_named_removes_only_named_grants,delete_flow_trust_all_purges_only_that_flow,record_flow_preauthorization_lands_in_audit_not_pending}` | ✅ | Batch pre-grants via `approval.preauthorize_flow` are idempotent, flow-scoped, and each new grant lands as a born-decided `approve_always_for_flow` audit row (Approval history, never `list_pending`). Flow deletion purges the flow's grants. |- | 9.5.3 | Consolidated Approve-all/Deny card + enable flow | VU | `app/src/hooks/useFlowPreauthorization.test.ts`, `app/src/components/flows/FlowPreauthorizationCard.test.tsx` | ✅ | Hook: direct enable when nothing missing, grant-then-enable ordering on Approve all, Deny leaves the flow saved-but-disabled, fail-open on manifest RPC errors. Card: exactly two actions, per-kind rows (approvable/blocked/dynamic/agent), busy + error states. |+ | 9.5.3 | Consolidated Approve-all/Deny card + enable flow | VU | `app/src/hooks/useFlowPreauthorization.test.ts`, `app/src/components/flows/FlowPreauthorizationCard.test.tsx` | ✅ | Hook: direct enable when nothing missing, grant-then-enable ordering on Approve all, Deny leaves the flow saved-but-disabled, fail-open on manifest RPC errors. Card: exactly two actions, per-kind rows (approvable/blocked/dynamic/agent), busy + error states. |---diff --cc scripts/ci/module-boundaries.jsonindex 0055f5b324,e690198704..e79ec5e1c3--- a/scripts/ci/module-boundaries.json+++ b/scripts/ci/module-boundaries.json@@@ -30,11 -30,7 +30,12 @@@"tinysearch-core","cpal","tinyflows-module",+ "tinyflows",+ "tinyflows-catalog",+ "tinyflows-copilot",+ "tinyflows-drivers",- "tinyflows-schedule"++ "tinyflows-schedule",+ "tinyeventqueues"],"implementationPrefixes": ["tinyjuice-",