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
feat(memory): add source sync support to brain
Steven Enamakel9a8160dc3191
diff --git a/crates/openhuman-core/src/flows/tinyflows/memory_adapter_tests.rs b/crates/openhuman-core/src/flows/tinyflows/memory_adapter_tests.rsindex 3c0a9652ad..0e41283654 100644--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter_tests.rs+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter_tests.rs@@ -314,7 +314,7 @@ fn plain_agent_learnings_are_trusted_and_everything_else_is_not() {assert!(!is_untrusted(&MemoryMeta::default()));assert!(is_untrusted(&crate::flows::flow_meta("f", &[])));assert!(is_untrusted(&MemoryMeta::from_source(- SourceKind::Composio,+ SourceKind::Import,None)));}diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rsindex c0da42e150..53e401b2af 100644--- a/crates/openhuman-core/src/memory/brain.rs+++ b/crates/openhuman-core/src/memory/brain.rs@@ -35,24 +35,31 @@ pub fn files_source() -> BrainSource {}/// The brain source a synced item belongs to: the connector it came from,-/// so disconnecting or removing it erases one source. GitHub (the reader-/// and the Composio toolkit alike) to `github`, links and feeds to `web`, a-/// Composio toolkit to its canonical slug (`gmail`, `googledrive`), and-/// local files, whatever their format, to `files`.+/// so removing it erases one source. GitHub to `github`, links and feeds to+/// `web`, and local files, whatever their format, to `files`.#[must_use]-pub fn brain_source(kind: MemorySourceKind, target: &str) -> BrainSource {+pub fn brain_source(kind: MemorySourceKind) -> BrainSource {match kind {MemorySourceKind::Github => BrainSource::Github,MemorySourceKind::Link | MemorySourceKind::Rss => BrainSource::Web,- MemorySourceKind::Composio => {- crate::integrations::composio::tools::canonicalize_toolkit_slug(target)- .parse()- .unwrap_or_else(|_| BrainSource::Other("composio".to_string()))- }MemorySourceKind::Folder | MemorySourceKind::File => files_source(),}}+/// Canonical form of a connector slug found on a legacy brain node+/// (`google_drive` becomes `googledrive`), so documents filed by the removed+/// Composio sync still migrate to the node they were filed under.+fn legacy_connector_slug(slug: &str) -> String {+ let key = slug.trim().to_ascii_lowercase();+ match key.as_str() {+ "feishu" | "lark" => "larksuite".to_string(),+ "google_calendar" => "googlecalendar".to_string(),+ "google_drive" => "googledrive".to_string(),+ "google_sheets" => "googlesheets".to_string(),+ _ => key,+ }+}+/// The brain source a document filed under the old per-type layout belongs/// to now, for the migration that moves it: `old_source_id` is the id of/// the `source:<id>` node it sits at, `item` the document itself.@@ -65,7 +72,7 @@ pub fn brain_source(kind: MemorySourceKind, target: &str) -> BrainSource {/// becomes `googledrive`), so `notion`, `github` and `gmail` stay put.#[must_use]pub fn legacy_brain_node(old_source_id: &str, item: &StoreItem) -> BrainSource {- let id = crate::integrations::composio::tools::canonicalize_toolkit_slug(old_source_id);+ let id = legacy_connector_slug(old_source_id);match id.as_str() {"files" | "pdf" | "markdown" | "md" | "docx" | "xlsx" | "pptx" | "code" | "other" => {files_source()diff --git a/crates/openhuman-core/src/memory/brain_tests.rs b/crates/openhuman-core/src/memory/brain_tests.rsindex 0c4713a4ee..d3b8268904 100644--- a/crates/openhuman-core/src/memory/brain_tests.rs+++ b/crates/openhuman-core/src/memory/brain_tests.rs@@ -22,25 +22,11 @@ fn synced_items_are_filed_by_their_connector() {(MemorySourceKind::Github, "o/r", BrainSource::Github),(MemorySourceKind::Link, "https://x", BrainSource::Web),(MemorySourceKind::Rss, "https://x/feed", BrainSource::Web),- (MemorySourceKind::Composio, "Notion", BrainSource::Notion),- // The Composio toolkit and the GitHub reader share one source.- (MemorySourceKind::Composio, "github", BrainSource::Github),- (- MemorySourceKind::Composio,- "gmail",- BrainSource::Other("gmail".into()),- ),- // An alias files under the slug Composio itself uses.- (- MemorySourceKind::Composio,- "google_drive",- BrainSource::Other("googledrive".into()),- ),// Local files, whatever their format, share one source.(MemorySourceKind::Folder, "/n", files_source()),(MemorySourceKind::File, "/n/deck/Q3.PDF", files_source()),] {- assert_eq!(brain_source(kind, target), want, "{kind:?} {target}");+ assert_eq!(brain_source(kind), want, "{kind:?} {target}");}assert_eq!(files_source().to_string(), "files");}diff --git a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rsindex 632670729f..66e879fcc1 100644--- a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs@@ -255,10 +255,10 @@ async fn old_brain_nodes_are_refiled_by_connector() {doc("a drive doc","source:google_drive",- SourceKind::Composio,+ SourceKind::Import,None,),- doc("a notion page", "source:notion", SourceKind::Composio, None),+ doc("a notion page", "source:notion", SourceKind::Import, None),] {legacy.store(item).await.unwrap();}diff --git a/crates/openhuman-core/src/memory/layout_migration/map_tests.rs b/crates/openhuman-core/src/memory/layout_migration/map_tests.rsindex 18d0bb01a0..c39803a20b 100644--- a/crates/openhuman-core/src/memory/layout_migration/map_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/map_tests.rs@@ -90,14 +90,14 @@ fn a_web_link_stays_web_and_an_uploaded_page_is_a_file() {fn a_connector_document_keeps_its_node() {let placement = placement("root");let placed = placement- .place(document("source:gmail", SourceKind::Composio, None))+ .place(document("source:gmail", SourceKind::Import, None)).unwrap();assert_eq!(placed.meta().namespace, ns("source:gmail"));}#[test]fn a_github_document_goes_to_its_repository_when_the_setting_splits_them() {- let mut item = document("source:github", SourceKind::Composio, None);+ let mut item = document("source:github", SourceKind::Import, None);item.meta_mut().repo = Some("Acme/Widgets".into());let mut placement = placement("root");assert_eq!(diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex 8168e1d6fb..442f335c5d 100644--- a/crates/openhuman-core/src/memory/sources/mod.rs+++ b/crates/openhuman-core/src/memory/sources/mod.rs@@ -1,18 +1,14 @@//! Document sources: the registry persisted in `[[memory.sources]]`, and sync.//!//! A source names something to read — a folder, a file, a web page, a GitHub-//! repository, an RSS feed or a connected Composio toolkit — and how often.-//! Sync reads it through `tinymemory-sources` (or, for Composio, the connector-//! module) and stores each item as a `Document` whose `meta.source` is+//! repository or an RSS feed — and how often. Sync reads it through+//! `tinymemory-integrations`' readers and stores each item as a `Document` whose `meta.source` is//! `{kind, id: <source id>}`, so removing a source can forget exactly its//! items. Sync runs on demand ([`start_sync`]) and from the//! `memory_sources_sync` cron job ([`sync_due`]).-pub mod composio;-pub mod roots;pub mod state;mod sync;-pub mod versions;use chrono::{DateTime, Utc};use tinymemory_api::{ForgetTarget, MetaFilter};@@ -60,7 +56,7 @@ pub fn list(config: &Config) -> Vec<SourceView> {}/// Normalises a target for `kind`: GitHub accepts `owner/repo` or a URL;-/// network kinds must be http(s) URLs; a Composio target is a toolkit slug.+/// network kinds must be http(s) URLs.pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<String> {let target = target.trim();if target.is_empty() {@@ -83,16 +79,6 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<St}}MemorySourceKind::Link | MemorySourceKind::Rss => http_url(target),- MemorySourceKind::Composio => {- if target- .chars()- .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')- {- Ok(crate::integrations::composio::tools::canonicalize_toolkit_slug(target))- } else {- Err(MemoryError::invalid("a Composio target is a toolkit slug"))- }- }}}@@ -112,7 +98,7 @@ pub fn apply_add() -> MemoryResult<MemorySourceConfig> {let kind = MemorySourceKind::parse(¶ms.kind).ok_or_else(|| {MemoryError::invalid(format!(- "unknown source kind `{}` (folder, file, link, github, rss, composio)",+ "unknown source kind `{}` (folder, file, link, github, rss)",params.kind.trim()))})?;@@ -124,19 +110,11 @@ pub fn apply_add()));}}- // A Composio target saved before targets were canonicalized- // (`google_drive`) is the same toolkit as its canonical slug.- let same_target = |saved: &str| match kind {- MemorySourceKind::Composio => {- crate::integrations::composio::tools::canonicalize_toolkit_slug(saved) == target- }- _ => saved == target,- };if config.memory.sources.iter()- .any(|source| source.kind == kind && same_target(&source.target))+ .any(|source| source.kind == kind && source.target == target){return Err(MemoryError::invalid("that source is already added"));}diff --git a/crates/openhuman-core/src/memory/sources/mod_tests.rs b/crates/openhuman-core/src/memory/sources/mod_tests.rsindex 5cb7e6465a..1e179a8f87 100644--- a/crates/openhuman-core/src/memory/sources/mod_tests.rs+++ b/crates/openhuman-core/src/memory/sources/mod_tests.rs@@ -51,14 +51,6 @@ fn normalize_target_accepts_each_kinds_shape() {normalize_target(MemorySourceKind::Link, "https://example.com").unwrap(),"https://example.com/");- assert_eq!(- normalize_target(MemorySourceKind::Composio, "GMail").unwrap(),- "gmail"- );- assert_eq!(- normalize_target(MemorySourceKind::Composio, "Google_Drive").unwrap(),- "googledrive"- );}#[test]@@ -71,8 +63,6 @@ fn normalize_target_rejects_malformed_targets() {(MemorySourceKind::Link, "not a url"),(MemorySourceKind::Link, "ftp://example.com/x"),(MemorySourceKind::Rss, "file:///etc/passwd"),- (MemorySourceKind::Composio, "has space"),- (MemorySourceKind::Composio, "a/b"),] {assert_eq!(normalize_target(kind, target).unwrap_err().code(),@@ -158,24 +148,27 @@ fn add_validates_kind_schedule_and_target() {config.memory.sources.is_empty(),"a refused add changes nothing");- // A Composio source needs no reader.- apply_add(&mut config, &add_params("composio", "Gmail")).unwrap();- assert_eq!(config.memory.sources[0].target, "gmail");+}- // A source saved under an alias before canonicalization is still the- // same toolkit.- config.memory.sources.push(MemorySourceConfig {- kind: MemorySourceKind::Composio,- target: "google_drive".into(),- ..source("src-drive", None)- });- assert_eq!(- apply_add(&mut config, &add_params("composio", "googledrive"))- .unwrap_err()- .code(),- INVALID_REQUEST- );- assert_eq!(config.memory.sources.len(), 2, "no duplicate was added");+#[test]+fn the_removed_composio_kind_is_rejected_and_every_other_kind_is_accepted() {+ let mut config = Config::default();+ let error = apply_add(&mut config, &add_params("composio", "gmail")).unwrap_err();+ assert_eq!(error.code(), INVALID_REQUEST);+ assert!(config.memory.sources.is_empty());+ for (kind, target) in [+ ("folder", "/notes"),+ ("file", "/notes/a.md"),+ ("link", "https://example.com/docs"),+ ("github", "acme/widgets"),+ ("rss", "https://example.com/feed.xml"),+ ] {+ assert!(+ apply_add(&mut config, &add_params(kind, target)).is_ok(),+ "{kind}"+ );+ }+ assert_eq!(config.memory.sources.len(), 5);}#[test]diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex a1929d1fdf..c773ddccc0 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -1,10 +1,9 @@//! Syncing sources into memory.//!-//! Non-Composio sources are read through `tinymemory-sources`' readers+//! Sources are read through `tinymemory-integrations`' readers//! (`collect_items`), which turn each file, page, commit or feed entry into a//! `Document` with its metadata filled. Every item is scrubbed and stored on//! the bound engine; per-item failures are logged and skipped, not fatal.-//! Composio sources go through [`super::composio`].use std::collections::HashSet;use std::path::PathBuf;@@ -28,16 +27,14 @@ use super::state;static RUNNING: LazyLock<Mutex<HashSet<(PathBuf, String)>>> =LazyLock::new(|| Mutex::new(HashSet::new()));-/// The `tinymemory-sources` entry that reads `source`; `None` for Composio,-/// which syncs through the connector module instead.-pub(super) fn reader_entry(source: &MemorySourceConfig) -> MemoryResult<Option<MemorySourceEntry>> {+/// The `tinymemory-integrations` entry that reads `source`.+pub(super) fn reader_entry(source: &MemorySourceConfig) -> MemoryResult<MemorySourceEntry> {let kind = match source.kind {MemorySourceKind::Folder => SourceKind::Folder,MemorySourceKind::File => SourceKind::File,MemorySourceKind::Link => SourceKind::WebPage,MemorySourceKind::Github => SourceKind::GithubRepo,MemorySourceKind::Rss => SourceKind::RssFeed,- MemorySourceKind::Composio => return Ok(None),};let mut entry = MemorySourceEntry::new(source.id.clone(), kind, source.label.clone());match source.kind {@@ -50,7 +47,7 @@ pub(super) fn reader_entry(source: &MemorySourceConfig) -> MemoryResult<Option<Mentry.validate().map_err(|error| MemoryError::invalid(error.to_string()))?;- Ok(Some(entry))+ Ok(entry)}/// Fills the per-kind read caps the user did not set: a GitHub repo reads at@@ -73,9 +70,7 @@ fn apply_kind_defaults(entry: &mut MemorySourceEntry) {/// Reads `source` and stores what it yields. Returns the number stored.pub async fn sync_one(config: &Config, source: &MemorySourceConfig) -> MemoryResult<u64> {let bound = engine::resolve(config).engine()?;- let Some(entry) = reader_entry(source)? else {- return super::composio::sync_toolkit(config, &bound, source).await;- };+ let entry = reader_entry(source)?;let reader = reader_for_request(&entry.kind);let collected = collect_items(reader.as_ref(),@@ -96,7 +91,7 @@ pub async fn sync_one(config: &Config, source: &MemorySourceConfig) -> MemoryResconfig,&bound,collected.items,- (source.kind, &source.target, &source.id),+ (source.kind, &source.id),&super::layout_of_source(config, source),).await@@ -109,32 +104,20 @@ pub(crate) async fn store_all(config: &Config,bound: &BoundEngine,items: Vec<tinymemory_api::StoreItem>,- source: (crate::config::schema::MemorySourceKind, &str, &str),+ (kind, source_id): (crate::config::schema::MemorySourceKind, &str),layout: &tinymemory_tools::MemoryLayout,) -> MemoryResult<u64> {- let ids = store_all_ids(config, bound, items, source, layout).await?;- Ok(ids.iter().flatten().count() as u64)-}--/// [`store_all`], returning the id each item was stored under, in order-/// (`None` for an item that failed).-pub(crate) async fn store_all_ids(- config: &Config,- bound: &BoundEngine,- items: Vec<tinymemory_api::StoreItem>,- (kind, target, source_id): (crate::config::schema::MemorySourceKind, &str, &str),- layout: &tinymemory_tools::MemoryLayout,-) -> MemoryResult<Vec<Option<String>>> {- let mut ids = Vec::with_capacity(items.len());+ let mut stored = 0u64;+ let mut failed = 0u64;let mut last_error = None;let mut touched = std::collections::BTreeSet::new();for item in items {- let brain_source = crate::memory::brain::brain_source(kind, target);+ let brain_source = crate::memory::brain::brain_source(kind);let node = crate::memory::brain::brain_node(config, layout, &brain_source, &item)?;let item = crate::memory::brain::file_into(node.clone(), item);match store_on(bound, item).await {- Ok(receipt) => {- ids.push(Some(receipt.id.to_string()));+ Ok(_) => {+ stored += 1;touched.insert(node);}// Out of credits or unreachable refuses every item, so stop@@ -142,7 +125,7 @@ pub(crate) async fn store_all_ids(Err(error) if error.is_account_wide() => return Err(error),Err(error) => {tracing::debug!(id = %source_id, code = error.code(), "[memory:sources] item store failed");- ids.push(None);+ failed += 1;last_error = Some(error);}}@@ -161,8 +144,8 @@ pub(crate) async fn store_all_ids(.collect();crate::memory::lifecycle::jobs::enqueue(config, layout.root(), jobs).await;match last_error {- Some(error) if ids.iter().all(Option::is_none) => Err(error),- _ => Ok(ids),+ Some(error) if stored == 0 && failed > 0 => Err(error),+ _ => Ok(stored),}}diff --git a/crates/openhuman-core/src/memory/sources/sync_tests.rs b/crates/openhuman-core/src/memory/sources/sync_tests.rsindex a2dc8fcb3d..4a103d9ce1 100644--- a/crates/openhuman-core/src/memory/sources/sync_tests.rs+++ b/crates/openhuman-core/src/memory/sources/sync_tests.rs@@ -51,25 +51,18 @@ fn reader_entry_maps_every_kind() {schedule_mins: None,namespace: None,};- let folder = reader_entry(&mk(MemorySourceKind::Folder, "/p"))- .unwrap()- .unwrap();+ let folder = reader_entry(&mk(MemorySourceKind::Folder, "/p")).unwrap();assert_eq!(folder.path.as_deref(), Some("/p"));- let file = reader_entry(&mk(MemorySourceKind::File, "/p/a.md"))- .unwrap()- .unwrap();+ let file = reader_entry(&mk(MemorySourceKind::File, "/p/a.md")).unwrap();assert_eq!(file.path.as_deref(), Some("/p/a.md"));for (kind, target) in [(MemorySourceKind::Link, "https://example.com/"),(MemorySourceKind::Github, "https://github.com/o/r"),(MemorySourceKind::Rss, "https://example.com/feed"),] {- let entry = reader_entry(&mk(kind, target)).unwrap().unwrap();+ let entry = reader_entry(&mk(kind, target)).unwrap();assert_eq!(entry.url.as_deref(), Some(target));}- assert!(reader_entry(&mk(MemorySourceKind::Composio, "gmail"))- .unwrap()- .is_none());}#[tokio::test]@@ -261,7 +254,7 @@ async fn store_all_skips_a_bad_item_but_fails_when_nothing_stored() {&config,&bound,vec![bad.clone(), good],- (MemorySourceKind::Folder, "/n", "src"),+ (MemorySourceKind::Folder, "src"),&tinymemory_tools::MemoryLayout::default()).await@@ -272,7 +265,7 @@ async fn store_all_skips_a_bad_item_but_fails_when_nothing_stored() {&config,&bound,vec![bad],- (MemorySourceKind::Folder, "/n", "src"),+ (MemorySourceKind::Folder, "src"),&tinymemory_tools::MemoryLayout::default()).await@@ -282,7 +275,7 @@ async fn store_all_skips_a_bad_item_but_fails_when_nothing_stored() {&config,&bound,Vec::new(),- (MemorySourceKind::Folder, "/n", "src"),+ (MemorySourceKind::Folder, "src"),&tinymemory_tools::MemoryLayout::default()).await@@ -334,7 +327,7 @@ async fn a_sync_queues_a_belief_build_only_for_an_engine_that_waits_for_one() {&config,&bound,vec![note()],- (MemorySourceKind::Folder, "/n", "src"),+ (MemorySourceKind::Folder, "src"),&tinymemory_tools::MemoryLayout::default(),).await@@ -366,11 +359,7 @@ async fn github_files_per_repository_only_when_switched_on() {&config,&bound,items,- (- MemorySourceKind::Github,- "https://github.com/acme/api",- "src",- ),+ (MemorySourceKind::Github, "src"),&tinymemory_tools::MemoryLayout::default(),).await@@ -415,3 +404,18 @@ async fn github_files_per_repository_only_when_switched_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");+ state::remove_orphaned_connector_files(tmp.path());+}