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 roots, versions, and sync tracking
Steven Enamakel8e45fab0c7a9
diff --git a/crates/openhuman-core/src/config/schema/load/migrate.rs b/crates/openhuman-core/src/config/schema/load/migrate.rsindex b6c58abc12..3405142000 100644--- a/crates/openhuman-core/src/config/schema/load/migrate.rs+++ b/crates/openhuman-core/src/config/schema/load/migrate.rs@@ -215,7 +215,7 @@ pub(crate) fn migrate_search_settings(config: &mut Config) {/// Migrates legacy v1 `[[memory_sources]]` into `[[memory.sources]]`, once:/// only when no v2 source exists yet. Kinds without a v2 equivalent-/// (`twitter_query`, `conversation`) and disabled entries are dropped. The+/// (everything but `folder` and `file`, including the removed `web_page`, `github_repo`, `rss_feed` and `composio`) and disabled entries are dropped. The/// legacy list is cleared either way, so it is never written back.pub(crate) fn migrate_legacy_memory_sources(config: &mut Config) {let legacy = std::mem::take(&mut config.legacy_memory_sources);diff --git a/crates/openhuman-core/src/memory/sources/composio.rs b/crates/openhuman-core/src/memory/sources/composio.rsdeleted file mode 100644index fd8ee53718..0000000000--- a/crates/openhuman-core/src/memory/sources/composio.rs+++ /dev/null@@ -1,406 +0,0 @@-//! Composio sources: connector records become `Document` items.-//!-//! A Composio source names a toolkit (`gmail`, `notion`, …). Syncing it runs-//! the connector module's sync for each active connection of that toolkit-//! (`integrations::composio::ops::run_sync_pass`), which pages the account and-//! hands back decoded records; each record is stored as a document with-//! `source = composio:<source id>`, `tags = [toolkit, "connection:<id>", …]`,-//! its URL, its upstream timestamp and, when the connector names one (an-//! email's sender), its sender as `meta.observed_actor` ([`sender_actor`]).-//! The connection tag is what deleting a-//! connection with `clear_memory` forgets by. The same conversion backs `openhuman.composio_sync`,-//! which syncs one connection on demand.--use chrono::{TimeZone, Utc};-use tinyconnectors_bus::records::{ConnectorRecord, RecordSender};-use tinymemory_api::{DocumentBody, MemoryMeta, ObservedActor, SourceKind, SourceRef, StoreItem};--use crate::config::schema::MemorySourceConfig;-use crate::config::Config;-use crate::integrations::composio::ops::{- active_connection_ids, run_sync_pass, SYNC_PASS_MAX_ITEMS,-};-use crate::memory::engine::BoundEngine;-use crate::memory::error::{MemoryError, MemoryResult};--/// Held across one [`store_records`] call (storing, finding the previous-/// versions and forgetting them) and across [`forget_connection`]. Two-/// passes over the same records (the on-demand and the scheduled sync)-/// would otherwise interleave, and one could forget an item the other has-/// just made current again; a disconnect could miss an item a pass stores-/// while it runs.-// ponytail: one lock for every connection, as passes are short and rare; a-// per-connection lock if syncs of many accounts must overlap.-static STORE: std::sync::LazyLock<tokio::sync::Mutex<()>> =- std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));--/// Connections deleted in this process, per workspace. A sync pass that-/// read a connection's records before its disconnect must not store them-/// after it, so [`forget_connection`] records the connection (under-/// [`STORE`]) and [`store_records`] drops any later batch for it. Composio-/// never reuses a connection id, so an entry stays for the life of the-/// process.-static DISCONNECTED: std::sync::LazyLock<- std::sync::Mutex<std::collections::HashSet<(std::path::PathBuf, String)>>,-> = std::sync::LazyLock::new(Default::default);--fn disconnected(-) -> std::sync::MutexGuard<'static, std::collections::HashSet<(std::path::PathBuf, String)>> {- DISCONNECTED- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)-}--/// Whether `connection_id` was disconnected in this process: its records-/// are no longer read or stored.-#[must_use]-pub fn is_disconnected(config: &Config, connection_id: &str) -> bool {- disconnected().contains(&(config.workspace_dir.clone(), connection_id.to_string()))-}--/// Most connector passes one source sync runs per connection.-const MAX_PASSES_PER_CONNECTION: usize = 25;--/// The tag every item synced through a connection carries.-#[must_use]-pub fn connection_tag(connection_id: &str) -> String {- format!("connection:{connection_id}")-}--/// The document one connector record stores, or `None` for an empty record.-#[must_use]-pub fn record_item(- toolkit: &str,- connection_id: &str,- source_id: &str,- record: &ConnectorRecord,-) -> Option<StoreItem> {- if record.content.trim().is_empty() {- return None;- }- let mut tags = vec![toolkit.to_ascii_lowercase(), connection_tag(connection_id)];- for tag in &record.tags {- if !tag.trim().is_empty() && !tags.contains(tag) {- tags.push(tag.clone());- }- }- let observed_at = record- .updated_at_ms- .and_then(|ms| Utc.timestamp_millis_opt(ms).single());- Some(StoreItem::Document {- title: Some(record.title.trim().to_string()).filter(|title| !title.is_empty()),- body: DocumentBody::Text(record.content.clone()),- mime: record.mime.clone(),- meta: MemoryMeta {- url: record.url.clone(),- tags,- observed_at,- source: SourceRef {- kind: SourceKind::Composio,- id: Some(source_id.to_string()),- },- observed_actor: record.sender.as_ref().and_then(sender_actor),- ..MemoryMeta::default()- },- })-}--/// Who a record came from, as the memory actor `user:<address>` with their-/// name: an email address, lower-cased so one person is one actor, or a-/// phone number as the connector's dial digits. Stored as given (the engine-/// sends it only with `[memory] observed_actor` on); `None` for a blank-/// address.-fn sender_actor(sender: &RecordSender) -> Option<ObservedActor> {- let address = sender.address.trim();- (!address.is_empty()).then(|| ObservedActor {- id: format!("user:{}", address.to_ascii_lowercase()),- name: sender- .name- .as_deref()- .map(str::trim)- .filter(|name| !name.is_empty())- .map(str::to_string),- })-}--/// Files every non-empty record into `layout`'s brain, under the toolkit's-/// brain source, and forgets the previous version of each record that-/// changed or came back empty upstream ([`super::versions`]). Returns how-/// many were stored.-pub async fn store_records(- config: &Config,- bound: &BoundEngine,- toolkit: &str,- connection_id: &str,- source_id: &str,- layout: &tinymemory_tools::MemoryLayout,- records: &[ConnectorRecord],-) -> MemoryResult<u64> {- let _serial = STORE.lock().await;- if is_disconnected(config, connection_id) {- tracing::debug!(- connection_id = %connection_id,- "[memory:sources] dropping records read before their connection was deleted"- );- return Ok(0);- }- let mut keys = Vec::with_capacity(records.len());- let mut items = Vec::with_capacity(records.len());- let mut emptied = Vec::new();- for record in records {- let key = super::versions::key(connection_id, &record.item_id);- match record_item(toolkit, connection_id, source_id, record) {- Some(item) => {- keys.push(key);- items.push(item);- }- None => emptied.push(key),- }- }- if !items.is_empty() {- // Before the write, so an item stored is never under an unrecorded- // root.- super::roots::record(- &config.workspace_dir,- connection_id,- &layout.root().to_string(),- )- .map_err(|error| {- MemoryError::Engine(format!(- "recording the connection's memory root failed: {error}"- ))- })?;- }- let ids = super::sync::store_all_ids(- config,- bound,- items,- (- crate::config::schema::MemorySourceKind::Composio,- toolkit,- source_id,- ),- layout,- )- .await?;- let stored: Vec<(String, String)> = keys- .into_iter()- .zip(ids)- .filter_map(|(key, id)| Some((key, id?)))- .collect();- let stale = super::versions::begin(&config.workspace_dir, &stored, &emptied);- forget_stale(config, bound, toolkit, stale).await;- Ok(stored.len() as u64)-}--/// Forgets the previous versions [`super::versions::begin`] handed back and-/// settles them. A failed forget leaves them pending, so the next sync-/// retries; it never fails the sync.-async fn forget_stale(config: &Config, bound: &BoundEngine, toolkit: &str, stale: Vec<String>) {- if stale.is_empty() {- return;- }- let ids = stale- .iter()- .cloned()- .map(tinymemory_api::ItemId::new)- .collect();- match bound- .engine- .forget(tinymemory_api::ForgetTarget::Ids(ids))- .await- {- Ok(report) => {- tracing::debug!(- toolkit = %toolkit,- stale = stale.len(),- forgotten = report.forgotten,- "[memory:sources] forgot the previous versions of edited records"- );- super::versions::settle(&config.workspace_dir, &stale);- }- Err(error) => tracing::warn!(- toolkit = %toolkit,- stale = stale.len(),- code = MemoryError::from(error).code(),- "[memory:sources] forgetting previous versions failed; retrying next sync"- ),- }-}--/// Syncs every active connection of the source's toolkit.-pub async fn sync_toolkit(- config: &Config,- bound: &BoundEngine,- source: &MemorySourceConfig,-) -> MemoryResult<u64> {- let toolkit = source.target.as_str();- let connections = active_connection_ids(config, toolkit)- .await- .map_err(MemoryError::Engine)?;- if connections.is_empty() {- return Err(MemoryError::invalid(format!(- "no active {toolkit} connection; connect it first"- )));- }- let mut stored = 0u64;- for connection_id in connections {- for _ in 0..MAX_PASSES_PER_CONNECTION {- let pass = run_sync_pass(- config,- bound,- toolkit,- &connection_id,- &source.id,- "manual",- SYNC_PASS_MAX_ITEMS,- )- .await- .map_err(MemoryError::Engine)?;- stored += pass.written;- if let Some(failure) = pass.failure {- return Err(MemoryError::Engine(failure));- }- if !pass.more_pending {- break;- }- }- }- Ok(stored)-}--/// The memory source id a Composio sync of `toolkit` files its items under:-/// the configured `composio` source for the toolkit when there is one, else-/// `composio:<toolkit>`.-#[must_use]-pub fn source_id_for_toolkit(config: &Config, toolkit: &str) -> String {- use crate::integrations::composio::tools::canonicalize_toolkit_slug;- let toolkit = canonicalize_toolkit_slug(toolkit);- config- .memory- .sources- .iter()- .find(|source| {- source.kind == crate::config::schema::MemorySourceKind::Composio- && canonicalize_toolkit_slug(&source.target) == toolkit- })- .map_or_else(|| format!("composio:{toolkit}"), |source| source.id.clone())-}--/// Forgets every item synced through `connection_id`. Memory off forgets-/// nothing and is not an error.-///-/// With the connection's `toolkit` known, only that toolkit's brain source-/// is read (`source:<toolkit>`): under the current root and under every-/// root the connection filed items under before ([`super::roots`]), so-/// items left under a root no longer configured go too. Without the-/// toolkit, or when those sources hold none of the connection's items-/// (stored before roots were recorded), the whole tree is searched, so a-/// connection's items are never left behind.-pub async fn forget_connection(- config: &Config,- connection_id: &str,- toolkit: Option<&str>,-) -> MemoryResult<usize> {- // A sync pass storing this connection's records finishes first, so none- // of its items lands after the forget; any pass after it, even one that- // read its records before, stores nothing (`DISCONNECTED`). Marked even- // with memory off, so nothing is stored if memory comes back on.- let _serial = STORE.lock().await;- disconnected().insert((config.workspace_dir.clone(), connection_id.to_string()));- let bound = match crate::memory::engine::resolve(config).engine() {- Ok(bound) => bound,- Err(MemoryError::Off(_)) => return Ok(0),- Err(error) => return Err(error),- };- let recorded = super::roots::of(&config.workspace_dir, connection_id);- let reaches = match toolkit {- // An unreadable roots record cannot bound the search: search all.- Some(toolkit) => match &recorded {- Some(recorded) => toolkit_reaches(config, toolkit, recorded)?,- None => Vec::new(),- },- None => {- tracing::warn!(- connection_id = %connection_id,- "[memory:sources] toolkit unknown; forgetting the connection across all memory"- );- Vec::new()- }- };- tracing::debug!(- connection_id = %connection_id,- roots = reaches.len(),- "[memory:sources] forgetting a connection's items"- );- let filter = |reach| tinymemory_api::MetaFilter {- reach,- sources: vec![SourceKind::Composio],- tags_any: vec![connection_tag(connection_id)],- ..tinymemory_api::MetaFilter::default()- };- let mut forgotten = 0;- for reach in &reaches {- forgotten += bound- .engine- .forget(tinymemory_api::ForgetTarget::Filter(filter(Some(- reach.clone(),- ))))- .await?- .forgotten;- }- if forgotten == 0 {- if !reaches.is_empty() {- tracing::debug!(- connection_id = %connection_id,- "[memory:sources] nothing in the toolkit's sources; searching all memory"- );- }- forgotten = bound- .engine- .forget(tinymemory_api::ForgetTarget::Filter(filter(None)))- .await?- .forgotten;- }- if let Some(recorded) = &recorded {- super::roots::forget(&config.workspace_dir, connection_id, recorded);- }- super::versions::drop_connection(&config.workspace_dir, connection_id);- Ok(forgotten)-}--/// `source:<toolkit>` under the current root and under every `recorded`-/// root.-fn toolkit_reaches(- config: &Config,- toolkit: &str,- recorded: &std::collections::BTreeSet<String>,-) -> MemoryResult<Vec<tinymemory_api::Reach>> {- let source = crate::memory::brain::brain_source(- crate::config::schema::MemorySourceKind::Composio,- toolkit,- );- let current = super::layout_of(config, &source_id_for_toolkit(config, toolkit));- let mut roots = recorded.clone();- roots.insert(current.root().to_string());- let mut reaches = Vec::with_capacity(roots.len());- for root in roots {- let layout = root- .parse::<tinymemory_api::Namespace>()- .map_err(|error| error.to_string())- .and_then(|root| {- tinymemory_tools::MemoryLayout::new(root).map_err(|error| error.to_string())- });- match layout {- Ok(layout) => reaches.push(tinymemory_api::Reach::subtree(layout.brain(&source)?)),- Err(error) => {- tracing::warn!(%error, "[memory:sources] skipping an unreadable recorded root")- }- }- }- Ok(reaches)-}--#[cfg(test)]-#[path = "composio_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/sources/composio_tests.rs b/crates/openhuman-core/src/memory/sources/composio_tests.rsdeleted file mode 100644index 08104b0545..0000000000--- a/crates/openhuman-core/src/memory/sources/composio_tests.rs+++ /dev/null@@ -1,546 +0,0 @@-use super::*;-use crate::config::schema::MemorySourceKind;-use crate::memory::test_fixtures::{bind_reference, config_in, stored};-use tinymemory_api::{ItemKind, MetaFilter};-use tinymemory_tools::MemoryLayout;--fn record(id: &str, title: &str, content: &str) -> ConnectorRecord {- ConnectorRecord {- item_id: id.to_string(),- title: title.to_string(),- content: content.to_string(),- ..ConnectorRecord::default()- }-}--#[test]-fn record_item_builds_a_tagged_document() {- let mut rec = record("m-1", " Quarterly plan ", "ship memory v2");- rec.mime = Some("text/plain".into());- rec.url = Some("https://mail.example/m-1".into());- rec.updated_at_ms = Some(1_700_000_000_000);- rec.tags = vec!["inbox".into(), " ".into(), "gmail".into(), "inbox".into()];-- let item = record_item("GMail", "conn-7", "src-g", &rec).expect("an item");- let StoreItem::Document {- title,- body,- mime,- meta,- } = item- else {- panic!("expected a document");- };- assert_eq!(title.as_deref(), Some("Quarterly plan"));- assert!(matches!(body, DocumentBody::Text(ref t) if t == "ship memory v2"));- assert_eq!(mime.as_deref(), Some("text/plain"));- assert_eq!(meta.url.as_deref(), Some("https://mail.example/m-1"));- assert_eq!(meta.source.kind, SourceKind::Composio);- assert_eq!(meta.source.id.as_deref(), Some("src-g"));- assert_eq!(- meta.tags,- vec![- "gmail".to_string(),- "connection:conn-7".to_string(),- "inbox".to_string()- ],- "toolkit and connection first, blanks and duplicates dropped"- );- assert_eq!(- meta.observed_at.map(|t| t.timestamp_millis()),- Some(1_700_000_000_000)- );-}--#[test]-fn record_item_skips_empty_content_and_blank_titles() {- assert!(record_item("gmail", "c", "s", &record("1", "t", " ")).is_none());- let StoreItem::Document { title, .. } =- record_item("gmail", "c", "s", &record("1", " ", "body")).unwrap()- else {- panic!("expected a document");- };- assert!(title.is_none());-}--#[test]-fn connection_tag_is_namespaced() {- assert_eq!(connection_tag("abc"), "connection:abc");-}--#[tokio::test]-async fn store_records_stores_the_non_empty_ones() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- let records = vec![- record("1", "One", "first record"),- record("2", "Empty", " "),- record("3", "Three", "third record"),- ];- let stored_count = store_records(- &config,- &bound,- "notion",- "conn-1",- "src-n",- &MemoryLayout::default(),- &records,- )- .await- .unwrap();- assert_eq!(stored_count, 2);- let docs = stored(- &engine,- MetaFilter {- kinds: vec![ItemKind::Document],- ..MetaFilter::default()- },- )- .await;- assert_eq!(docs.len(), 2);- assert!(docs- .iter()- .all(|d| d.meta.source.kind == SourceKind::Composio));- assert!(- docs.iter()- .all(|d| d.meta.namespace.to_string() == "source:notion"),- "filed under the toolkit's brain source"- );- assert_eq!(- crate::memory::lifecycle::jobs::snapshot(&config)- .await- .pending- .len(),- 1- );-}--#[tokio::test]-async fn store_records_with_nothing_to_store_is_zero() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- assert_eq!(- store_records(- &config,- &bound,- "notion",- "c",- "s",- &MemoryLayout::default(),- &[]- )- .await- .unwrap(),- 0- );-}--#[test]-fn source_id_for_toolkit_prefers_the_configured_source() {- let tmp = tempfile::tempdir().unwrap();- let mut config = config_in(&tmp);- assert_eq!(source_id_for_toolkit(&config, "Gmail"), "composio:gmail");- config- .memory- .sources- .push(crate::config::schema::MemorySourceConfig {- id: "src-gmail".into(),- kind: MemorySourceKind::Composio,- target: "gmail".into(),- label: "Gmail".into(),- schedule_mins: None,- namespace: None,- });- config- .memory- .sources- .push(crate::config::schema::MemorySourceConfig {- id: "src-folder".into(),- kind: MemorySourceKind::Folder,- target: "notion".into(),- label: "Folder named like a toolkit".into(),- schedule_mins: None,- namespace: None,- });- assert_eq!(source_id_for_toolkit(&config, "GMAIL"), "src-gmail");- assert_eq!(source_id_for_toolkit(&config, "notion"), "composio:notion");-- // A source saved before targets were canonicalized still matches the- // slug Composio reports for its connections.- config- .memory- .sources- .push(crate::config::schema::MemorySourceConfig {- id: "src-drive".into(),- kind: MemorySourceKind::Composio,- target: "google_drive".into(),- label: "Drive".into(),- schedule_mins: None,- namespace: None,- });- assert_eq!(source_id_for_toolkit(&config, "googledrive"), "src-drive");- assert_eq!(source_id_for_toolkit(&config, "google_drive"), "src-drive");-}--#[tokio::test]-async fn forget_connection_removes_only_that_connections_items() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- store_records(- &config,- &bound,- "gmail",- "conn-a",- "src",- &MemoryLayout::default(),- &[record("1", "A", "from a")],- )- .await- .unwrap();- store_records(- &config,- &bound,- "gmail",- "conn-b",- "src",- &MemoryLayout::default(),- &[record("2", "B", "from b")],- )- .await- .unwrap();- assert_eq!(- forget_connection(&config, "conn-a", Some("gmail"))- .await- .unwrap(),- 1- );- let left = stored(&engine, MetaFilter::default()).await;- assert_eq!(left.len(), 1);- assert!(left[0].meta.tags.contains(&"connection:conn-b".to_string()));-}--#[tokio::test]-async fn forget_connection_reads_every_root_its_items_were_filed_under() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- // One connection's items under the current root and under one it used- // before (a source namespace since changed), plus another connection.- for (connection, layout) in [- ("conn-c", MemoryLayout::default()),- (- "conn-c",- MemoryLayout::new("team:old".parse().unwrap()).unwrap(),- ),- ("conn-d", MemoryLayout::default()),- ] {- store_records(- &config,- &bound,- "gmail",- connection,- "src",- &layout,- &[record(- &format!("{connection}-{}", layout.root()),- "m",- "mail",- )],- )- .await- .unwrap();- }- assert_eq!(- super::super::roots::of(&config.workspace_dir, "conn-c")- .unwrap()- .len(),- 2- );-- assert_eq!(- forget_connection(&config, "conn-c", Some("gmail"))- .await- .unwrap(),- 2,- "both roots' items, though the current one alone found some"- );- let left = stored(&engine, MetaFilter::default()).await;- assert_eq!(left.len(), 1);- assert!(left[0].meta.tags.contains(&"connection:conn-d".to_string()));- assert!(super::super::roots::of(&config.workspace_dir, "conn-c")- .unwrap()- .is_empty());-}--#[tokio::test]-async fn an_edited_record_replaces_its_previous_version() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- let sync = |records: Vec<ConnectorRecord>| {- let (config, bound) = (&config, &bound);- async move {- store_records(- config,- bound,- "notion",- "conn-a",- "src",- &MemoryLayout::default(),- &records,- )- .await- .unwrap()- }- };- let texts = || async {- let mut texts: Vec<String> = stored(&engine, MetaFilter::default())- .await- .into_iter()- .map(|hit| hit.text)- .collect();- texts.sort();- texts- };-- sync(vec![- record("p1", "Plan", "v1"),- record("p2", "Notes", "kept"),- ])- .await;- // The same records again: nothing is stale.- sync(vec![- record("p1", "Plan", "v1"),- record("p2", "Notes", "kept"),- ])- .await;- assert_eq!(texts().await, ["# Notes\n\nkept", "# Plan\n\nv1"]);-- // p1 edited upstream: its old version goes, p2 stays.- assert_eq!(sync(vec![record("p1", "Plan", "v2")]).await, 1);- assert_eq!(texts().await, ["# Notes\n\nkept", "# Plan\n\nv2"]);-- // p2 comes back empty upstream: its stored version goes.- sync(vec![record("p2", "Notes", " ")]).await;- assert_eq!(texts().await, ["# Plan\n\nv2"]);-- // Disconnecting drops the record ids with the items.- forget_connection(&config, "conn-a", Some("notion"))- .await- .unwrap();- assert!(super::super::versions::begin(- &config.workspace_dir,- &[(super::super::versions::key("conn-a", "p1"), "other".into())],- &[]- )- .is_empty());-}--#[tokio::test]-async fn forget_connection_with_memory_off_forgets_nothing() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- assert_eq!(- forget_connection(&config, "conn-a", Some("gmail"))- .await- .unwrap(),- 0- );- assert!(- is_disconnected(&config, "conn-a"),- "the deletion is recorded even with memory off"- );-}--#[tokio::test]-async fn forget_connection_reads_only_its_toolkits_source() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- // The same connection tag in another toolkit's source: an item the- // scoped forget must not reach.- for toolkit in ["gmail", "notion"] {- store_records(- &config,- &bound,- toolkit,- "conn-a",- "src",- &MemoryLayout::default(),- &[record(toolkit, toolkit, &format!("from {toolkit}"))],- )- .await- .unwrap();- }- assert_eq!(- forget_connection(&config, "conn-a", Some("gmail"))- .await- .unwrap(),- 1- );- let left = stored(&engine, MetaFilter::default()).await;- assert_eq!(left.len(), 1);- assert_eq!(left[0].meta.namespace.to_string(), "source:notion");-- // Items filed under a root no longer configured (a removed source's own- // namespace) are outside the toolkit's source: the scoped forget finds- // none and falls back to the whole tree.- let elsewhere = MemoryLayout::new("team:old".parse().unwrap()).unwrap();- store_records(- &config,- &bound,- "gmail",- "conn-b",- "src",- &elsewhere,- &[record("b", "b", "from an old root")],- )- .await- .unwrap();- assert_eq!(- forget_connection(&config, "conn-b", Some("gmail"))- .await- .unwrap(),- 1- );-- // An unknown toolkit falls back to the whole tree.- assert_eq!(forget_connection(&config, "conn-a", None).await.unwrap(), 1);- assert!(stored(&engine, MetaFilter::default()).await.is_empty());-}--#[tokio::test]-async fn sync_toolkit_without_a_connector_is_an_error_not_a_panic() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- let source = crate::config::schema::MemorySourceConfig {- id: "src-gmail".into(),- kind: MemorySourceKind::Composio,- target: "gmail".into(),- label: "Gmail".into(),- schedule_mins: None,- namespace: None,- };- assert!(sync_toolkit(&config, &bound, &source).await.is_err());-}--#[tokio::test]-async fn a_disconnect_waits_for_a_store_in_progress() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- bind_reference(&config);- // A store of this connection's records is running.- let held = STORE.lock().await;- let forget = {- let config = config.clone();- tokio::spawn(async move { forget_connection(&config, "conn-w", Some("gmail")).await })- };- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- assert!(!forget.is_finished(), "the disconnect waits for the store");- drop(held);- assert_eq!(forget.await.unwrap().unwrap(), 0);-}--#[tokio::test]-async fn records_read_before_a_disconnect_are_not_stored_after_it() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let engine = bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- forget_connection(&config, "conn-gone", Some("gmail"))- .await- .unwrap();- assert!(is_disconnected(&config, "conn-gone"));- // A pass that read its records before the disconnect stores nothing.- let stored_now = store_records(- &config,- &bound,- "gmail",- "conn-gone",- "src",- &MemoryLayout::default(),- &[record("late", "Late", "read before the disconnect")],- )- .await- .unwrap();- assert_eq!(stored_now, 0);- assert!(stored(&engine, MetaFilter::default()).await.is_empty());- // Another connection, or the same id in another workspace, is unaffected.- assert!(!is_disconnected(&config, "conn-other"));-}--#[tokio::test]-async fn a_deleted_connection_is_not_read_again() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- bind_reference(&config);- let bound = crate::memory::engine::resolve(&config).engine().unwrap();- forget_connection(&config, "conn-x", Some("gmail"))- .await- .unwrap();- // No connector call is made: an empty pass with nothing pending ends- // the caller's loop.- let pass = run_sync_pass(- &config,- &bound,- "gmail",- "conn-x",- "src",- "manual",- SYNC_PASS_MAX_ITEMS,- )- .await- .unwrap();- assert_eq!(pass.records_read, 0);- assert_eq!(pass.written, 0);- assert!(!pass.more_pending);- assert!(pass.failure.is_none());-}--#[test]-fn a_records_sender_becomes_its_observed_actor() {- let actor_of = |address: &str, name: Option<&str>| {- let mut rec = record("m-1", "Lunch", "see you at noon");- rec.sender = Some(RecordSender {- address: address.into(),- name: name.map(str::to_string),- });- record_item("gmail", "conn-7", "src-g", &rec)- .expect("an item")- .meta()- .observed_actor- .clone()- };- assert_eq!(- actor_of(" [email protected] ", Some(" Priya ")),- Some(ObservedActor {- id: "user:[email protected]".into(),- name: Some("Priya".into()),- }),- "an email address, lower-cased, with the name"- );- assert_eq!(- actor_of("+15551234567", Some(" ")),- Some(ObservedActor {- id: "user:+15551234567".into(),- name: None,- }),- "a phone number as given; a blank name is none"- );- assert_eq!(actor_of(" ", Some("Priya")), None, "no address, no actor");-- let unsent =- record_item("gmail", "conn-7", "src-g", &record("m-2", "", "no sender")).expect("an item");- assert_eq!(unsent.meta().observed_actor, None);-}diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex 8168e1d6fb..d1dc86ab43 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+//! A source names something to read — a local folder or a single file — 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};@@ -59,8 +55,7 @@ pub fn list(config: &Config) -> Vec<SourceView> {.collect()}-/// 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.+/// Normalises a target for `kind`: a folder or file path, trimmed.pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<String> {let target = target.trim();if target.is_empty() {@@ -68,42 +63,9 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<St}match kind {MemorySourceKind::Folder | MemorySourceKind::File => Ok(target.to_string()),- MemorySourceKind::Github => {- if target.starts_with("http://") || target.starts_with("https://") {- return http_url(target);- }- let mut parts = target.split('/');- match (parts.next(), parts.next(), parts.next()) {- (Some(owner), Some(repo), None) if !owner.is_empty() && !repo.is_empty() => {- Ok(format!("https://github.com/{owner}/{repo}"))- }- _ => Err(MemoryError::invalid(- "a GitHub target is `owner/repo` or a repository URL",- )),- }- }- 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"))- }- }}}-fn http_url(target: &str) -> MemoryResult<String> {- let url = url::Url::parse(target).map_err(|_| MemoryError::invalid("target is not a URL"))?;- if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {- return Err(MemoryError::invalid("target must be an http(s) URL"));- }- Ok(url.to_string())-}-/// Builds a new source from `memory_sources_add` params and appends it to/// `config`; the caller persists `config`.pub fn apply_add(@@ -112,7 +74,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 `{}`: only folder and file sources are supported",params.kind.trim()))})?;@@ -124,19 +86,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/roots.rs b/crates/openhuman-core/src/memory/sources/roots.rsdeleted file mode 100644index 0d9da66897..0000000000--- a/crates/openhuman-core/src/memory/sources/roots.rs+++ /dev/null@@ -1,122 +0,0 @@-//! Which layout roots each Composio connection's items were filed under.-//!-//! A connection's items go to its toolkit's brain source in the layout of-//! the source configured for it, and that layout can change between syncs-//! (a source's own `namespace` set, changed or removed). Forgetting a-//! connection reads `source:<toolkit>` under every root recorded here, so-//! items filed under an earlier root are forgotten with the rest. It lives-//! in `<workspace>/memory/connection_roots.json`.--use std::collections::{BTreeMap, BTreeSet};-use std::path::{Path, PathBuf};-use std::sync::{LazyLock, Mutex};--/// Serialises every read and read-modify-write of the file in this process.-static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));--type Roots = BTreeMap<String, BTreeSet<String>>;--fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("connection_roots.json")-}--/// The file's contents. A read error is returned and nothing is changed, so-/// a file that is only unreadable for now is never replaced. A file that-/// reads but does not parse is set aside (`.corrupt`) with a warning.-fn load(workspace_dir: &Path) -> std::io::Result<Roots> {- let file = path(workspace_dir);- let text = match std::fs::read_to_string(&file) {- Ok(text) => text,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Roots::new()),- Err(error) => return Err(error),- };- Ok(serde_json::from_str(&text).unwrap_or_else(|error| {- tracing::warn!(error = %error, "[memory:sources] connection roots unparsable");- set_aside(&file)- }))-}--fn set_aside(file: &Path) -> Roots {- if let Err(error) = std::fs::rename(file, file.with_extension("json.corrupt")) {- tracing::warn!(error = %error, "[memory:sources] could not set the roots file aside");- }- Roots::new()-}--/// Writes through a temporary file and a rename, so a stop mid-write never-/// leaves a partial file.-fn save(workspace_dir: &Path, all: &Roots) -> std::io::Result<()> {- let file = path(workspace_dir);- let temp = file.with_extension("json.tmp");- if let Some(parent) = file.parent() {- std::fs::create_dir_all(parent)?;- }- let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;- let mut out = std::fs::File::create(&temp)?;- std::io::Write::write_all(&mut out, &json)?;- // On disk before it replaces the old file, so a power loss cannot- // leave a renamed file with unwritten contents.- out.sync_all()?;- std::fs::rename(&temp, &file)-}--fn locked() -> std::sync::MutexGuard<'static, ()> {- LOCK.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)-}--/// Records that `connection_id` files items under `root`.-///-/// # Errors-///-/// The record could not be written: the caller must not file items under-/// a root a later forget would not know.-pub fn record(workspace_dir: &Path, connection_id: &str, root: &str) -> std::io::Result<()> {- let _guard = locked();- let mut all = load(workspace_dir)?;- if all- .entry(connection_id.to_string())- .or_default()- .insert(root.to_string())- {- save(workspace_dir, &all)?;- }- Ok(())-}--/// Every root `connection_id` filed items under, or `None` when the record-/// cannot be read: the caller must then search everywhere.-#[must_use]-pub fn of(workspace_dir: &Path, connection_id: &str) -> Option<BTreeSet<String>> {- let _guard = locked();- match load(workspace_dir) {- Ok(mut all) => Some(all.remove(connection_id).unwrap_or_default()),- Err(error) => {- tracing::warn!(error = %error, "[memory:sources] connection roots unreadable");- None- }- }-}--/// Forgets `roots` of `connection_id`, once its items under them are gone.-/// A root recorded meanwhile (a sync during the forget) is kept.-pub fn forget(workspace_dir: &Path, connection_id: &str, roots: &BTreeSet<String>) {- let _guard = locked();- let Ok(mut all) = load(workspace_dir) else {- return;- };- let Some(held) = all.get_mut(connection_id) else {- return;- };- held.retain(|root| !roots.contains(root));- if held.is_empty() {- all.remove(connection_id);- }- if let Err(error) = save(workspace_dir, &all) {- tracing::warn!(error = %error, "[memory:sources] writing connection roots failed");- }-}--#[cfg(test)]-#[path = "roots_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/sources/roots_tests.rs b/crates/openhuman-core/src/memory/sources/roots_tests.rsdeleted file mode 100644index 9467a81a27..0000000000--- a/crates/openhuman-core/src/memory/sources/roots_tests.rs+++ /dev/null@@ -1,59 +0,0 @@-use super::*;--#[test]-fn forgetting_keeps_a_root_recorded_meanwhile() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- record(dir, "c", "root").unwrap();- let seen = of(dir, "c").unwrap();- // A sync records another root while the forget runs.- record(dir, "c", "team:new").unwrap();- forget(dir, "c", &seen);- assert_eq!(- of(dir, "c").unwrap(),- BTreeSet::from(["team:new".to_string()])- );- forget(dir, "c", &of(dir, "c").unwrap());- assert!(of(dir, "c").unwrap().is_empty());-}--#[test]-fn an_unparsable_file_is_set_aside_not_overwritten() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let file = path(dir);- std::fs::create_dir_all(file.parent().unwrap()).unwrap();- std::fs::write(&file, "{ not json").unwrap();- assert!(of(dir, "c").unwrap().is_empty());- assert_eq!(- std::fs::read_to_string(file.with_extension("json.corrupt")).unwrap(),- "{ not json"- );- record(dir, "c", "root").unwrap();- assert_eq!(of(dir, "c").unwrap().len(), 1, "recording resumed");-}--#[test]-fn a_record_that_cannot_be_written_is_an_error() {- let tmp = tempfile::tempdir().unwrap();- // `memory` is a file, so the record's directory cannot be made.- std::fs::write(tmp.path().join("memory"), "").unwrap();- assert!(record(tmp.path(), "c", "root").is_err());-}--#[test]-fn an_unreadable_file_is_left_alone_and_reported() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- record(dir, "c", "root").unwrap();- // A directory where the file should be cannot be read as text.- let file = path(dir);- std::fs::remove_file(&file).unwrap();- std::fs::create_dir(&file).unwrap();- assert!(of(dir, "c").is_none(), "the caller must search everywhere");- assert!(- record(dir, "c", "team:new").is_err(),- "nothing is filed unrecorded"- );- assert!(file.is_dir(), "nothing was set aside or overwritten");-}diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex a1929d1fdf..e7259aea8f 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -1,17 +1,17 @@//! Syncing sources into memory.//!-//! Non-Composio sources are read through `tinymemory-sources`' 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`].+//! Sources are read through `tinymemory-integrations`' readers+//! (`collect_items`), which turn each file under a folder, or the one file,+//! 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.use std::collections::HashSet;use std::path::PathBuf;use std::sync::{LazyLock, Mutex};use chrono::{DateTime, Utc};-use tinymemory_integrations::sources::readers::reader_for_request;+use tinymemory_integrations::sources::readers::reader_for;use tinymemory_integrations::sources::{collect_items, MemorySourceEntry, SourceKind};use crate::config::schema::{MemorySourceConfig, MemorySourceKind};@@ -28,55 +28,26 @@ 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 {- MemorySourceKind::Folder | MemorySourceKind::File => {- entry.path = Some(source.target.clone())- }- _ => entry.url = Some(source.target.clone()),- }- apply_kind_defaults(&mut entry);+ entry.path = Some(source.target.clone());entry.validate().map_err(|error| MemoryError::invalid(error.to_string()))?;- Ok(Some(entry))-}--/// Fills the per-kind read caps the user did not set: a GitHub repo reads at-/// most 10 PRs, 10 issues and 50 commits, a feed at most 20 items. How much a-/// sync pulls is host policy, so it lives here rather than in the readers.-fn apply_kind_defaults(entry: &mut MemorySourceEntry) {- match entry.kind {- SourceKind::GithubRepo => {- entry.max_prs.get_or_insert(10);- entry.max_issues.get_or_insert(10);- entry.max_commits.get_or_insert(50);- }- SourceKind::RssFeed => {- entry.max_items.get_or_insert(20);- }- _ => {}- }+ Ok(entry)}/// 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 reader = reader_for_request(&entry.kind);+ let entry = reader_entry(source)?;+ let reader = reader_for(&entry.kind)+ .ok_or_else(|| MemoryError::invalid("no reader for this source kind"))?;let collected = collect_items(reader.as_ref(),&entry,@@ -106,26 +77,14 @@ pub async fn sync_one(config: &Config, source: &MemorySourceConfig) -> MemoryRes/// belongs to (`memory::brain::brain_node`), and queues one belief build/// per node it touched. Returns how many were stored.pub(crate) async fn store_all(- config: &Config,- bound: &BoundEngine,- items: Vec<tinymemory_api::StoreItem>,- source: (crate::config::schema::MemorySourceKind, &str, &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());+) -> MemoryResult<u64> {+ let mut stored = 0u64;+ let mut failed = 0u64;let mut last_error = None;let mut touched = std::collections::BTreeSet::new();for item in items {diff --git a/crates/openhuman-core/src/memory/sources/versions.rs b/crates/openhuman-core/src/memory/sources/versions.rsdeleted file mode 100644index 9ecbdc26fc..0000000000--- a/crates/openhuman-core/src/memory/sources/versions.rs+++ /dev/null@@ -1,186 +0,0 @@-//! Which stored item holds the current version of each connector record.-//!-//! A memory item's id is a digest of its content, so a record edited-//! upstream (a Notion page, a Linear issue) syncs as a new item and the old-//! version stays beside it. This file remembers, per record-//! ([`key`]), the id of the item last stored for it. A sync pass-//! ([`begin`]) records the ids it stored and the records that came back-//! empty, and hands back the ids no record uses any more; the caller-//! forgets them and then [`settle`]s them. Until settled they stay pending-//! and are handed back again by the next pass, so a failed forget is-//! retried and never orphans a version. It lives in-//! `<workspace>/memory/connector_items.json`.-//!-//! A workspace without the file (a new device) cannot tell an old version-//! from a new one, so versions stored before it existed stay until the-//! source is re-synced from scratch.--use std::collections::{BTreeMap, BTreeSet};-use std::path::{Path, PathBuf};-use std::sync::{LazyLock, Mutex};--use serde::{Deserialize, Serialize};--/// Serialises every read and read-modify-write of the file in this process.-static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));--/// The file's contents.-#[derive(Debug, Default, Serialize, Deserialize)]-struct Versions {- /// Record key → the id of the item holding its current version.- #[serde(default)]- items: BTreeMap<String, String>,- /// Ids no record uses any more, not yet forgotten.- #[serde(default)]- stale: BTreeSet<String>,-}--fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("connector_items.json")-}--// ponytail: the whole map is read and rewritten per sync pass (~100 B a-// record, so ~1 MB at 10k records); a keyed store if accounts grow past that.-/// The file's contents, or `None` when it cannot be read right now: the-/// caller then changes nothing. A file that reads but does not parse is set-/// aside (`.corrupt`) with a warning rather than overwritten, and tracking-/// starts again from empty.-fn load(workspace_dir: &Path) -> Option<Versions> {- let file = path(workspace_dir);- let text = match std::fs::read_to_string(&file) {- Ok(text) => text,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- return Some(Versions::default())- }- Err(error) => {- tracing::warn!(error = %error, "[memory:sources] connector item versions unreadable; skipping");- return None;- }- };- match serde_json::from_str(&text) {- Ok(versions) => Some(versions),- Err(error) => {- tracing::warn!(error = %error, "[memory:sources] connector item versions unparsable");- set_aside(&file)- }- }-}--/// Moves an unparsable file to `.corrupt` and starts from empty, or, when-/// it cannot be moved, changes nothing (`None`), so a later save never-/// overwrites the only copy.-fn set_aside(file: &Path) -> Option<Versions> {- match std::fs::rename(file, file.with_extension("json.corrupt")) {- Ok(()) => Some(Versions::default()),- Err(error) => {- tracing::warn!(error = %error, "[memory:sources] could not set the versions file aside; skipping");- None- }- }-}--/// Writes through a temporary file and a rename, so a stop mid-write never-/// leaves a partial file.-/// (`std::fs::rename` replaces an existing file on every platform.)-fn save(workspace_dir: &Path, versions: &Versions) -> bool {- let file = path(workspace_dir);- let temp = file.with_extension("json.tmp");- let result = file- .parent()- .map_or(Ok(()), std::fs::create_dir_all)- .and_then(|()| {- let json = serde_json::to_vec(versions).map_err(std::io::Error::other)?;- std::fs::write(&temp, json)?;- std::fs::rename(&temp, &file)- });- if let Err(error) = &result {- tracing::warn!(error = %error, "[memory:sources] writing connector item versions failed");- }- result.is_ok()-}--fn locked() -> std::sync::MutexGuard<'static, ()> {- LOCK.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)-}--/// The key one record of `connection_id` is remembered under. The-/// connection id is length-prefixed, so no pair of ids shares a key.-#[must_use]-pub fn key(connection_id: &str, item_id: &str) -> String {- format!("{}{item_id}", prefix(connection_id))-}--fn prefix(connection_id: &str) -> String {- format!("{}:{connection_id}:", connection_id.len())-}--/// Starts a sync pass: `stored` records (key, id now stored) and `emptied`-/// records (keys that came back with no content). Remembers their state and-/// returns every id to forget: those no record uses any more, and those an-/// earlier pass could not forget, even when this pass stored nothing.-/// Forget them, then [`settle`] them. Hands back nothing when the state-/// cannot be read or written, so no id is forgotten unrecorded.-#[must_use]-pub fn begin(workspace_dir: &Path, stored: &[(String, String)], emptied: &[String]) -> Vec<String> {- let _guard = locked();- let Some(mut versions) = load(workspace_dir) else {- return Vec::new();- };- if stored.is_empty() && emptied.is_empty() {- return versions.stale.into_iter().collect();- }- let mut replaced = Vec::new();- for (key, id) in stored {- if let Some(old) = versions.items.insert(key.clone(), id.clone()) {- if old != *id {- replaced.push(old);- }- }- }- for key in emptied {- replaced.extend(versions.items.remove(key));- }- versions.stale.extend(replaced);- // An id another record still holds (two records with the same content)- // is not stale.- let current: BTreeSet<&String> = versions.items.values().collect();- versions.stale.retain(|id| !current.contains(id));- if !save(workspace_dir, &versions) {- return Vec::new();- }- versions.stale.into_iter().collect()-}--/// Marks `forgotten` as gone: they are no longer handed back.-pub fn settle(workspace_dir: &Path, forgotten: &[String]) {- if forgotten.is_empty() {- return;- }- let _guard = locked();- let Some(mut versions) = load(workspace_dir) else {- return;- };- for id in forgotten {- versions.stale.remove(id);- }- let _ = save(workspace_dir, &versions);-}--/// Forgets every record of `connection_id`, once its items are gone.-pub fn drop_connection(workspace_dir: &Path, connection_id: &str) {- let _guard = locked();- let Some(mut versions) = load(workspace_dir) else {- return;- };- let prefix = prefix(connection_id);- let before = versions.items.len();- versions.items.retain(|key, _| !key.starts_with(&prefix));- if versions.items.len() != before {- let _ = save(workspace_dir, &versions);- }-}--#[cfg(test)]-#[path = "versions_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/sources/versions_tests.rs b/crates/openhuman-core/src/memory/sources/versions_tests.rsdeleted file mode 100644index 3e7ecb8b57..0000000000--- a/crates/openhuman-core/src/memory/sources/versions_tests.rs+++ /dev/null@@ -1,116 +0,0 @@-use super::*;--fn pair(key: &str, id: &str) -> (String, String) {- (key.to_string(), id.to_string())-}--#[test]-fn a_changed_record_hands_back_its_previous_id() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- assert!(begin(dir, &[pair("k1", "a"), pair("k2", "b")], &[]).is_empty());-- // Unchanged, edited and new records: only the edited one's old id.- let stale = begin(- dir,- &[pair("k1", "a"), pair("k2", "b2"), pair("k3", "c")],- &[],- );- assert_eq!(stale, ["b"]);- settle(dir, &stale);- assert!(begin(dir, &[pair("k2", "b2")], &[]).is_empty());-}--#[test]-fn an_unsettled_id_is_handed_back_again_and_the_new_one_is_kept() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let _ = begin(dir, &[pair("k", "v1")], &[]);- // The forget of v1 fails: nothing is settled.- assert_eq!(begin(dir, &[pair("k", "v2")], &[]), ["v1"]);- // Edited again before the retry: v2 is stale too, v1 is still owed.- assert_eq!(begin(dir, &[pair("k", "v3")], &[]), ["v1", "v2"]);- settle(dir, &["v1".into(), "v2".into()]);- assert!(begin(dir, &[pair("k", "v3")], &[]).is_empty());-}--#[test]-fn an_id_another_record_still_holds_is_not_stale() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- // Two records with the same content share an id.- let _ = begin(dir, &[pair("a", "x"), pair("b", "x")], &[]);- assert!(- begin(dir, &[pair("a", "y")], &[]).is_empty(),- "b still holds x"- );- assert_eq!(begin(dir, &[pair("b", "z")], &[]), ["x"]);-}--#[test]-fn a_record_that_comes_back_empty_hands_back_its_id() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let _ = begin(dir, &[pair("k", "v1")], &[]);- assert_eq!(begin(dir, &[], &["k".into()]), ["v1"]);-}--#[test]-fn keys_do_not_collide_across_connections() {- assert_ne!(key("a:b", "c"), key("a", "b:c"));- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let _ = begin(- dir,- &[pair(&key("a:b", "c"), "x"), pair(&key("a", "b:c"), "y")],- &[],- );- drop_connection(dir, "a");- // `a:b`'s record is untouched by dropping `a`.- let stale = begin(dir, &[pair(&key("a:b", "c"), "x2")], &[]);- assert_eq!(stale, ["x"]);- settle(dir, &stale);- // `a`'s record was dropped, so its new id replaces nothing.- assert!(begin(dir, &[pair(&key("a", "b:c"), "y2")], &[]).is_empty());-}--#[test]-fn an_unparsable_file_is_set_aside_not_overwritten() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let file = path(dir);- std::fs::create_dir_all(file.parent().unwrap()).unwrap();- std::fs::write(&file, "{ not json").unwrap();- assert!(begin(dir, &[pair("k", "v")], &[]).is_empty());- assert_eq!(- std::fs::read_to_string(file.with_extension("json.corrupt")).unwrap(),- "{ not json"- );- assert_eq!(- begin(dir, &[pair("k", "v2")], &[]),- ["v"],- "tracking resumed"- );-}--#[test]-fn a_pass_with_no_records_still_hands_back_pending_ids() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let _ = begin(dir, &[pair("k", "v1")], &[]);- let _ = begin(dir, &[pair("k", "v2")], &[]); // the forget of v1 fails- assert_eq!(begin(dir, &[], &[]), ["v1"]);-}--#[test]-fn an_unreadable_file_changes_nothing() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path();- let _ = begin(dir, &[pair("k", "v1")], &[]);- // A directory where the file should be cannot be read as text.- let file = path(dir);- std::fs::remove_file(&file).unwrap();- std::fs::create_dir(&file).unwrap();- assert!(begin(dir, &[pair("k", "v2")], &[]).is_empty());- assert!(file.is_dir(), "nothing was set aside or overwritten");-}