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 origin/main into remove-composio-memory-sync
Steven Enamakelcad7abd3e839
diff --cc crates/openhuman-core/src/config/schema/memory_tests.rsindex 589bcff715,63b8fc7add..0b6c13db9e--- a/crates/openhuman-core/src/config/schema/memory_tests.rs+++ b/crates/openhuman-core/src/config/schema/memory_tests.rs@@@ -150,50 -150,6 +150,56 @@@ target = "https://example.com/feed.xmlassert_eq!(config.sources[0].label, "", "label defaults to empty");}+#[test]+fn drops_a_stale_composio_source_and_keeps_every_other_kind() {+ let config: MemoryConfig = toml::from_str(+ r#"+[[sources]]+id = "src-composio"+kind = "composio"+target = "gmail"++[[sources]]+id = "src-link"+kind = "link"+target = "https://example.com"++[[sources]]+id = "src-github"+kind = "github"+target = "o/r"++[[sources]]+id = "src-rss"+kind = "rss"+target = "https://example.com/feed.xml"++[[sources]]+id = "src-folder"+kind = "folder"+target = "/notes"++[[sources]]+id = "src-file"+kind = "file"+target = "/notes/a.md"+"#,+ )+ .expect("a removed kind must not fail the section");+ let ids: Vec<&str> = config.sources.iter().map(|s| s.id.as_str()).collect();+ assert_eq!(+ ids,- ["src-link", "src-github", "src-rss", "src-folder", "src-file"]++ [++ "src-link",++ "src-github",++ "src-rss",++ "src-folder",++ "src-file"++ ]+ );+ assert_eq!(MemorySourceKind::parse("composio"), None);+}+#[test]fn endpoint_for_ignores_blank_and_missing_endpoints() {let mut config = MemoryConfig::default();diff --cc crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rsindex e83642ae86,6f65e52ff0..59069dbd5a--- a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs@@@ -645,4 -645,26 +645,3 @@@ async fn composio_list_connections_retuoutcome.logs);}--// ── sync reasons ─────────────────────────────────────────────────────────────---/// Every parsed sync reason is a distinct event trigger — the stage events-/// must not collapse periodic and connection-created syncs into "manual"-/// (review finding on #5932).-#[test]-fn sync_reasons_map_to_distinct_triggers() {- use crate::integrations::composio::providers::SyncReason;- let all = [- SyncReason::Manual,- SyncReason::Periodic,- SyncReason::ConnectionCreated,- ];- let mut seen = std::collections::HashSet::new();- for reason in all {- assert!(- seen.insert(reason.as_str().to_string()),- "duplicate trigger"- );- }- assert_eq!(seen.len(), 3);-}diff --cc crates/openhuman-core/src/integrations/composio/ops_no_session_and_cache_tests.rsindex ef5e335b77,885e1c1c5d..6ba02a5098--- a/crates/openhuman-core/src/integrations/composio/ops_no_session_and_cache_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_no_session_and_cache_tests.rs@@@ -387,8 -436,8 +387,6 @@@ async fn composio_delete_connection_vialet base = start_mock_backend(app).await;let tmp = tempfile::tempdir().unwrap();let config = config_with_backend(&tmp, base);- let outcome = composio_delete_connection(&config, "c1")- let outcome = composio_delete_connection(&config, "c1", false)-- .await-- .unwrap();++ let outcome = composio_delete_connection(&config, "c1").await.unwrap();assert!(outcome.value.deleted);}diff --cc crates/openhuman-core/src/memory/README.mdindex 368105098d,fb6b43287e..c1cc4290c5--- a/crates/openhuman-core/src/memory/README.md+++ b/crates/openhuman-core/src/memory/README.md@@@ -37,8 -47,9 +47,9 @@@ Chat thread persistence is not memory:| `lifecycle/jobs.rs` | The persisted job queue (`<workspace>/memory/jobs.json`) and the `memory_background` run. || `lifecycle/views.rs` | Policy get/set, pack preview, agents list, jobs list/run. || `brain.rs` | Brain source mapping and the brain ops. |-| `sources/` | Source registry, state and sync (folder, file, link, github, rss, composio). |+| `sources/` | Source registry, state and sync (folder, file, link, github, rss). || `channels.rs` | Channel → thread records for forgetting a channel. |+ | `deletion.rs` | Hard deletes that must reach the engine: thread forget, the pending-deletion queue (`<workspace>/memory/pending_deletions.json`) and its drain. || `backfill.rs` | Past chats from the thread store, resumable, with consent. || `import.rs` | Consent-gated, resumable v1 import. || `tools.rs` | The single `memory` agent tool and the turn's memory citations. |diff --cc crates/openhuman-core/src/memory/deletion.rsindex 0000000000,290d491117..5660b80f8amode 000000,100644..100644--- a/crates/openhuman-core/src/memory/deletion.rs+++ b/crates/openhuman-core/src/memory/deletion.rs@@@ -1,0 -1,254 +1,237 @@@+ //! Deletions that must reach the engine, whenever it is reachable.+ //!-//! Deleting a chat thread, disconnecting a connector, forgetting a channel-//! (one thread deletion per thread it owned) or removing a source asks the engine to delete for good. When memory is off++//! Deleting a chat thread, forgetting a channel (one thread deletion per++//! thread it owned) or removing a source asks the engine to delete for good. When memory is off+ //! (signed out, no credential) the engine cannot be reached, and when it+ //! fails the deletion has not happened. Either way the deletion is recorded+ //! here, in `<workspace>/memory/pending_deletions.json`, and [`drain`] runs+ //! it again on the next sign-in ([`super::bus`], on `CredentialChanged`) and+ //! on every background tick, until it succeeds.+ //!+ //! Every deletion is hard: a forget by filter removes the matched events by-//! `memory_ids` with an explicit `redact_events` cascade, and a connector's-//! own source scope is erased outright (see `sources::composio`).++//! `memory_ids` with an explicit `redact_events` cascade.++ use std::path::{Path, PathBuf};+ use std::sync::{LazyLock, Mutex};++ use serde::{Deserialize, Serialize};+ use tinymemory_api::{ForgetTarget, ItemKind, MetaFilter};++ use crate::config::Config;++ use super::engine;+ use super::error::{MemoryError, MemoryResult};++ /// One deletion still owed to the engine.+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+ #[serde(tag = "kind", rename_all = "snake_case")]+ pub enum PendingDeletion {+ /// A deleted chat thread's conversation memory.+ Thread {+ /// The thread.+ thread_id: String,+ },- /// Everything synced through a disconnected Composio connection.- Connection {- /// The connection.- connection_id: String,- /// Its toolkit, when it was known at disconnect.- #[serde(default, skip_serializing_if = "Option::is_none")]- toolkit: Option<String>,- },+ /// Every item a removed memory source stored.+ Source {+ /// The source id.+ source_id: String,+ },+ }++ impl PendingDeletion {+ /// A short, content-free label for logs.+ fn label(&self) -> &'static str {+ match self {+ Self::Thread { .. } => "thread",- Self::Connection { .. } => "connection",+ Self::Source { .. } => "source",+ }+ }+ }++ /// Serialises every read-modify-write of the file in this process.+ static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));++ /// Serialises drains, so two triggers never run one deletion twice at once.+ static DRAINING: LazyLock<tokio::sync::Mutex<()>> = LazyLock::new(|| tokio::sync::Mutex::new(()));++ fn path(workspace_dir: &Path) -> PathBuf {+ workspace_dir.join("memory").join("pending_deletions.json")+ }++ fn locked() -> std::sync::MutexGuard<'static, ()> {+ LOCK.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ fn read(workspace_dir: &Path) -> Vec<PendingDeletion> {+ let file = path(workspace_dir);+ let Ok(text) = std::fs::read_to_string(&file) else {+ return Vec::new();+ };+ serde_json::from_str(&text).unwrap_or_else(|error| {+ tracing::warn!(%error, "[memory:deletion] pending deletions unparsable; set aside");+ if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {+ tracing::warn!(%error, "[memory:deletion] could not set the file aside");+ }+ Vec::new()+ })+ }++ /// Writes (owner-only, like the other memory files) through a temporary file and a rename, so a stop mid-write never+ /// leaves a partial file and loses the queue.+ fn write(workspace_dir: &Path, all: &[PendingDeletion]) {+ let file = path(workspace_dir);+ if all.is_empty() {+ match std::fs::remove_file(&file) {+ Ok(()) => {}+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => tracing::warn!(%error, "[memory:deletion] clearing the queue failed"),+ }+ return;+ }+ let temp = file.with_extension("json.tmp");+ let result = file+ .parent()+ .map_or(Ok(()), super::files::create_private_dir_all)+ .and_then(|()| {+ let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;+ super::files::write_private(&temp, &json)?;+ std::fs::rename(&temp, &file)+ });+ if let Err(error) = result {+ tracing::warn!(%error, "[memory:deletion] writing pending deletions failed");+ }+ }++ /// Records `deletion` to run on the next [`drain`]. A deletion already+ /// queued is not queued twice.+ pub fn enqueue(workspace_dir: &Path, deletion: PendingDeletion) {+ let _guard = locked();+ let mut all = read(workspace_dir);+ if all.contains(&deletion) {+ return;+ }+ tracing::info!(+ kind = deletion.label(),+ "[memory:deletion] deletion queued until memory is reachable"+ );+ all.push(deletion);+ write(workspace_dir, &all);+ }++ /// Every deletion still owed, oldest first.+ #[must_use]+ pub fn pending(workspace_dir: &Path) -> Vec<PendingDeletion> {+ let _guard = locked();+ read(workspace_dir)+ }++ fn settle(workspace_dir: &Path, deletion: &PendingDeletion) {+ let _guard = locked();+ let mut all = read(workspace_dir);+ let before = all.len();+ all.retain(|queued| queued != deletion);+ if all.len() != before {+ write(workspace_dir, &all);+ }+ }++ /// Runs `deletion` now. Memory off is [`MemoryError::Off`], which the+ /// caller decides how to treat.+ async fn run(config: &Config, deletion: &PendingDeletion) -> MemoryResult<usize> {+ match deletion {+ PendingDeletion::Thread { thread_id } => forget_thread_now(config, thread_id).await,- PendingDeletion::Connection {- connection_id,- toolkit,- } => {- super::sources::composio::forget_connection(config, connection_id, toolkit.as_deref())- .await- }+ PendingDeletion::Source { source_id } => {+ super::sources::forget_items(config, source_id).await+ }+ }+ }++ /// Runs every queued deletion, settling each one that succeeds. Stops at+ /// once when memory is off (nothing can run), and keeps a deletion that+ /// fails for the next drain. Returns how many deletions settled.+ pub async fn drain(config: &Config) -> usize {+ let _draining = DRAINING.lock().await;+ let queued = pending(&config.workspace_dir);+ if queued.is_empty() {+ return 0;+ }+ if !engine::resolve(config).is_on() {+ tracing::debug!(+ queued = queued.len(),+ "[memory:deletion] memory off; pending deletions wait"+ );+ return 0;+ }+ let mut settled = 0;+ for deletion in queued {+ // Settled first: the deletion re-queues itself if it cannot finish.+ settle(&config.workspace_dir, &deletion);+ match run(config, &deletion).await {+ Ok(forgotten) => {+ settled += 1;+ tracing::info!(+ kind = deletion.label(),+ forgotten,+ "[memory:deletion] pending deletion completed"+ );+ }+ Err(error) => {+ enqueue(&config.workspace_dir, deletion.clone());+ tracing::warn!(+ kind = deletion.label(),+ code = error.code(),+ "[memory:deletion] pending deletion failed; kept for the next drain"+ );+ }+ }+ }+ settled+ }++ /// Forgets every conversation item of `thread_id` now.+ async fn forget_thread_now(config: &Config, thread_id: &str) -> MemoryResult<usize> {+ let bound = engine::resolve(config).engine()?;+ let filter = MetaFilter {+ thread_id: Some(thread_id.to_string()),+ ..MetaFilter::kinds([ItemKind::Conversation])+ };+ let report = bound.engine.forget(ForgetTarget::Filter(filter)).await?;+ tracing::debug!(+ forgotten = report.forgotten,+ "[memory:deletion] thread conversation memory forgotten"+ );+ Ok(report.forgotten)+ }++ /// Forgets a deleted thread's conversation memory, for good. Memory off or+ /// a failed forget queues the deletion for the next [`drain`] rather than+ /// failing the caller: the thread itself is already gone. Returns how many+ /// items went now.+ pub async fn forget_thread(config: &Config, thread_id: &str) -> usize {+ if thread_id.trim().is_empty() {+ return 0;+ }+ let deletion = PendingDeletion::Thread {+ thread_id: thread_id.to_string(),+ };+ match forget_thread_now(config, thread_id).await {+ Ok(forgotten) => forgotten,+ Err(MemoryError::Off(_)) => {+ enqueue(&config.workspace_dir, deletion);+ 0+ }+ Err(error) => {+ tracing::warn!(+ code = error.code(),+ "[memory:deletion] forgetting a deleted thread failed; queued"+ );+ enqueue(&config.workspace_dir, deletion);+ 0+ }+ }+ }++ #[cfg(test)]+ #[path = "deletion_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/memory/deletion_tests.rsindex 0000000000,6818203d25..23750f4646mode 000000,100644..100644--- a/crates/openhuman-core/src/memory/deletion_tests.rs+++ b/crates/openhuman-core/src/memory/deletion_tests.rs@@@ -1,0 -1,122 +1,121 @@@+ use super::*;++ use tinymemory_api::{MemoryEngine, MemoryMeta, Role, StoreItem, Turn};++ use crate::memory::test_fixtures::{bind_reference, config_in, stored};++ fn conversation(thread_id: &str, text: &str) -> StoreItem {+ StoreItem::Conversation {+ turns: vec![Turn::new(Role::User, text.to_string())],+ meta: MemoryMeta {+ thread_id: Some(thread_id.to_string()),+ ..MemoryMeta::default()+ },+ }+ }++ fn thread(id: &str) -> PendingDeletion {+ PendingDeletion::Thread {+ thread_id: id.to_string(),+ }+ }++ #[tokio::test]+ async fn a_deleted_threads_conversation_is_forgotten_for_good() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let engine = bind_reference(&config);+ engine+ .store(conversation("t-gone", "secret plan"))+ .await+ .unwrap();+ engine+ .store(conversation("t-kept", "keep me"))+ .await+ .unwrap();++ assert_eq!(forget_thread(&config, "t-gone").await, 1);++ let left = stored(&engine, MetaFilter::default()).await;+ assert_eq!(left.len(), 1);+ assert_eq!(left[0].meta.thread_id.as_deref(), Some("t-kept"));+ assert!(pending(&config.workspace_dir).is_empty());+ }++ #[tokio::test]+ async fn a_thread_deleted_while_signed_out_is_forgotten_on_the_next_sign_in() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ // Memory off: no credential, no engine.+ assert_eq!(forget_thread(&config, "t-1").await, 0);+ assert_eq!(pending(&config.workspace_dir), vec![thread("t-1")]);+ // Nothing runs while memory stays off, and nothing is lost.+ assert_eq!(drain(&config).await, 0);+ assert_eq!(pending(&config.workspace_dir), vec![thread("t-1")]);++ // Signed in: the engine is reachable and holds the thread's memory.+ let engine = bind_reference(&config);+ engine+ .store(conversation("t-1", "from before"))+ .await+ .unwrap();+ assert_eq!(drain(&config).await, 1);+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());+ assert!(pending(&config.workspace_dir).is_empty());+ }++ #[tokio::test]+ async fn a_failed_forget_is_kept_for_the_next_drain() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);+ assert_eq!(forget_thread(&config, "t-2").await, 0);+ assert_eq!(pending(&config.workspace_dir), vec![thread("t-2")]);+ assert_eq!(drain(&config).await, 0);+ assert_eq!(pending(&config.workspace_dir), vec![thread("t-2")]);+ }++ #[test]+ fn a_deletion_is_queued_once() {+ let tmp = tempfile::tempdir().unwrap();+ enqueue(tmp.path(), thread("t"));+ enqueue(tmp.path(), thread("t"));+ enqueue(+ tmp.path(),- PendingDeletion::Connection {- connection_id: "c".into(),- toolkit: Some("gmail".into()),++ PendingDeletion::Source {++ source_id: "src-1".into(),+ },+ );+ assert_eq!(pending(tmp.path()).len(), 2);+ }++ #[test]+ fn an_unparsable_queue_is_set_aside_not_lost() {+ let tmp = tempfile::tempdir().unwrap();+ let file = path(tmp.path());+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, "not json").unwrap();+ assert!(pending(tmp.path()).is_empty());+ assert!(file.with_extension("json.corrupt").exists());+ }++ #[tokio::test]+ async fn a_blank_thread_id_queues_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ assert_eq!(forget_thread(&config, " ").await, 0);+ assert!(pending(&config.workspace_dir).is_empty());+ }++ #[cfg(unix)]+ #[test]+ fn the_pending_queue_is_owner_only() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ enqueue(tmp.path(), thread("t"));+ let mode = std::fs::metadata(path(tmp.path()))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o077, 0, "{mode:o}");+ }diff --cc crates/openhuman-core/src/memory/sources/sync_tests.rsindex 4a103d9ce1,a2dc8fcb3d..2b45bf39e7--- a/crates/openhuman-core/src/memory/sources/sync_tests.rs+++ b/crates/openhuman-core/src/memory/sources/sync_tests.rs@@@ -404,18 -415,3 +404,21 @@@ async fn github_files_per_repository_on"one belief build per node written");}++#[test]+fn orphaned_connector_files_are_removed_and_missing_ones_ignored() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("connector_items.json"), "{}").unwrap();+ std::fs::write(dir.join("connection_roots.json"), "{}").unwrap();+ std::fs::write(dir.join("sources_state.json"), "{}").unwrap();+ state::remove_orphaned_connector_files(tmp.path());+ assert!(!dir.join("connector_items.json").exists());+ assert!(!dir.join("connection_roots.json").exists());- assert!(dir.join("sources_state.json").exists(), "live state is kept");++ assert!(++ dir.join("sources_state.json").exists(),++ "live state is kept"++ );+ state::remove_orphaned_connector_files(tmp.path());+}