Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(memory): sync local sources into hosted memory from the host

Shanu40661d077d77
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index a007f5c057..e7e3276249 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -98,6 +98,10 @@ async fn start_channels_inner(mut config: Config) -> Result<()> {
// is intentionally cheap and the loop body no-ops when there are
// no connections.
crate::integrations::composio::start_periodic_sync();
+ // The folder, GitHub, RSS and web sources a driver without a source
+ // pipeline of its own (hosted memory) needs refreshed; each tick checks the
+ // driver bound at that moment.
+ crate::memory::sources::start_hosted_periodic_sync();
// Task-sources: subscribe to Composio connection-created events for
// one-shot fetches, and spawn the periodic poll that pulls work from
// configured external sources onto the agent's todo board.
diff --git a/crates/openhuman-core/src/memory/sources/hosted_periodic.rs b/crates/openhuman-core/src/memory/sources/hosted_periodic.rs
new file mode 100644
index 0000000000..725b84af2a
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/hosted_periodic.rs
@@ -0,0 +1,245 @@
+//! Scheduled syncs of the local memory sources when the host syncs them.
+//!
+//! With the embedded engine, the TinyMemory module refreshes folder, GitHub,
+//! RSS and web-page sources on a schedule of its own. A driver that keeps what
+//! it is sent and runs no source pipeline (hosted memory; see
+//! [`super::hosted_sync`]) has no such schedule, so without this loop those
+//! sources would change only when the user pressed Sync. It runs each due
+//! source through the same host sync the Sync button reaches, recorded the
+//! same way, and it keeps the engine loop's rules:
+//!
+//! - the cadence is the user's `memory_sync_interval_secs`, never shorter than
+//! a day, and `0` means manual only;
+//! - a source is due when its last run from this loop, or its last successful
+//! run in the host's run log, is older than that — so a restart does not
+//! sync everything again;
+//! - nothing runs while the user is signed out or has turned background work
+//! off;
+//! - nothing runs unless the driver bound at that tick is one the host syncs,
+//! because the engine can be switched while the app runs.
+//!
+//! Connector sources are not scheduled here; the periodic Composio loop owns
+//! them. Nor are conversations and searches, which the engine's loop does not
+//! schedule either.
+
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock, PoisonError};
+use std::time::{Duration, Instant};
+
+use chrono::{DateTime, Utc};
+
+use crate::config::DEFAULT_MEMORY_SYNC_INTERVAL_SECS;
+use crate::cron::scheduler_gate::PauseReason;
+use crate::memory::api::provider::sync::SyncAuditEntry;
+use crate::memory::sources::hosted_sync;
+use crate::memory::sources::rpc::driver_run;
+use crate::memory::sources::run_history;
+use crate::memory::sources::types::{MemorySourceEntry, SourceKind};
+
+/// How often the loop looks for due sources. The per-source cadence, a day at
+/// least, bounds how often each one runs; this bounds how late past due it
+/// can start.
+const TICK: Duration = Duration::from_secs(1200);
+
+/// Guards [`start_hosted_periodic_sync`] against a second loop.
+static STARTED: OnceLock<()> = OnceLock::new();
+
+/// When this loop last started each source, by source id.
+fn last_fired() -> &'static Mutex<HashMap<String, Instant>> {
+ static FIRED: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
+ FIRED.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+/// Start the loop. Idempotent. Each tick does nothing unless the driver bound
+/// at that moment is one the host syncs, so an embedded engine, whose module
+/// schedules these sources itself, is left to it.
+pub fn start_hosted_periodic_sync() {
+ if STARTED.set(()).is_err() {
+ tracing::debug!("[memory_sources:hosted_periodic] loop already running");
+ return;
+ }
+ tracing::info!(
+ tick_secs = TICK.as_secs(),
+ "[memory_sources:hosted_periodic] starting the scheduled sync of local sources"
+ );
+ tokio::spawn(async move {
+ let mut ticker = tokio::time::interval(TICK);
+ // The first tick fires at once; skip it so startup is not spent
+ // syncing before the user has even signed in.
+ ticker.tick().await;
+ loop {
+ ticker.tick().await;
+ match run_one_tick().await {
+ Ok(0) => {}
+ Ok(ran) => tracing::debug!(ran, "[memory_sources:hosted_periodic] tick done"),
+ Err(error) => {
+ tracing::warn!(%error, "[memory_sources:hosted_periodic] tick failed");
+ }
+ }
+ }
+ });
+}
+
+/// One pass: run every due source, one after another, and answer how many
+/// ran.
+async fn run_one_tick() -> Result<usize, String> {
+ if let Some(reason) = pause_reason() {
+ tracing::debug!(
+ ?reason,
+ "[memory_sources:hosted_periodic] background work is paused; skipping"
+ );
+ return Ok(0);
+ }
+ let config = crate::config::rpc::load_config_with_timeout().await?;
+ let binding = crate::memory::binding::for_config(&config)?;
+ let provider = binding.provider();
+ if !hosted_sync::host_synced(provider.as_ref()) {
+ return Ok(0);
+ }
+ let Some(sink) = provider.as_sources() else {
+ return Ok(0);
+ };
+ let Some(interval_secs) = effective_interval_secs(config.memory_sync_interval_secs) else {
+ tracing::debug!("[memory_sources:hosted_periodic] manual-only; skipping");
+ return Ok(0);
+ };
+ let history = match run_history::read_runs(&config.workspace_dir, run_history::KEEP_ROWS) {
+ Ok(entries) => Some(last_success_by_source(&entries)),
+ Err(error) => {
+ tracing::warn!(
+ %error,
+ "[memory_sources:hosted_periodic] run log unreadable; only sources this \
+ process has run are considered"
+ );
+ None
+ }
+ };
+ let sources = crate::memory::sources::registry::list_sources_in(&config)?;
+ let fired: HashMap<String, Duration> = last_fired()
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .iter()
+ .map(|(source_id, at)| (source_id.clone(), at.elapsed()))
+ .collect();
+ let due = due_sources(
+ &sources,
+ interval_secs,
+ &fired,
+ history.as_ref(),
+ Utc::now(),
+ );
+ if due.is_empty() {
+ return Ok(0);
+ }
+
+ let mut ran = 0;
+ for source in due {
+ // Recorded before the run, success or not, so a source that keeps
+ // failing waits out its interval rather than retrying every tick.
+ last_fired()
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .insert(source.id.clone(), Instant::now());
+ tracing::info!(
+ source_id = %source.id,
+ kind = source.kind.as_str(),
+ interval_secs,
+ "[memory_sources:hosted_periodic] syncing a due source"
+ );
+ let result = driver_run::run_recorded(
+ &config,
+ &source.id,
+ Some(source),
+ || hosted_sync::run(&config, source, sink),
+ |error| error.to_string(),
+ driver_run::bus_stage_publisher(driver_run::PERIODIC, &source.id, source.kind.as_str()),
+ )
+ .await;
+ if let Err(error) = result {
+ tracing::warn!(
+ source_id = %source.id,
+ %error,
+ "[memory_sources:hosted_periodic] sync failed; retried when next due"
+ );
+ }
+ ran += 1;
+ }
+ Ok(ran)
+}
+
+/// Why background work is paused, when it is for a reason this loop honours:
+/// the user turned it off, or is signed out. Battery and CPU pressure throttle
+/// LLM work; a sync that is due a day at a time is not held back by them.
+fn pause_reason() -> Option<PauseReason> {
+ let reason = crate::cron::scheduler_gate::current_policy().pause_reason()?;
+ matches!(reason, PauseReason::UserDisabled | PauseReason::SignedOut).then_some(reason)
+}
+
+/// The cadence in seconds for the user's setting, or `None` for manual only.
+/// Never shorter than the default day, as the engine's loop rules.
+fn effective_interval_secs(configured: Option<u64>) -> Option<u64> {
+ match configured {
+ Some(0) => None,
+ Some(secs) => Some(secs.max(DEFAULT_MEMORY_SYNC_INTERVAL_SECS)),
+ None => Some(DEFAULT_MEMORY_SYNC_INTERVAL_SECS),
+ }
+}
+
+/// Source kinds this loop schedules.
+fn is_scheduled_kind(kind: &SourceKind) -> bool {
+ hosted_sync::serves(kind)
+}
+
+/// The newest successful run of each scheduled source in the run log.
+fn last_success_by_source(entries: &[SyncAuditEntry]) -> HashMap<String, DateTime<Utc>> {
+ let mut newest: HashMap<String, DateTime<Utc>> = HashMap::new();
+ for entry in entries.iter().filter(|entry| {
+ entry.success
+ && matches!(
+ entry.source_kind.as_str(),
+ "folder" | "github_repo" | "rss_feed" | "web_page"
+ )
+ }) {
+ newest
+ .entry(entry.source_id.clone())
+ .and_modify(|at| *at = (*at).max(entry.timestamp))
+ .or_insert(entry.timestamp);
+ }
+ newest
+}
+
+/// The enabled, scheduled sources whose last run is at least `interval_secs`
+/// old at `now`.
+///
+/// A source this process ran is timed from that run (`fired` holds how long
+/// ago each started). Otherwise it is timed from its last success in the run
+/// log, and one with none there has never synced and is due. Without a
+/// readable log, only sources this process ran can be timed, so the rest wait
+/// rather than all running at once.
+fn due_sources<'a>(
+ sources: &'a [MemorySourceEntry],
+ interval_secs: u64,
+ fired: &HashMap<String, Duration>,
+ history: Option<&HashMap<String, DateTime<Utc>>>,
+ now: DateTime<Utc>,
+) -> Vec<&'a MemorySourceEntry> {
+ let interval = Duration::from_secs(interval_secs);
+ sources
+ .iter()
+ .filter(|source| source.enabled && is_scheduled_kind(&source.kind))
+ .filter(|source| {
+ let since = match (fired.get(&source.id), history) {
+ (Some(elapsed), _) => Some(*elapsed),
+ (None, Some(history)) => history
+ .get(&source.id)
+ .map(|at| (now - *at).to_std().unwrap_or_default()),
+ (None, None) => return false,
+ };
+ since.is_none_or(|since| since >= interval)
+ })
+ .collect()
+}
+
+#[cfg(test)]
+#[path = "hosted_periodic_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs b/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs
new file mode 100644
index 0000000000..a693485f86
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs
@@ -0,0 +1,136 @@
+//! The hosted-memory schedule for local sources: its cadence, and which
+//! sources a tick finds due.
+
+use std::collections::HashMap;
+use std::time::Duration;
+
+use chrono::{DateTime, TimeZone, Utc};
+
+use super::*;
+use crate::memory::sources::run_history::HostRun;
+
+const DAY: u64 = 86_400;
+
+fn now() -> DateTime<Utc> {
+ Utc.timestamp_opt(1_789_000_000, 0)
+ .single()
+ .expect("a valid instant")
+}
+
+fn source(id: &str, kind: &str, enabled: bool) -> MemorySourceEntry {
+ serde_json::from_value(serde_json::json!({
+ "id": id,
+ "kind": kind,
+ "label": id,
+ "enabled": enabled,
+ "path": ".",
+ "url": "https://example.test/feed.xml",
+ "toolkit": "gmail",
+ "connection_id": "conn-1",
+ }))
+ .expect("a valid source entry")
+}
+
+fn row(source_id: &str, kind: &str, hours_ago: i64, failed: bool) -> SyncAuditEntry {
+ HostRun {
+ source_id: source_id.to_string(),
+ source_kind: kind.to_string(),
+ scope: source_id.to_string(),
+ error: failed.then(|| "offline".to_string()),
+ ..HostRun::default()
+ }
+ .into_entry(now() - chrono::Duration::hours(hours_ago))
+}
+
+fn ids(due: &[&MemorySourceEntry]) -> Vec<String> {
+ due.iter().map(|source| source.id.clone()).collect()
+}
+
+#[test]
+fn the_cadence_is_a_day_at_least_and_zero_is_manual_only() {
+ assert_eq!(effective_interval_secs(None), Some(DAY));
+ assert_eq!(effective_interval_secs(Some(0)), None);
+ assert_eq!(effective_interval_secs(Some(3_600)), Some(DAY));
+ assert_eq!(effective_interval_secs(Some(2 * DAY)), Some(2 * DAY));
+}
+
+#[test]
+fn only_enabled_local_sources_are_scheduled() {
+ let sources = vec![
+ source("notes", "folder", true),
+ source("repo", "github_repo", true),
+ source("feed", "rss_feed", true),
+ source("page", "web_page", true),
+ source("off", "folder", false),
+ source("mail", "composio", true),
+ source("chats", "conversation", true),
+ source("search", "twitter_query", true),
+ ];
+ let due = due_sources(&sources, DAY, &HashMap::new(), Some(&HashMap::new()), now());
+ assert_eq!(ids(&due), ["notes", "repo", "feed", "page"]);
+}
+
+/// The run log times a source across restarts: a recent success waits, an old
+/// one or none at all is due, and a failure does not count as a run.
+#[test]
+fn the_run_log_decides_what_is_due_after_a_restart() {
+ let sources = vec![
+ source("fresh", "folder", true),
+ source("stale", "folder", true),
+ source("failing", "folder", true),
+ source("never", "folder", true),
+ ];
+ let history = last_success_by_source(&[
+ row("fresh", "folder", 2, false),
+ row("stale", "folder", 30, false),
+ row("stale", "folder", 26, false),
+ row("failing", "folder", 1, true),
+ row("mail", "composio", 1, false),
+ ]);
+ assert!(!history.contains_key("failing"), "a failure is not a run");
+ assert!(
+ !history.contains_key("mail"),
+ "connectors are not timed here"
+ );
+ assert_eq!(
+ history["stale"],
+ now() - chrono::Duration::hours(26),
+ "the newest success wins"
+ );
+ let due = due_sources(&sources, DAY, &HashMap::new(), Some(&history), now());
+ assert_eq!(ids(&due), ["stale", "failing", "never"]);
+}
+
+/// This process's own runs time a source before the log does, and without a
+/// readable log only those can be timed at all.
+#[test]
+fn this_process_times_what_it_ran() {
+ let sources = vec![
+ source("ran", "folder", true),
+ source("unknown", "folder", true),
+ ];
+ let just_now = HashMap::from([("ran".to_string(), Duration::from_secs(60))]);
+ let long_ago = HashMap::from([("ran".to_string(), now() - chrono::Duration::days(9))]);
+ assert!(
+ due_sources(&sources, DAY, &just_now, Some(&long_ago), now())
+ .iter()
+ .all(|source| source.id != "ran"),
+ "a run in this process is newer than the log says"
+ );
+ let due = due_sources(&sources, DAY, &just_now, None, now());
+ assert!(due.is_empty(), "without the log, an untimed source waits");
+
+ let yesterday = HashMap::from([("ran".to_string(), Duration::from_secs(DAY + 60))]);
+ assert_eq!(
+ ids(&due_sources(&sources, DAY, &yesterday, None, now())),
+ ["ran"]
+ );
+}
+
+/// A log stamped in the future, from a clock that moved, reads as just run.
+#[test]
+fn a_run_stamped_in_the_future_is_not_due() {
+ let sources = vec![source("skewed", "folder", true)];
+ let history = HashMap::from([("skewed".to_string(), now() + chrono::Duration::hours(3))]);
+ assert!(due_sources(&sources, DAY, &HashMap::new(), Some(&history), now()).is_empty());
+}
diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync.rs b/crates/openhuman-core/src/memory/sources/hosted_sync.rs
new file mode 100644
index 0000000000..170ab81a61
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/hosted_sync.rs
@@ -0,0 +1,219 @@
+//! Local sources the host syncs into a driver's source sink.
+//!
+//! The embedded engine runs its own pipeline behind `MemorySourceSync`: it
+//! reads a folder, a repository, a feed or a page, tracks what changed, and
+//! ingests it. Hosted memory runs none — it keeps what it is sent through its
+//! source sink — so for a driver that serves the sink but not the pipeline
+//! ([`host_synced`]), the host reads the source itself and sends the items.
+//! The Sync button, Apply all and the periodic loop all come here for such a
+//! driver.
+//!
+//! # What a run does
+//!
+//! It lists the source's items with the source's reader, keeps the newest
+//! `max_items` and none older than `sync_depth_days`, reads each one, and hands
+//! them to `accept_source_items` in batches. The sink skips an item it already
+//! holds unchanged, so a run over an unchanged folder writes nothing, and a
+//! changed item replaces its old version. `max_tokens_per_sync` stops the run
+//! once the text read would pass it, at about four characters a token, and the
+//! run reports more pending.
+//!
+//! # What it does not do
+//!
+//! An item removed from the source stays in memory: the sink forgets a whole
+//! source, never one item by its id. Removing the source forgets everything it
+//! synced.
+
+use tinymemory_sources::types::ContentType;
+
+use crate::config::Config;
+use crate::memory::api::error::MemoryError;
+use crate::memory::api::provider::sync::SyncRunOutcome;
+use crate::memory::api::provider::types::SourceItem as SinkItem;
+use crate::memory::api::provider::{MemoryProvider, MemorySourceSink};
+use crate::memory::api::types::MemoryTaint;
+use crate::memory::sources::readers::{folder, github, rss, web_page, SourceReader};
+use crate::memory::sources::types::{MemorySourceEntry, SourceItem, SourceKind};
+
+/// Items handed to the sink in one call.
+const BATCH: usize = 25;
+
+/// Characters a token is counted as, for `max_tokens_per_sync`.
+const CHARS_PER_TOKEN: u64 = 4;
+
+/// Whether the host syncs local sources for `provider`: it keeps what it is
+/// sent, and runs no source pipeline of its own.
+pub(crate) fn host_synced(provider: &dyn MemoryProvider) -> bool {
+ provider.as_source_sync().is_none() && provider.as_sources().is_some()
+}
+
+/// Whether the host syncs sources of `kind`. Connector sources go through the
+/// connector, and conversations and X queries have no host reader that feeds a
+/// sink.
+pub(crate) fn serves(kind: &SourceKind) -> bool {
+ matches!(
+ kind,
+ SourceKind::Folder | SourceKind::GithubRepo | SourceKind::RssFeed | SourceKind::WebPage
+ )
+}
+
+/// The reader for `kind`, built here rather than taken from `reader_for`: a
+/// run may come from the periodic loop as well as a user's request, and the
+/// network readers are handed out only for the kinds a user added as sources
+/// to be synced on their schedule.
+fn reader(kind: &SourceKind) -> Option<Box<dyn SourceReader>> {
+ match kind {
+ SourceKind::Folder => Some(Box::new(folder::FolderReader)),
+ SourceKind::GithubRepo => Some(Box::new(github::GithubReader)),
+ SourceKind::RssFeed => Some(Box::new(rss::RssReader::new())),
+ SourceKind::WebPage => Some(Box::new(web_page::WebPageReader)),
+ _ => None,
+ }
+}
+
+/// A local folder is the user's own material; anything fetched is not.
+fn taint_of(kind: &SourceKind) -> MemoryTaint {
+ if *kind == SourceKind::Folder {
+ MemoryTaint::Internal
+ } else {
+ MemoryTaint::ExternalSync
+ }
+}
+
+fn mime_of(content_type: &ContentType) -> &'static str {
+ match content_type {
+ ContentType::Markdown => "text/markdown",
+ ContentType::Html => "text/html",
+ ContentType::Plaintext => "text/plain",
+ }
+}
+
+/// The items a run reads: none older than `sync_depth_days`, newest first, at
+/// most `max_items`.
+fn chosen(entry: &MemorySourceEntry, mut items: Vec<SourceItem>, now_ms: i64) -> Vec<SourceItem> {
+ if let Some(days) = entry.sync_depth_days.filter(|days| *days > 0) {
+ let floor = now_ms - i64::from(days) * 86_400_000;
+ items.retain(|item| item.updated_at_ms.is_none_or(|at| at >= floor));
+ }
+ items.sort_by_key(|item| std::cmp::Reverse(item.updated_at_ms));
+ if let Some(cap) = entry.max_items {
+ items.truncate(cap as usize);
+ }
+ items
+}
+
+/// Syncs `entry` into `sink` once.
+///
+/// # Errors
+///
+/// [`MemoryError::Unsupported`] for a kind the host does not sync;
+/// [`MemoryError::Backend`] when the source cannot be listed; the sink's own
+/// error when a batch is refused. An item that cannot be read is skipped and
+/// counted in the outcome's note.
+pub(crate) async fn run(
+ config: &Config,
+ entry: &MemorySourceEntry,
+ sink: &dyn MemorySourceSink,
+) -> Result<SyncRunOutcome, MemoryError> {
+ let Some(reader) = reader(&entry.kind) else {
+ return Err(MemoryError::unsupported_raw(format!(
+ "host sync of {} sources",
+ entry.kind.as_str()
+ )));
+ };
+ let listed = reader
+ .list_items(entry, config)
+ .await
+ .map_err(|error| MemoryError::Backend(format!("listing source '{}': {error}", entry.id)))?;
+ let total = listed.len();
+ let items = chosen(entry, listed, chrono::Utc::now().timestamp_millis());
+ tracing::debug!(
+ source_id = %entry.id,
+ kind = entry.kind.as_str(),
+ listed = total,
+ chosen = items.len(),
+ "[memory_sources:hosted_sync] run starting"
+ );
+ let budget = entry
+ .max_tokens_per_sync
+ .map(|tokens| tokens.saturating_mul(CHARS_PER_TOKEN));
+ let mut spent: u64 = 0;
+ let mut unreadable = 0usize;
+ let mut more_pending = false;
+ let mut batch: Vec<SinkItem> = Vec::with_capacity(BATCH);
+ let mut outcome = SyncRunOutcome::default();
+ for item in items {
+ let content = match reader.read_item(entry, &item.id, config).await {
+ Ok(content) => content,
+ Err(error) => {
+ unreadable += 1;
+ tracing::warn!(
+ source_id = %entry.id,
+ item_id = %item.id,
+ "[memory_sources:hosted_sync] item could not be read: {error}"
+ );
+ continue;
+ }
+ };
+ if content.body.trim().is_empty() {
+ continue;
+ }
+ let size = content.body.len() as u64;
+ if budget.is_some_and(|budget| spent + size > budget) {
+ more_pending = true;
+ break;
+ }
+ spent += size;
+ batch.push(SinkItem {
+ item_id: item.id,
+ title: if content.title.is_empty() {
+ item.title
+ } else {
+ content.title
+ },
+ content: content.body,
+ mime: Some(mime_of(&content.content_type).to_string()),
+ url: content
+ .metadata
+ .get("url")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string),
+ updated_at_ms: item.updated_at_ms,
+ tags: Vec::new(),
+ });
+ if batch.len() == BATCH {
+ outcome.records_ingested += send(entry, sink, std::mem::take(&mut batch)).await?;
+ }
+ }
+ if !batch.is_empty() {
+ outcome.records_ingested += send(entry, sink, batch).await?;
+ }
+ outcome.more_pending = more_pending;
+ if unreadable > 0 {
+ outcome.note = Some(format!("{unreadable} item(s) could not be read"));
+ }
+ tracing::debug!(
+ source_id = %entry.id,
+ written = outcome.records_ingested,
+ unreadable,
+ more_pending,
+ "[memory_sources:hosted_sync] run finished"
+ );
+ Ok(outcome)
+}
+
+/// One batch into the sink; answers how many items it wrote.
+async fn send(
+ entry: &MemorySourceEntry,
+ sink: &dyn MemorySourceSink,
+ batch: Vec<SinkItem>,
+) -> Result<u32, MemoryError> {
+ let accepted = sink
+ .accept_source_items(&entry.id, entry.kind.as_str(), batch, taint_of(&entry.kind))
+ .await?;
+ Ok(accepted.written)
+}
+
+#[cfg(test)]
+#[path = "hosted_sync_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs
new file mode 100644
index 0000000000..365673c2ec
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs
@@ -0,0 +1,199 @@
+//! The host's sync of local sources into a driver's sink: which items a run
+//! reads, what it sends, and the budgets it keeps.
+
+use std::sync::Mutex;
+
+use async_trait::async_trait;
+
+use super::*;
+use crate::memory::api::provider::types::IngestOutcome;
+
+/// One `accept_source_items` call: source id, source kind, items, taint.
+type Batch = (String, String, Vec<SinkItem>, MemoryTaint);
+
+/// A sink that records every batch and writes each item it is handed.
+#[derive(Default)]
+struct RecordingSink {
+ batches: Mutex<Vec<Batch>>,
+}
+
+impl RecordingSink {
+ fn items(&self) -> Vec<SinkItem> {
+ self.batches
+ .lock()
+ .expect("batches")
+ .iter()
+ .flat_map(|(_, _, items, _)| items.clone())
+ .collect()
+ }
+}
+
+#[async_trait]
+impl MemorySourceSink for RecordingSink {
+ async fn accept_source_items(
+ &self,
+ source_id: &str,
+ source_kind: &str,
+ items: Vec<SinkItem>,
+ taint: MemoryTaint,
+ ) -> Result<IngestOutcome, MemoryError> {
+ let written = items.len() as u32;
+ self.batches.lock().expect("batches").push((
+ source_id.to_string(),
+ source_kind.to_string(),
+ items,
+ taint,
+ ));
+ Ok(IngestOutcome {
+ written,
+ ..IngestOutcome::default()
+ })
+ }
+
+ async fn forget_source(&self, _source_id: &str) -> Result<u64, MemoryError> {
+ Ok(0)
+ }
+}
+
+fn folder_entry(path: &std::path::Path) -> MemorySourceEntry {
+ serde_json::from_value(serde_json::json!({
+ "id": "notes",
+ "kind": "folder",
+ "label": "Notes",
+ "enabled": true,
+ "path": path.to_string_lossy(),
+ }))
+ .expect("a folder source")
+}
+
+fn listed(id: &str, updated_at_ms: Option<i64>) -> SourceItem {
+ SourceItem {
+ id: id.to_string(),
+ title: id.to_string(),
+ updated_at_ms,
+ }
+}
+
+fn config(dir: &std::path::Path) -> Config {
+ Config {
+ workspace_dir: dir.to_path_buf(),
+ ..Config::default()
+ }
+}
+
+#[test]
+fn the_host_syncs_local_kinds_only() {
+ for kind in [
+ SourceKind::Folder,
+ SourceKind::GithubRepo,
+ SourceKind::RssFeed,
+ SourceKind::WebPage,
+ ] {
+ assert!(serves(&kind), "{kind:?}");
+ }
+ for kind in [
+ SourceKind::Composio,
+ SourceKind::Conversation,
+ SourceKind::TwitterQuery,
+ ] {
+ assert!(!serves(&kind), "{kind:?}");
+ }
+ assert_eq!(taint_of(&SourceKind::Folder), MemoryTaint::Internal);
+ assert_eq!(taint_of(&SourceKind::RssFeed), MemoryTaint::ExternalSync);
+}
+
+#[test]
+fn a_run_reads_the_newest_items_within_its_depth_and_cap() {
+ let day = 86_400_000;
+ let now = 100 * day;
+ let mut entry = folder_entry(std::path::Path::new("."));
+ let items = || {
+ vec![
+ listed("old", Some(now - 40 * day)),
+ listed("new", Some(now - day)),
+ listed("undated", None),
+ listed("mid", Some(now - 10 * day)),
+ ]
+ };
+ let ids = |items: Vec<SourceItem>| items.into_iter().map(|i| i.id).collect::<Vec<_>>();
+ assert_eq!(
+ ids(chosen(&entry, items(), now)),
+ ["new", "mid", "old", "undated"]
+ );
+ entry.sync_depth_days = Some(30);
+ assert_eq!(
+ ids(chosen(&entry, items(), now)),
+ ["new", "mid", "undated"],
+ "an item with no date is kept"
+ );
+ entry.max_items = Some(1);
+ assert_eq!(ids(chosen(&entry, items(), now)), ["new"]);
+}
+
+#[tokio::test]
+async fn a_folder_is_read_and_sent_to_the_sink() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = dir.path().join("notes");
+ std::fs::create_dir_all(&folder).expect("folder");
+ std::fs::write(folder.join("a.md"), "# Tea\n\nOolong is best.").expect("a");
+ std::fs::write(folder.join("b.md"), " ").expect("blank");
+ std::fs::write(folder.join("skip.txt"), "not markdown").expect("txt");
+ let sink = RecordingSink::default();
+ let outcome = run(&config(dir.path()), &folder_entry(&folder), &sink)
+ .await
+ .expect("run");
+ assert_eq!(outcome.records_ingested, 1);
+ assert!(!outcome.more_pending);
+ let batches = sink.batches.lock().expect("batches");
+ assert_eq!(batches.len(), 1);
+ let (source_id, kind, items, taint) = &batches[0];
+ assert_eq!((source_id.as_str(), kind.as_str()), ("notes", "folder"));
+ assert_eq!(*taint, MemoryTaint::Internal);
+ assert_eq!(items.len(), 1, "a blank file is not sent");
+ assert!(items[0].content.contains("Oolong is best."));
+ assert_eq!(items[0].mime.as_deref(), Some("text/markdown"));
+}
+
+#[tokio::test]
+async fn a_token_budget_stops_the_run_with_more_pending() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = dir.path().join("notes");
+ std::fs::create_dir_all(&folder).expect("folder");
+ for name in ["a", "b", "c"] {
+ std::fs::write(folder.join(format!("{name}.md")), "x".repeat(400)).expect("file");
+ }
+ let mut entry = folder_entry(&folder);
+ entry.max_tokens_per_sync = Some(150);
+ let sink = RecordingSink::default();
+ let outcome = run(&config(dir.path()), &entry, &sink).await.expect("run");
+ assert_eq!(
+ sink.items().len(),
+ 1,
+ "600 characters fit one 400-character file"
+ );
+ assert!(outcome.more_pending);
+}
+
+#[tokio::test]
+async fn a_missing_folder_or_unserved_kind_fails_the_run() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let sink = RecordingSink::default();
+ let missing = run(
+ &config(dir.path()),
+ &folder_entry(&dir.path().join("absent")),
+ &sink,
+ )
+ .await;
+ assert!(
+ matches!(missing, Err(MemoryError::Backend(_))),
+ "{missing:?}"
+ );
+ let mut chats = folder_entry(dir.path());
+ chats.kind = SourceKind::Conversation;
+ let refused = run(&config(dir.path()), &chats, &sink).await;
+ assert!(
+ matches!(refused, Err(MemoryError::Unsupported { .. })),
+ "{refused:?}"
+ );
+ assert!(sink.items().is_empty());
+}
diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rs
index 826d779dfd..9b2c49b491 100644
--- a/crates/openhuman-core/src/memory/sources/mod.rs
+++ b/crates/openhuman-core/src/memory/sources/mod.rs
@@ -104,6 +104,13 @@ pub mod reconcile;
// the driver's log by the history RPCs (openhuman#6257).
pub(crate) mod run_history;
+// Local sources the host reads and sends through a driver's source sink, for a
+// driver that runs no source pipeline of its own (hosted memory), and the loop
+// that schedules them.
+pub(crate) mod hosted_periodic;
+pub(crate) mod hosted_sync;
+pub use hosted_periodic::start_hosted_periodic_sync;
+
// The controller aggregators this domain's RPC surface defines. Aliased
// exactly as the pre-extraction module exported them.
pub use schemas::{
diff --git a/crates/openhuman-core/src/memory/sources/rpc.rs b/crates/openhuman-core/src/memory/sources/rpc.rs
index 648842e40c..86a177abe0 100644
--- a/crates/openhuman-core/src/memory/sources/rpc.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc.rs
@@ -60,7 +60,7 @@
mod apply_all;
mod coding_sessions;
mod cost_reporting;
-mod driver_run;
+pub(in crate::memory::sources) mod driver_run;
mod registry_crud;
mod source_sync;
mod status_toolkits;
diff --git a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs
index 899c5bbe75..8ef66bd410 100644
--- a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs
@@ -108,6 +108,12 @@ pub async fn apply_all_in_rpc() -> Result<Outcome<AllInResponse>, String> {
// the family reports the refusal as its own per-source error, which is
// exactly what this sweep aggregates.
let source_sync = binding.provider().as_source_sync();
+ // A driver that keeps what it is sent and runs no source pipeline (hosted
+ // memory) is synced by the host through its sink instead.
+ let host_sink = binding
+ .provider()
+ .as_sources()
+ .filter(|_| crate::memory::sources::hosted_sync::host_synced(binding.provider().as_ref()));
let config_ref = &config;
let driver_id = binding.driver_id();
@@ -134,18 +140,35 @@ pub async fn apply_all_in_rpc() -> Result<Outcome<AllInResponse>, String> {
.await
.map(|_| ()),
SyncDispatch::Driver => {
+ let publish = super::driver_run::bus_stage_publisher(
+ super::driver_run::MANUAL,
+ &source.id,
+ source.kind.as_str(),
+ );
+ // The same start, finish and history row as the Sync button
+ // (openhuman#6257), whichever side runs the sync.
+ if let Some(sink) = host_sink {
+ return super::driver_run::run_recorded(
+ config_ref,
+ &source.id,
+ Some(&source),
+ || crate::memory::sources::hosted_sync::run(config_ref, &source, sink),
+ |error| error.to_string(),
+ publish,
+ )
+ .await
+ .map(|_| ());
+ }
let sync = source_sync.ok_or_else(|| {
format!("the bound memory driver '{driver_id}' does not serve source sync")
})?;
- // The same start, finish and history row as the Sync button
- // (openhuman#6257).
super::driver_run::run_recorded(
config_ref,
&source.id,
Some(&source),
|| sync.run_source_sync(&source.id),
|error| error.to_string(),
- super::driver_run::bus_stage_publisher(&source.id, source.kind.as_str()),
+ publish,
)
.await
.map(|_| ())
diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs
index df62a67529..f1d34a8928 100644
--- a/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs
@@ -21,7 +21,11 @@ use crate::memory::sources::types::MemorySourceEntry;
/// The trigger a user-started driver run reports under — the word the engine's
/// `sync_source` used for the Sync button.
-const TRIGGER: &str = "manual";
+pub(in crate::memory::sources) const MANUAL: &str = "manual";
+
+/// The trigger a scheduled driver run reports under — the word the periodic
+/// Composio loop uses for its runs.
+pub(in crate::memory::sources) const PERIODIC: &str = "periodic";
/// The scope a history row names for `entry`: the rule the engine's periodic
/// writer applies (URL, then toolkit, then the id), so a source's manual and
@@ -34,15 +38,16 @@ pub(super) fn history_scope(entry: &MemorySourceEntry) -> String {
.unwrap_or_else(|| entry.id.clone())
}
-/// The stage event for one driver-backed source.
+/// The stage event for one driver-backed source, under `trigger`.
pub(super) fn stage_event(
+ trigger: &str,
source_id: &str,
kind: &str,
stage: &str,
detail: Option<String>,
) -> DomainEvent {
DomainEvent::MemorySyncStageChanged {
- trigger: TRIGGER.to_string(),
+ trigger: trigger.to_string(),
stage: stage.to_string(),
provider: Some(kind.to_string()),
// The row id here too, as the engine's `sync_source` sent it: the app
@@ -54,12 +59,16 @@ pub(super) fn stage_event(
}
}
-/// A stage publisher for one source, on the process bus.
-pub(super) fn bus_stage_publisher(source_id: &str, kind: &str) -> impl Fn(&str, Option<String>) {
+/// A stage publisher for one source, on the process bus, under `trigger`.
+pub(in crate::memory::sources) fn bus_stage_publisher(
+ trigger: &'static str,
+ source_id: &str,
+ kind: &str,
+) -> impl Fn(&str, Option<String>) {
let source_id = source_id.to_string();
let kind = kind.to_string();
move |stage, detail| {
- crate::core::bus::BUS.publish(stage_event(&source_id, &kind, stage, detail));
+ crate::core::bus::BUS.publish(stage_event(trigger, &source_id, &kind, stage, detail));
}
}
@@ -73,7 +82,7 @@ pub(super) fn bus_stage_publisher(source_id: &str, kind: &str) -> impl Fn(&str,
/// The row is written before the terminal stage is published, on purpose: the
/// history panel refetches when that stage arrives, and a row written after it
/// would miss that read.
-pub(super) async fn run_recorded<Run, Fut, Describe, Publish>(
+pub(in crate::memory::sources) async fn run_recorded<Run, Fut, Describe, Publish>(
config: &Config,
source_id: &str,
entry: Option<&MemorySourceEntry>,
diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs
index a2b806f2fa..5dcf2fb3a7 100644
--- a/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs
@@ -196,6 +196,7 @@ fn the_history_scope_prefers_the_url_then_the_toolkit_then_the_id() {
#[test]
fn the_stage_event_names_the_source_for_the_row_indicator() {
match stage_event(
+ MANUAL,
"src_ev",
"folder",
"completed",
diff --git a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs
index 2435953ed2..a6fd5837dc 100644
--- a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs
@@ -155,30 +155,57 @@ pub async fn sync_rpc(req: SyncRequest) -> Result<Outcome<SyncResponse>, String>
));
}
}
- // Resolved after the composio branch on purpose: the connector-backed
- // dispatch above needs `as_sources`, not `as_source_sync`, and a driver
- // serving the former without the latter must not fail a composio sync on
- // a capability it never uses (review finding on #5932).
- let sync = binding.provider().as_source_sync().ok_or_else(|| {
- format!(
- "the bound memory driver '{}' does not serve source sync",
- binding.driver_id()
- )
- })?;
- // `run_source_sync` reports neither the run's start nor its finish and
- // writes no history row; `run_recorded` owns all three (openhuman#6257).
let kind = host_entry
.as_ref()
.map_or("unknown", |entry| entry.kind.as_str());
- super::driver_run::run_recorded(
- &config,
- &req.source_id,
- host_entry.as_ref(),
- || sync.run_source_sync(&req.source_id),
- |error| describe_source_sync_failure(&req.source_id, host_entry.is_some(), error),
- super::driver_run::bus_stage_publisher(&req.source_id, kind),
- )
- .await?;
+ let publish =
+ super::driver_run::bus_stage_publisher(super::driver_run::MANUAL, &req.source_id, kind);
+ let provider = binding.provider();
+ if crate::memory::sources::hosted_sync::host_synced(provider.as_ref()) {
+ // A driver that keeps what it is sent and runs no source pipeline of
+ // its own (hosted memory): the host reads the source and sends the
+ // items through the driver's sink, recorded like any other run.
+ let entry = host_entry
+ .as_ref()
+ .ok_or_else(|| format!("unknown memory source '{}'", req.source_id))?;
+ let sink = provider.as_sources().ok_or_else(|| {
+ format!(
+ "the bound memory driver '{}' does not accept source items",
+ binding.driver_id()
+ )
+ })?;
+ super::driver_run::run_recorded(
+ &config,
+ &req.source_id,
+ Some(entry),
+ || crate::memory::sources::hosted_sync::run(&config, entry, sink),
+ |error| error.to_string(),
+ publish,
+ )
+ .await?;
+ } else {
+ // Resolved after the composio branch on purpose: the connector-backed
+ // dispatch above needs `as_sources`, not `as_source_sync`, and a driver
+ // serving the former without the latter must not fail a composio sync
+ // on a capability it never uses (review finding on #5932).
+ let sync = provider.as_source_sync().ok_or_else(|| {
+ format!(
+ "the bound memory driver '{}' does not serve source sync",
+ binding.driver_id()
+ )
+ })?;
+ // `run_source_sync` reports neither the run's start nor its finish and
+ // writes no history row; `run_recorded` owns all three (openhuman#6257).
+ super::driver_run::run_recorded(
+ &config,
+ &req.source_id,
+ host_entry.as_ref(),
+ || sync.run_source_sync(&req.source_id),
+ |error| describe_source_sync_failure(&req.source_id, host_entry.is_some(), error),
+ publish,
+ )
+ .await?;
+ }
Ok(Outcome::new(
SyncResponse {