Skip to content

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

Merge upstream/main into storage-event-agents: one agent registry

Steven Enamakel7e2792e00bb3
diff --cc crates/openhuman-core/src/core/runtime/agent_scope.rs
index 0000000000,4f1e1a934f..b10b551b8c
mode 000000,100644..100644
--- a/crates/openhuman-core/src/core/runtime/agent_scope.rs
+++ b/crates/openhuman-core/src/core/runtime/agent_scope.rs
@@@ -1,0 -1,175 +1,181 @@@
+ //! Per-agent state owned by a [`CoreContext`].
+ //!
+ //! An embedded agent runs every turn under its own derived context
+ //! ([`CoreContext::derive_with`]). Core state that must not be shared between
+ //! agents hangs off that context instead of a process static:
+ //!
+ //! - [`AgentScopedState`]: a lazily populated, type-keyed slot map. Each
+ //! derived agent context owns one; the booted default context owns its own,
+ //! so the app and CLI keep a single instance as before.
+ //! - [`AgentContextRegistry`]: the live agent contexts by agent id, so work
+ //! that starts outside a turn (cron) can run under the agent that owns it.
+ //! - [`agent_scope_dir`]: where an agent's workspace-scoped stores live.
+
+ use std::any::{Any, TypeId};
+ use std::collections::HashMap;
+ use std::path::PathBuf;
+ use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock, Weak};
+
+ use super::CoreContext;
+
+ /// Type-keyed state slots owned by one context.
+ ///
+ /// A slot is created on first use with `T::default()` and lives as long as
+ /// the context that owns it. Two contexts never share a slot.
+ #[derive(Default)]
+ pub struct AgentScopedState {
+ slots: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
+ }
+
+ impl AgentScopedState {
+ /// The slot of type `T`, created on first use.
+ pub fn slot<T: Default + Send + Sync + 'static>(&self) -> Arc<T> {
+ let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
+ let entry = slots
+ .entry(TypeId::of::<T>())
+ .or_insert_with(|| Arc::new(T::default()) as Arc<dyn Any + Send + Sync>);
+ Arc::clone(entry)
+ .downcast::<T>()
+ .unwrap_or_else(|_| unreachable!("a slot is keyed by its own TypeId"))
+ }
+
+ /// Number of slots created so far.
+ pub fn len(&self) -> usize {
+ self.slots
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .len()
+ }
+
+ /// Whether no slot has been created yet.
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// Drops every slot.
+ pub fn clear(&self) {
+ self.slots
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clear();
+ }
+ }
+
+ impl std::fmt::Debug for AgentScopedState {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("AgentScopedState")
+ .field("slots", &self.len())
+ .finish()
+ }
+ }
+
+ /// Slots used when no context exists at all.
+ static UNSCOPED: LazyLock<AgentScopedState> = LazyLock::new(AgentScopedState::default);
+
+ /// The ambient context's slot of type `T`, or the unscoped one when no
+ /// context exists.
+ pub fn current_slot<T: Default + Send + Sync + 'static>() -> Arc<T> {
+ match CoreContext::current() {
+ Some(ctx) => ctx.agent_state().slot::<T>(),
+ None => UNSCOPED.slot::<T>(),
+ }
+ }
+
+ static AGENT_CONTEXTS: LazyLock<RwLock<HashMap<String, Weak<CoreContext>>>> =
+ LazyLock::new(|| RwLock::new(HashMap::new()));
+
+ /// The process's live agent contexts, by agent id.
+ ///
+ /// Holds weak references: registering a context does not keep it alive, and a
+ /// dropped agent's entry resolves to `None` even before it is deregistered.
+ pub struct AgentContextRegistry;
+
+ impl AgentContextRegistry {
+ /// Records `ctx` as the context of `agent_id`, replacing any dead entry.
+ pub fn register(agent_id: &str, ctx: &Arc<CoreContext>) {
- let mut map = AGENT_CONTEXTS
- .write()
- .unwrap_or_else(PoisonError::into_inner);
- map.retain(|_, weak| weak.strong_count() > 0);
- map.insert(agent_id.to_string(), Arc::downgrade(ctx));
- log::debug!(
- "[core-context] agent context registered agent={agent_id} live={}",
- map.len()
- );
++ {
++ let mut map = AGENT_CONTEXTS
++ .write()
++ .unwrap_or_else(PoisonError::into_inner);
++ map.retain(|_, weak| weak.strong_count() > 0);
++ map.insert(agent_id.to_string(), Arc::downgrade(ctx));
++ log::debug!(
++ "[core-context] agent context registered agent={agent_id} live={}",
++ map.len()
++ );
++ }
++ // With a storage backend, remember the agent there so a restarted
++ // process still visits its records (`crate::storage::agents`). After
++ // the lock is released: recording waits on the storage bridge.
++ crate::storage::agents::record(agent_id);
+ }
+
+ /// Removes `agent_id`'s entry when it still points at `ctx`.
+ pub fn deregister(agent_id: &str, ctx: &Arc<CoreContext>) -> bool {
+ let mut map = AGENT_CONTEXTS
+ .write()
+ .unwrap_or_else(PoisonError::into_inner);
+ let owned = map
+ .get(agent_id)
+ .is_some_and(|weak| std::ptr::eq(weak.as_ptr(), Arc::as_ptr(ctx)));
+ if owned {
+ map.remove(agent_id);
+ log::debug!("[core-context] agent context deregistered agent={agent_id}");
+ }
+ owned
+ }
+
+ /// The live context of `agent_id`, if that agent is still alive.
+ pub fn get(agent_id: &str) -> Option<Arc<CoreContext>> {
+ AGENT_CONTEXTS
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .get(agent_id)
+ .and_then(Weak::upgrade)
+ }
+
+ /// Every live agent context, sorted by agent id.
+ pub fn live() -> Vec<(String, Arc<CoreContext>)> {
+ let mut live: Vec<(String, Arc<CoreContext>)> = AGENT_CONTEXTS
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .iter()
+ .filter_map(|(id, weak)| weak.upgrade().map(|ctx| (id.clone(), ctx)))
+ .collect();
+ live.sort_by(|a, b| a.0.cmp(&b.0));
+ live
+ }
+ }
+
+ /// The directory an agent's workspace-scoped stores live under:
+ /// `<workspace>/agents/<id>` under a context derived for an agent, else the
+ /// workspace itself.
+ pub fn agent_scope_dir(config: &crate::config::Config) -> PathBuf {
+ match CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned)) {
+ Some(agent_id) => config.workspace_dir.join("agents").join(agent_id),
+ None => config.workspace_dir.clone(),
+ }
+ }
+
+ /// The agent id of the ambient context, when it was derived for one.
+ pub fn current_agent_id() -> Option<String> {
+ CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned))
+ }
+
+ /// A context derived from `parent` for `agent_id`, for tests that need two
+ /// agents side by side.
+ #[cfg(test)]
+ pub(crate) fn test_agent_context(parent: &Arc<CoreContext>, agent_id: &str) -> Arc<CoreContext> {
+ parent.derive_with(
+ super::ContextOverlay::new(
+ crate::config::Config::default(),
+ super::DomainSet::kernel(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .session_agent(agent_id),
+ )
+ }
+
+ #[cfg(test)]
+ #[path = "agent_scope_tests.rs"]
+ mod tests;
diff --cc crates/openhuman-core/src/core/runtime/context.rs
index 5970b2d498,4bf3711273..77cf5e4651
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@@ -741,8 -692,13 +692,16 @@@ pub async fn init_stores(cfg: &crate::c
#[path = "context_turn_origin.rs"]
mod turn_origin_scope;
++#[path = "context_for_agent.rs"]
++mod for_agent_scope;
++
+ #[path = "context_agent.rs"]
+ mod agent_parts;
+
+ #[path = "context_overlay.rs"]
+ mod overlay;
+ pub use overlay::ContextOverlay;
+
#[cfg(test)]
#[path = "context_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/core/runtime/context_for_agent.rs
index 0000000000,0000000000..4b7f3bf075
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/context_for_agent.rs
@@@ -1,0 -1,0 +1,41 @@@
++use super::*;
++
++impl CoreContext {
++ /// This context, acting for `agent`: the same configuration, workspace
++ /// binding, domains and transport, with the session agent replaced.
++ ///
++ /// For background work that visits an agent's records when no live
++ /// context of that agent is at hand (`crate::storage::agents`): the agent
++ /// was registered by an earlier process, or its host dropped it. A live
++ /// agent context is always preferred, since it carries the agent's own
++ /// configuration, policy and tools.
++ pub fn for_agent(self: &Arc<Self>, agent: &str) -> Arc<CoreContext> {
++ let binding = self
++ .workspace_binding
++ .read()
++ .map(|handle| Arc::clone(&*handle))
++ .unwrap_or_else(|poisoned| Arc::clone(&*poisoned.into_inner()));
++ // The agent parts a derived context for `agent` would get: this
++ // context's policy, approval switch and definitions, and state slots
++ // of its own.
++ let mut overlay = ContextOverlay::new(
++ crate::config::Config::default(),
++ self.domains,
++ self.tool_groups.clone(),
++ )
++ .session_agent(agent);
++ let parts = self.agent.derive(&mut overlay);
++ Arc::new(CoreContext {
++ host_kind: self.host_kind,
++ workspace_binding: RwLock::new(binding),
++ domains: self.domains,
++ tool_groups: self.tool_groups.clone(),
++ embedder_config: self.embedder_config.clone(),
++ user_skill_roots: self.user_skill_roots,
++ backend_transport: self.backend_transport.clone(),
++ turn_origin: self.turn_origin.clone(),
++ session_agent: Some(agent.to_string()),
++ agent: parts,
++ })
++ }
++}
diff --cc crates/openhuman-core/src/cron/scheduler.rs
index ba27d2fa91,e0f6949fd9..8ef1cba300
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@@ -79,44 -98,46 +98,55 @@@ pub async fn run(config: Config) -> Res
}
}
- /// The same poll for every agent that keeps its jobs in its own storage scope
- /// (`crate::storage::agents`): a job an agent scheduled from its own turn
- /// lives there, and runs there — under that agent's context and, when the
- /// agent is live, its configuration. Only the `local` pass reports the
- /// scheduler's health tracker (`last_emitted_health`, shared with the `local`
- /// pass so a failure or recovery reported from an agent pass is seen by the
- /// next one); each agent pass authorizes its jobs with a policy built from
- /// that agent's own configuration.
- pub(crate) async fn tick_agents(config: &Config, last_emitted_health: &mut Option<bool>) {
- let health = std::sync::Mutex::new(*last_emitted_health);
- crate::storage::agents::for_each_agent("cron", || async {
- let mut steady = *health
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- tick_agent_scope(config, &mut steady).await;
- *health
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = steady;
- })
- .await;
- *last_emitted_health = health
- .into_inner()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
+ /// Runs the due jobs of every live embedded agent, each under that agent's
-/// own context: its config, provider route, policy and job database. An
-/// agent that is not live has no context to run under, so its jobs stay
-/// dormant until it is instantiated again.
++/// own context: its config, provider route, policy and job store. An agent
++/// that is not live has no context to run under — no host tools or prompt
++/// for its agent jobs — so its jobs stay dormant until it is instantiated
++/// again, including when a storage backend still records it
++/// (`crate::storage::agents`).
+ pub(crate) async fn tick_live_agents(dispatcher: &mut JobDispatcher) {
+ for (agent_id, ctx) in crate::core::runtime::AgentContextRegistry::live() {
+ let agent = agent_id.clone();
+ let dispatcher = &mut *dispatcher;
+ crate::core::runtime::CoreContext::scope(ctx, async move {
+ let config = match crate::config::ops::load_current_or_init().await {
+ Ok(config) => config,
+ Err(error) => {
+ tracing::debug!(agent = %agent, %error, "[cron:scheduler] agent config unavailable");
+ return;
+ }
+ };
- if !crate::cron::store::db_path(&config).exists() {
++ if !agent_jobs_may_exist(&config) {
+ return;
+ }
+ let jobs = match due_jobs(&config, Utc::now()) {
+ Ok(jobs) => jobs,
+ Err(error) => {
+ tracing::warn!(agent = %agent, "[cron:scheduler] agent poll db_error: {error}");
+ return;
+ }
+ };
+ if jobs.is_empty() {
+ return;
+ }
+ let Some(security) = crate::security::live_policy::effective() else {
+ tracing::warn!(agent = %agent, "[cron:scheduler] agent has no policy; jobs skipped");
+ return;
+ };
+ tracing::debug!(agent = %agent, due_count = jobs.len(), "[cron:scheduler] running agent jobs");
+ dispatcher.dispatch(&config, &security, jobs).await;
+ })
+ .await;
+ }
}
- /// One agent's pass: the poll under the current (agent) context, with that
- /// agent's configuration when it has one and a policy built from it.
- async fn tick_agent_scope(config: &Config, last_emitted_health: &mut Option<bool>) {
- let config = crate::core::runtime::CoreContext::current_embedder_config()
- .unwrap_or_else(|| config.clone());
- let security = Arc::new(SecurityPolicy::from_config(
- &config.autonomy,
- &config.workspace_dir,
- &config.action_dir,
- ));
- tick_once(&config, &security, last_emitted_health).await;
++/// Whether an agent can have jobs to poll: with a storage backend its jobs
++/// live in the backend under its scope (`crate::storage`), so there is always
++/// something to ask; without one, only once its own `jobs.db` exists.
++pub(crate) fn agent_jobs_may_exist(config: &Config) -> bool {
++ crate::storage::installed().is_some() || crate::cron::store::db_path(config).exists()
+}
+
/// Single poll cycle of the scheduler loop, extracted so tests can drive
/// it without owning `tokio::time::interval`.
///
diff --cc crates/openhuman-core/src/cron/scheduler_tests.rs
index 80184d947d,4aa6223ac0..012b0200b4
--- a/crates/openhuman-core/src/cron/scheduler_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_tests.rs
@@@ -313,25 -317,3 +317,19 @@@ async fn a_pipeline_reports_its_last_st
a failure and re-status every existing job with a pipeline in it: {output}"
);
}
+
+#[tokio::test]
- async fn an_agent_pass_polls_with_its_own_config_and_reports_health() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp).await;
- let mut health = None;
- tick_agent_scope(&config, &mut health).await;
- assert_eq!(health, Some(true), "a successful poll reports healthy");
- }
-
- #[tokio::test]
- async fn tick_agents_without_a_backend_leaves_the_health_tracker_alone() {
- // The lib test binary installs no storage backend, so no agent is visited.
++async fn without_a_backend_an_agent_needs_its_own_job_database() {
++ // The lib test binary installs no storage backend into the process slot.
+ if crate::storage::installed().is_some() {
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
- let mut health = Some(false);
- tick_agents(&config, &mut health).await;
- assert_eq!(health, Some(false));
++ let db = crate::cron::store::db_path(&config);
++ let _ = std::fs::remove_file(&db);
++ assert!(!agent_jobs_may_exist(&config));
++ std::fs::create_dir_all(db.parent().unwrap()).unwrap();
++ std::fs::write(&db, b"").unwrap();
++ assert!(agent_jobs_may_exist(&config));
+}
diff --cc crates/openhuman-core/src/flows/ops/run_management.rs
index 9c8a37592b,10be3a787c..7d7171a0ce
--- a/crates/openhuman-core/src/flows/ops/run_management.rs
+++ b/crates/openhuman-core/src/flows/ops/run_management.rs
@@@ -270,28 -270,6 +270,56 @@@ pub async fn sweep_expired_parked_runs(
/// resumable — only `pending_approval` is). Best-effort by construction: a store
/// error is logged and the sweep returns what it managed.
pub async fn sweep_orphaned_running_runs_on_boot(config: &Config) -> usize {
- // `local`, then every agent that keeps its runs in its own storage scope
- // (`crate::storage::agents`).
- //
- // On a backend other processes share (MongoDB), a `running` row below the
- // boot floor can belong to a run another replica is still driving, and
- // sweeping it would drop that run's checkpoint — so the agent scopes are
- // left alone there, as the agent run reaper does.
- if crate::storage::installed_is_shared() && !crate::core::runtime::mode::is_saas() {
- tracing::info!(target: "flows", "[flows] boot sweep: agent scopes skipped, the storage backend is shared");
- return sweep_orphaned_running_runs_in_scope(config).await;
++ match boot_sweep_plan(
++ crate::storage::installed_is_shared(),
++ crate::core::runtime::mode::is_saas(),
++ ) {
++ BootSweepPlan::Nothing => {
++ tracing::info!(target: "flows", "[flows] boot sweep: skipped, the storage backend is shared");
++ 0
++ }
++ BootSweepPlan::LocalOnly => {
++ tracing::info!(target: "flows", "[flows] boot sweep: agent scopes skipped, the storage backend is shared");
++ sweep_orphaned_running_runs_in_scope(config).await
++ }
++ BootSweepPlan::EveryScope => {
++ crate::storage::agents::for_each_scope("flows boot sweep", || {
++ sweep_orphaned_running_runs_in_scope(config)
++ })
++ .await
++ .into_iter()
++ .map(|(_, swept)| swept)
++ .sum()
++ }
++ }
++}
++
++/// Which scopes the boot sweep reconciles.
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++pub(crate) enum BootSweepPlan {
++ /// `local`, then every agent scope (`crate::storage::agents`).
++ EveryScope,
++ /// `local` only.
++ LocalOnly,
++ /// No scope.
++ Nothing,
++}
++
++/// The boot sweep's scopes. On a backend other processes share (MongoDB) a
++/// `running` row below the boot floor can belong to a run another replica is
++/// still driving, and sweeping it would drop that run's checkpoint, so the
++/// agent scopes are left alone there, as the agent run reaper does — and in
++/// SaaS mode, where every scope is an agent's, nothing is swept.
++pub(crate) fn boot_sweep_plan(shared: bool, saas: bool) -> BootSweepPlan {
++ match (shared, saas) {
++ (false, _) => BootSweepPlan::EveryScope,
++ (true, false) => BootSweepPlan::LocalOnly,
++ (true, true) => BootSweepPlan::Nothing,
+ }
- crate::storage::agents::for_each_scope("flows boot sweep", || {
- sweep_orphaned_running_runs_in_scope(config)
- })
- .await
- .into_iter()
- .map(|(_, swept)| swept)
- .sum()
+}
+
+/// [`sweep_orphaned_running_runs_on_boot`] for the current storage scope.
+async fn sweep_orphaned_running_runs_in_scope(config: &Config) -> usize {
let now_str = Utc::now().to_rfc3339();
const REASON: &str =
"Run interrupted by an app restart — no live run was executing this row after boot.";
diff --cc crates/openhuman-core/src/flows/ops_tests.rs
index fb5e5291d8,fb5e5291d8..36fbbb5ca7
--- a/crates/openhuman-core/src/flows/ops_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_tests.rs
@@@ -672,3 -672,3 +672,12 @@@ mod tool_contract_and_wiring_warnings_t
mod triggers_and_resume_tests;
#[path = "ops_validate_warnings_and_connections_tests.rs"]
mod validate_warnings_and_connections_tests;
++
++#[test]
++fn the_boot_sweep_leaves_shared_backends_alone() {
++ use super::run_management::{boot_sweep_plan, BootSweepPlan};
++ assert_eq!(boot_sweep_plan(false, false), BootSweepPlan::EveryScope);
++ assert_eq!(boot_sweep_plan(false, true), BootSweepPlan::EveryScope);
++ assert_eq!(boot_sweep_plan(true, false), BootSweepPlan::LocalOnly);
++ assert_eq!(boot_sweep_plan(true, true), BootSweepPlan::Nothing);
++}
diff --cc crates/openhuman-core/src/security/devices/bus.rs
index 2b1a829b5b,979c0747c9..d2dc9ef608
--- a/crates/openhuman-core/src/security/devices/bus.rs
+++ b/crates/openhuman-core/src/security/devices/bus.rs
@@@ -84,20 -84,7 +84,30 @@@ impl EventHandler<DomainEvent> for Devi
channel_id,
payload_b64,
} => {
- handle_tunnel_frame(channel_id, payload_b64).await;
+ // Handle the frame as the agent the device belongs to, so its
+ // pairing record and the RPCs it sends land in that agent's
+ // scope (`super::owner`).
+ let pending = PENDING_SESSIONS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(channel_id.as_str())
+ .cloned();
- let owner = super::owner::owner_of(channel_id, pending.as_ref()).await;
- crate::storage::agents::within_agent(
- owner.as_deref(),
- handle_tunnel_frame(channel_id, payload_b64),
- )
- .await;
++ match super::owner::owner_of(channel_id, pending.as_ref()).await {
++ Ok(owner) => {
++ crate::storage::agents::within_agent(
++ owner.as_deref(),
++ handle_tunnel_frame(channel_id, payload_b64),
++ )
++ .await;
++ }
++ // Fail closed: an unknown owner must not become `local`.
++ Err(failed) => log::warn!(
++ "[devices/bus] dropping tunnel frame channel_id={channel_id}: owner \
++ lookup failed in scope={} ({})",
++ failed.agent.as_deref().unwrap_or("local"),
++ failed.error
++ ),
++ }
}
_ => {}
}
diff --cc crates/openhuman-core/src/security/devices/owner.rs
index 54fc515b68,0000000000..569401dca0
mode 100644,000000..100644
--- a/crates/openhuman-core/src/security/devices/owner.rs
+++ b/crates/openhuman-core/src/security/devices/owner.rs
@@@ -1,79 -1,0 +1,115 @@@
+//! Which agent a paired device belongs to.
+//!
+//! A device paired from inside an agent's context is stored in that agent's
+//! storage scope (`crate::storage`), and the RPCs it sends through the tunnel
+//! must run as that agent — not as the process default, which would read and
+//! write somebody else's records. The tunnel subscriber runs outside any
+//! agent, so it asks here, per frame:
+//!
+//! 1. the pending pairing session, which recorded the agent that started it;
+//! 2. the owners this process has already resolved;
+//! 3. otherwise each storage scope, for a device paired by an earlier process
+//! (`crate::storage::agents::for_each_scope`).
+//!
+//! `None` means the `local` scope (a single-user host, or no backend).
+
+use std::collections::HashMap;
+use std::sync::{LazyLock, Mutex};
+
+use super::types::PairingSession;
+
+/// Channels whose owner this process has resolved: `Some(agent)`, or `None`
+/// for `local`.
+static OWNERS: LazyLock<Mutex<HashMap<String, Option<String>>>> = LazyLock::new(Default::default);
+
+/// Records that `channel_id` belongs to `agent` (`None` = `local`).
+pub(super) fn remember(channel_id: &str, agent: Option<String>) {
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(channel_id.to_string(), agent);
+}
+
+fn cached(channel_id: &str) -> Option<Option<String>> {
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(channel_id)
+ .cloned()
+}
+
- /// The agent `channel_id` belongs to, resolved as described above. A channel
- /// no scope knows yet (a handshake still in flight) is `local`.
- pub(super) async fn owner_of(channel_id: &str, pending: Option<&PairingSession>) -> Option<String> {
++/// A scope's device lookup failed, and no other scope has the device, so its
++/// owner is unknown. The frame is dropped rather than handled as `local`:
++/// guessing could run a paired device's RPCs as the wrong agent.
++#[derive(Debug, Clone, PartialEq, Eq)]
++pub(super) struct OwnerLookupFailed {
++ /// The scope whose lookup failed (`None` = `local`) and why.
++ pub(super) agent: Option<String>,
++ pub(super) error: String,
++}
++
++/// The agent `channel_id` belongs to, resolved as described above: `None`
++/// for `local`, which is also where a channel no scope knows yet (a handshake
++/// still in flight) is handled.
++///
++/// # Errors
++///
++/// [`OwnerLookupFailed`] when no scope has the device and at least one
++/// scope's lookup failed.
++pub(super) async fn owner_of(
++ channel_id: &str,
++ pending: Option<&PairingSession>,
++) -> Result<Option<String>, OwnerLookupFailed> {
+ if let Some(session) = pending {
- return session.agent.clone();
++ return Ok(session.agent.clone());
+ }
+ if let Some(owner) = cached(channel_id) {
- return owner;
++ return Ok(owner);
+ }
+ // The configuration is loaded inside each scope: in SaaS mode loading it
+ // needs an acting agent, which this tunnel task does not have.
- let found = crate::storage::agents::for_each_scope("device owner", || async {
- let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {
- return false;
- };
++ let lookups = crate::storage::agents::for_each_scope("device owner", || async {
++ let config = crate::config::rpc::load_config_with_timeout()
++ .await
++ .map_err(|error| format!("load config: {error}"))?;
+ super::store::get_device(&config, channel_id)
- .ok()
- .flatten()
- .is_some()
++ .map(|device| device.is_some())
++ .map_err(|error| error.to_string())
+ })
- .await
- .into_iter()
- .find_map(|(agent, has_device)| has_device.then_some(agent));
- match found {
- Some(owner) => {
- log::debug!(
- "[devices/owner] channel_id={channel_id} belongs to agent={}",
- owner.as_deref().unwrap_or("local")
- );
- remember(channel_id, owner.clone());
- owner
++ .await;
++ let owner = decide(lookups)?;
++ if let Some(owner) = &owner {
++ log::debug!(
++ "[devices/owner] channel_id={channel_id} belongs to agent={}",
++ owner.as_deref().unwrap_or("local")
++ );
++ remember(channel_id, owner.clone());
++ }
++ Ok(owner.flatten())
++}
++
++/// The owner from each scope's lookup: the first scope that has the device
++/// (`Some(Some(agent))` / `Some(None)` for `local`); `None` when none has it
++/// and every lookup succeeded; an error when none has it and one failed.
++fn decide(
++ lookups: Vec<(Option<String>, Result<bool, String>)>,
++) -> Result<Option<Option<String>>, OwnerLookupFailed> {
++ let mut failure = None;
++ for (agent, lookup) in lookups {
++ match lookup {
++ Ok(true) => return Ok(Some(agent)),
++ Ok(false) => {}
++ Err(error) => {
++ failure.get_or_insert(OwnerLookupFailed { agent, error });
++ }
+ }
- None => None,
++ }
++ match failure {
++ Some(failure) => Err(failure),
++ None => Ok(None),
+ }
+}
+
+#[cfg(test)]
+#[path = "owner_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/security/devices/owner_tests.rs
index 4a4575c241,0000000000..945c362029
mode 100644,000000..100644
--- a/crates/openhuman-core/src/security/devices/owner_tests.rs
+++ b/crates/openhuman-core/src/security/devices/owner_tests.rs
@@@ -1,81 -1,0 +1,113 @@@
+use super::*;
+
+fn session(agent: Option<&str>) -> PairingSession {
+ PairingSession {
+ channel_id: "owner-test".to_string(),
+ pairing_token: "token".to_string(),
+ core_pubkey: "pk".to_string(),
+ rpc_url: None,
+ expires_at: "2099-01-01T00:00:00Z".to_string(),
+ agent: agent.map(str::to_string),
+ }
+}
+
+#[tokio::test]
+async fn a_pending_pairing_names_its_agent() {
+ let pending = session(Some("agent-7"));
+ assert_eq!(
+ owner_of("owner-test-pending", Some(&pending))
+ .await
++ .unwrap()
+ .as_deref(),
+ Some("agent-7")
+ );
+ let local = session(None);
- assert_eq!(owner_of("owner-test-pending", Some(&local)).await, None);
++ assert_eq!(owner_of("owner-test-pending", Some(&local)).await, Ok(None));
+}
+
+#[tokio::test]
+async fn a_remembered_owner_is_used_without_a_lookup() {
+ remember("owner-test-cached", Some("agent-9".to_string()));
+ assert_eq!(
- owner_of("owner-test-cached", None).await.as_deref(),
++ owner_of("owner-test-cached", None)
++ .await
++ .unwrap()
++ .as_deref(),
+ Some("agent-9")
+ );
+ remember("owner-test-local", None);
- assert_eq!(owner_of("owner-test-local", None).await, None);
++ assert_eq!(owner_of("owner-test-local", None).await, Ok(None));
+}
+
+#[test]
+fn the_agent_is_not_sent_over_the_wire_when_absent() {
+ let json = serde_json::to_value(session(None)).unwrap();
+ assert!(json.get("agent").is_none());
+ let json = serde_json::to_value(session(Some("a"))).unwrap();
+ assert_eq!(json["agent"], "a");
+}
+
+fn scoped_config(dir: &std::path::Path) -> crate::config::Config {
+ crate::config::Config {
+ workspace_dir: dir.join("workspace"),
+ config_path: dir.join("config.toml"),
+ ..Default::default()
+ }
+}
+
+#[tokio::test]
+async fn a_device_found_in_the_local_scope_belongs_to_local_and_is_remembered() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = scoped_config(tmp.path());
+ super::super::store::insert_device(&config, "owner-test-found", "label", "pk", "hash").unwrap();
+ let context = crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ config,
+ );
+ let owner =
+ crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-found", None)).await;
- assert_eq!(owner, None);
++ assert_eq!(owner, Ok(None));
+ assert_eq!(cached("owner-test-found"), Some(None));
+}
+
+#[tokio::test]
+async fn a_channel_no_scope_knows_is_local_and_not_remembered() {
+ let tmp = tempfile::tempdir().unwrap();
+ let context = crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ scoped_config(tmp.path()),
+ );
+ let owner =
+ crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-missing", None))
+ .await;
- assert_eq!(owner, None);
++ assert_eq!(owner, Ok(None));
+ assert_eq!(cached("owner-test-missing"), None);
+}
++
++#[test]
++fn the_first_scope_holding_the_device_owns_it() {
++ let found = decide(vec![
++ (None, Ok(false)),
++ (Some("a".into()), Err("down".into())),
++ (Some("b".into()), Ok(true)),
++ ]);
++ assert_eq!(found, Ok(Some(Some("b".to_string()))));
++ assert_eq!(decide(vec![(None, Ok(true))]), Ok(Some(None)));
++}
++
++#[test]
++fn a_failed_lookup_without_a_match_fails_closed() {
++ let failed = decide(vec![
++ (None, Ok(false)),
++ (Some("a".into()), Err("down".into())),
++ ]);
++ assert_eq!(
++ failed,
++ Err(OwnerLookupFailed {
++ agent: Some("a".to_string()),
++ error: "down".to_string(),
++ })
++ );
++ assert_eq!(decide(vec![(None, Ok(false))]), Ok(None));
++ assert_eq!(decide(Vec::new()), Ok(None));
++}
diff --cc crates/openhuman-core/src/storage/README.md
index 3b9cb90136,14e34a43d4..165916b360
--- a/crates/openhuman-core/src/storage/README.md
+++ b/crates/openhuman-core/src/storage/README.md
@@@ -71,38 -71,6 +71,41 @@@ on `storage-mongodb`
master key they fail closed. The config encryption key stays on the
process keyring, because `config.toml` is loaded before any agent acts.
+## Background work and agent scopes
+
+Work done inside an agent's turn runs under that agent's `CoreContext`
+(`session_agent`, set for embed agents and SaaS user agents), so with a
+backend installed its records land in that agent's scope. Background work
+runs under the process default context and on its own would only see
+`local`. `storage::agents` closes the gap:
+
- - `registered(context)`: `CoreContext::derive_with` records every agent
- context it builds (live, by agent id), and the agent id is written to the
- backend's `local` scope (`storage_agents`) so a restarted process still
- knows it.
++- Known agents: the live ones are `core::runtime::AgentContextRegistry`'s
++ (embed registers each agent it builds and deregisters it on drop).
++ `AgentContextRegistry::register` also records the agent id in the
++ backend's `local` scope (`storage_agents`, `agents::record`), so a
++ restarted process still knows it; `agents::contexts()` lists both.
+- `for_each_scope(label, step)`: runs `step` for `local`, then under each
+ known agent's context — its live one, or the default context acting for it
+ (`CoreContext::for_agent`). `for_each_agent` skips `local`.
+- `within_agent(agent, fut)` / `context_for(agent)`: re-enter an agent's
+ scope when background work learned whose record it is handling.
+- `find_owner(label, probe)`: the scope (`local` first, then each agent)
+ where a record named only by id lives — for event subscribers, whose
+ events carry ids but no agent.
+
- Users: the cron scheduler (`cron::scheduler::tick_agents`), the task-source
- poller, the flows boot sweep and schedule-trigger reconcile, the run reaper,
++Users: the task-source poller, the flows boot sweep and schedule-trigger reconcile, the run reaper,
+the device tunnel (a paired device's frames run as the agent that paired
+it, `security::devices::owner`), and the event subscribers: a flow's
+schedule tick, run digest and dedup settlement run as the flow's owner
+(`flows::bus::owner`); Composio app-event triggers and new connections are
+matched in every scope; a cron job's completion notification is stored with
+the job's owner. Without a backend these run once, as
- before. In SaaS mode agent ids are not recorded and `local` is skipped;
++before. The cron scheduler visits live agents only
++(`cron::scheduler::tick_live_agents`): an agent's jobs need its live
++context (host tools, prompt) to run, so a recorded agent's jobs wait until
++it is live again; with a backend it no longer needs the agent's `jobs.db`. In SaaS mode agent ids are not recorded and `local` is skipped;
+per-user background work there is `user_agents::background`.
+
## Boundaries
The ports, drivers, scopes and conformance suites are tinystoragedrivers';
diff --cc crates/openhuman-core/src/storage/agents.rs
index 5e6c43c7c1,0000000000..b96b31ffa9
mode 100644,000000..100644
--- a/crates/openhuman-core/src/storage/agents.rs
+++ b/crates/openhuman-core/src/storage/agents.rs
@@@ -1,272 -1,0 +1,239 @@@
+//! The agents that keep records in their own storage scope, and a way for
+//! background work to visit each of them.
+//!
+//! Work done inside an agent's turn runs under that agent's `CoreContext`
+//! (`session_agent`), so with a storage backend installed its cron jobs,
+//! flows, approvals and the rest land in that agent's scope. Background work
+//! — the cron scheduler, pollers, boot sweeps — runs under the process
+//! default context, which names no agent, and on its own would only ever see
+//! the `local` scope. [`for_each_scope`] closes that gap: it runs a step once
+//! for `local` and once under each known agent's context.
+//!
- //! An agent is known when a context is derived for it in this process
- //! ([`registered`], called by `CoreContext::derive_with`) — the live context
- //! is used, with the agent's own configuration — or when an earlier process
- //! did and recorded its id in the backend's `local` scope
- //! (`storage_agents`), so a restart still visits agents the host has not
- //! re-created yet; those are visited under the default context with the
- //! agent swapped in (`CoreContext::for_agent`).
++//! An agent is known when it is live in this process
++//! (`core::runtime::AgentContextRegistry`, which embed agents register on
++//! build) — its own context is used, with its configuration, policy and
++//! tools — or when an earlier process recorded its id in the backend's
++//! `local` scope (`storage_agents`, written by [`record`] when the agent
++//! registers), so a restart still visits agents the host has not re-created
++//! yet; those are visited under the default context acting for them
++//! (`CoreContext::for_agent`).
+//!
- //! Without a backend nothing here changes behavior: the SQLite stores do not
- //! split by agent, so [`for_each_scope`] runs the step once. In SaaS mode the
- //! process has no `local` scope and per-user background work is driven by
++//! Without a backend [`for_each_agent`] visits nothing: the SQLite stores
++//! these loops read do not split by agent. In SaaS mode the process has no
++//! `local` scope and per-user background work is driven by
+//! `user_agents::background`, so agent ids are not recorded and
- //! [`for_each_scope`] visits only live agent contexts.
++//! [`for_each_scope`] skips `local`.
+
+use std::collections::{BTreeMap, HashSet};
+use std::future::Future;
- use std::sync::{Arc, LazyLock, Mutex, Weak};
++use std::sync::{Arc, LazyLock, Mutex};
+
+use serde_json::json;
+use tinystoragedrivers::{CollectionSpec, Precondition, Query, Scope};
+
+use super::{block_on, installed, DocumentStoreExt, StorageBackend};
- use crate::core::runtime::CoreContext;
++use crate::core::runtime::{AgentContextRegistry, CoreContext};
+
+/// The `local`-scope collection recording which agents have their own scope.
+const AGENTS: &str = "storage_agents";
+
- /// Live agent contexts, by agent id.
- ///
- /// Several contexts can name one agent (each `derive_with` makes one), so each
- /// agent keeps all of its live contexts, newest last.
- static LIVE: LazyLock<Mutex<BTreeMap<String, Vec<Weak<CoreContext>>>>> =
- LazyLock::new(Default::default);
-
- /// Agent ids this process has already recorded in the backend.
- static RECORDED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Default::default);
++/// `(backend, agent id)` pairs this process has already recorded, the
++/// backend identified by its address (see [`backend_key`]).
++static RECORDED: LazyLock<Mutex<HashSet<(usize, String)>>> = LazyLock::new(Default::default);
+
- /// Records `context` as its agent's live context (when it names one) and
- /// returns it unchanged. `CoreContext::derive_with` passes every derived
- /// context through here.
- pub fn registered(context: Arc<CoreContext>) -> Arc<CoreContext> {
- if let Some(agent) = context.session_agent() {
- let mut live = LIVE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let contexts = live.entry(agent.to_string()).or_default();
- contexts.retain(|existing| existing.strong_count() > 0);
- contexts.push(Arc::downgrade(&context));
- drop(live);
- record(agent);
- }
- context
++/// Identifies `backend` within this process. [`reset_recorded`] runs on every
++/// install and clear, so an address reused by a later backend never inherits
++/// an earlier one's records.
++fn backend_key(backend: &Arc<dyn StorageBackend>) -> usize {
++ Arc::as_ptr(backend).cast::<()>() as usize
+}
+
+/// Forgets which agents were recorded, so the next [`record`] writes them to
+/// the backend now installed (or removed). Called by [`super::install`] and
+/// [`super::clear`]: the record cache describes one backend, not the process.
+pub(super) fn reset_recorded() {
+ RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clear();
+}
+
- /// Records every live agent in the backend — for agents derived before the
- /// host installed its backend. Called by [`super::install`].
++/// Records every live agent in the backend — for agents registered before
++/// the host installed its backend. Called by [`super::install`].
+pub(super) fn record_live() {
- let agents: Vec<String> = LIVE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .keys()
- .cloned()
- .collect();
- for agent in agents {
++ for (agent, _) in AgentContextRegistry::live() {
+ record(&agent);
+ }
+}
+
+/// Writes `agent` to the backend's `storage_agents` collection, once per
- /// process. Best effort: a failure is logged and retried on the next
- /// registration, and only costs a restarted process its visits to that
- /// agent until the agent is derived again.
- fn record(agent: &str) {
++/// process. `AgentContextRegistry::register` calls it for every agent. Best
++/// effort: a failure is logged and retried on the next registration, and
++/// only costs a restarted process its visits to that agent until the agent
++/// registers again.
++pub fn record(agent: &str) {
+ if crate::core::runtime::mode::is_saas() {
+ return;
+ }
+ let Some(backend) = installed() else {
+ return;
+ };
+ record_in(backend, agent);
+}
+
+/// [`record`] against an explicit `backend`.
+fn record_in(backend: Arc<dyn StorageBackend>, agent: &str) {
++ let key = (backend_key(&backend), agent.to_string());
+ if RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(agent)
++ .contains(&key)
+ {
+ return;
+ }
+ let id = agent.to_string();
+ let result = block_on(async move {
+ let docs = Arc::clone(backend.for_scope(&Scope::local())?.documents());
+ docs.ensure_collection(&CollectionSpec::new(AGENTS)).await?;
+ docs.put(AGENTS, &id, json!({}), Precondition::None).await?;
+ Ok(())
+ });
+ match result {
+ Ok(()) => {
+ RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(agent.to_string());
++ .insert(key);
+ tracing::debug!(%agent, "[storage::agents] recorded agent scope");
+ }
+ Err(error) => {
+ tracing::warn!(%agent, %error, "[storage::agents] could not record agent scope");
+ }
+ }
+}
+
+/// Agent ids recorded in the backend by this or an earlier process.
+fn recorded(backend: Arc<dyn StorageBackend>) -> Vec<String> {
+ let result = block_on(async move {
+ let docs = Arc::clone(backend.for_scope(&Scope::local())?.documents());
+ docs.ensure_collection(&CollectionSpec::new(AGENTS)).await?;
+ let stored = docs.query_all(AGENTS, &Query::all()).await?;
+ Ok(stored.into_iter().map(|doc| doc.id).collect::<Vec<_>>())
+ });
+ result.unwrap_or_else(|error| {
+ tracing::warn!(%error, "[storage::agents] could not list recorded agent scopes");
+ Vec::new()
+ })
+}
+
- /// The agents [`for_each_scope`] visits, each with the context to visit it
- /// under: its live context when one exists, else `fallback` acting for it.
- fn agent_contexts(fallback: Option<&Arc<CoreContext>>) -> Vec<(String, Arc<CoreContext>)> {
++/// Every agent background work should visit, each with the context to visit
++/// it under: the live ones (`AgentContextRegistry`), then — with a storage
++/// backend installed, outside SaaS mode — every agent recorded by this or an
++/// earlier process, under the current context acting for it.
++pub fn contexts() -> Vec<(String, Arc<CoreContext>)> {
+ let backend = if crate::core::runtime::mode::is_saas() {
+ None
+ } else {
+ installed()
+ };
- agent_contexts_in(backend, fallback)
++ contexts_in(backend, CoreContext::current().as_ref())
+}
+
- /// [`agent_contexts`] with the backend whose recorded agents are visited
- /// made explicit (`None` visits live contexts only).
- fn agent_contexts_in(
++/// [`contexts`] with the backend whose recorded agents are visited, and the
++/// context that acts for an agent with no live one, made explicit (`None`
++/// visits live contexts only).
++fn contexts_in(
+ backend: Option<Arc<dyn StorageBackend>>,
+ fallback: Option<&Arc<CoreContext>>,
+) -> Vec<(String, Arc<CoreContext>)> {
- let mut contexts: BTreeMap<String, Arc<CoreContext>> = BTreeMap::new();
- {
- let mut live = LIVE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- live.retain(|agent, entries| {
- entries.retain(|entry| entry.strong_count() > 0);
- // The newest context that is still alive acts for the agent.
- if let Some(context) = entries.iter().rev().find_map(Weak::upgrade) {
- contexts.insert(agent.clone(), context);
- }
- !entries.is_empty()
- });
- }
++ let mut contexts: BTreeMap<String, Arc<CoreContext>> =
++ AgentContextRegistry::live().into_iter().collect();
+ if let (Some(backend), Some(fallback)) = (backend, fallback) {
+ for agent in recorded(backend) {
+ contexts
+ .entry(agent.clone())
+ .or_insert_with(|| fallback.for_agent(&agent));
+ }
+ }
+ contexts.into_iter().collect()
+}
+
+/// The context to act for `agent` under: its live context when one exists,
+/// else the current context acting for it (`CoreContext::for_agent`).
+pub fn context_for(agent: &str) -> Option<Arc<CoreContext>> {
- let live = LIVE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .get(agent)
- .and_then(|entries| entries.iter().rev().find_map(Weak::upgrade));
- live.or_else(|| CoreContext::current().map(|current| current.for_agent(agent)))
++ AgentContextRegistry::get(agent)
++ .or_else(|| CoreContext::current().map(|current| current.for_agent(agent)))
+}
+
+/// Runs `fut` acting for `agent` when there is one — background work that
+/// learned whose record it is handling (a device's pairing agent, an event's
+/// publisher) re-enters that agent's scope — and as-is otherwise.
+pub async fn within_agent<F: Future>(agent: Option<&str>, fut: F) -> F::Output {
+ match agent.and_then(context_for) {
+ Some(context) => CoreContext::scope(context, fut).await,
+ None => fut.await,
+ }
+}
+
+/// The scope a record lives in, for background work that holds only its id
+/// (an event naming a flow, a job, a device): the first scope — `local`
+/// first, then each known agent ([`for_each_scope`]) — where `probe` finds
+/// it. `Some(None)` is `local`, `Some(Some(agent))` an agent, `None` nowhere.
+pub async fn find_owner<F, Fut>(label: &str, probe: F) -> Option<Option<String>>
+where
+ F: Fn() -> Fut,
+ Fut: Future<Output = bool>,
+{
+ for_each_scope(label, probe)
+ .await
+ .into_iter()
+ .find_map(|(agent, found)| found.then_some(agent))
+}
+
+/// Runs `step` for every storage scope background work must cover: once
+/// under the current context (the `local` scope, outside SaaS mode), then
+/// once per known agent ([`for_each_agent`]). Each result is returned with
+/// the agent it ran for (`None` for `local`).
+///
+/// `label` names the caller in logs.
+pub async fn for_each_scope<T, F, Fut>(label: &str, step: F) -> Vec<(Option<String>, T)>
+where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+{
+ let mut results = Vec::new();
+ if !crate::core::runtime::mode::is_saas() {
+ results.push((None, step().await));
+ }
+ for (agent, value) in for_each_agent(label, step).await {
+ results.push((Some(agent), value));
+ }
+ results
+}
+
+/// Runs `step` once under each known agent's context, one after another —
+/// only when a storage backend is installed, since without one the stores do
+/// not split by agent and the `local` pass already covers everything.
+///
+/// For a loop that handles the `local` scope itself (the cron scheduler keeps
+/// its process-wide health tracking there) and needs the agents on top.
+pub async fn for_each_agent<T, F, Fut>(label: &str, step: F) -> Vec<(String, T)>
+where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+{
+ if installed().is_none() {
+ return Vec::new();
+ }
- let fallback = CoreContext::current();
+ let mut results = Vec::new();
- for (agent, context) in agent_contexts(fallback.as_ref()) {
++ for (agent, context) in contexts() {
+ tracing::trace!(%agent, label, "[storage::agents] visiting agent scope");
+ let value = CoreContext::scope(context, step()).await;
+ results.push((agent, value));
+ }
+ results
+}
+
+#[cfg(test)]
+#[path = "agents_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/storage/agents_tests.rs
index 83c18ffdde,0000000000..c6b5bcc795
mode 100644,000000..100644
--- a/crates/openhuman-core/src/storage/agents_tests.rs
+++ b/crates/openhuman-core/src/storage/agents_tests.rs
@@@ -1,130 -1,0 +1,154 @@@
+use super::*;
+use crate::core::runtime::{ContextOverlay, DomainSet};
+
- fn agent_context(agent: &str) -> Arc<CoreContext> {
- CoreContext::for_test(DomainSet::full(), None).derive_with(
++/// A context derived for `agent` and registered as that agent's live one,
++/// the way an embed agent is. Each test uses its own agent ids, so tests
++/// sharing the process-wide registry never see each other's agents.
++fn live_agent(agent: &str) -> Arc<CoreContext> {
++ let context = CoreContext::for_test(DomainSet::full(), None).derive_with(
+ ContextOverlay::new(
+ crate::config::Config::default(),
+ DomainSet::full(),
+ Default::default(),
+ )
+ .session_agent(agent),
- )
++ );
++ AgentContextRegistry::register(agent, &context);
++ context
+}
+
- fn live_agents() -> Vec<String> {
- agent_contexts(None).into_iter().map(|(id, _)| id).collect()
++/// Serializes the tests that depend on, or clear, the process-wide record
++/// cache.
++static CACHE: std::sync::Mutex<()> = std::sync::Mutex::new(());
++
++fn memory_backend() -> Arc<dyn StorageBackend> {
++ Arc::new(crate::storage::MemoryStorage::new())
++}
++
++fn visited(
++ backend: Option<Arc<dyn StorageBackend>>,
++ fallback: Option<&Arc<CoreContext>>,
++) -> Vec<String> {
++ contexts_in(backend, fallback)
++ .into_iter()
++ .map(|(id, _)| id)
++ .collect()
+}
+
+#[test]
- fn deriving_an_agent_context_registers_it_until_dropped() {
- let context = agent_context("agents-test-live");
- assert!(live_agents().contains(&"agents-test-live".to_string()));
- let (_, found) = agent_contexts(None)
++fn a_registered_agent_is_visited_through_its_live_context() {
++ let context = live_agent("agents-test-live");
++ let (_, found) = contexts_in(None, None)
+ .into_iter()
+ .find(|(id, _)| id == "agents-test-live")
- .unwrap();
++ .expect("a live agent is visited");
+ assert!(Arc::ptr_eq(&found, &context), "the live context is used");
++ assert!(Arc::ptr_eq(
++ &context_for("agents-test-live").unwrap(),
++ &context
++ ));
++ assert!(AgentContextRegistry::deregister(
++ "agents-test-live",
++ &context
++ ));
+ drop((found, context));
- assert!(!live_agents().contains(&"agents-test-live".to_string()));
- }
-
- #[test]
- fn a_context_without_an_agent_is_not_registered() {
- let before = live_agents().len();
- let _plain = CoreContext::for_test(DomainSet::full(), None);
- assert_eq!(live_agents().len(), before);
++ assert!(!visited(None, None).contains(&"agents-test-live".to_string()));
+}
+
+#[test]
+fn for_agent_swaps_only_the_agent() {
- let parent = agent_context("agents-test-parent");
++ let parent = live_agent("agents-test-parent");
+ let child = parent.for_agent("agents-test-other");
+ assert_eq!(child.session_agent(), Some("agents-test-other"));
+ assert_eq!(parent.session_agent(), Some("agents-test-parent"));
- }
-
- #[tokio::test]
- async fn without_a_backend_only_the_local_scope_runs() {
- // The lib test binary never installs a backend into the process slot.
- if installed().is_some() {
- return;
- }
- let _agent = agent_context("agents-test-unvisited");
- let runs = for_each_scope("test", || async {
- CoreContext::current().and_then(|c| c.session_agent().map(str::to_string))
- })
- .await;
- assert_eq!(runs.len(), 1);
- assert_eq!(runs[0].0, None);
- assert!(for_each_agent("test", || async {}).await.is_empty());
- }
-
- #[test]
- fn a_dropped_sibling_context_does_not_hide_a_live_one() {
- let first = agent_context("agents-test-siblings");
- let second = agent_context("agents-test-siblings");
- drop(second);
- let (_, found) = agent_contexts(None)
- .into_iter()
- .find(|(id, _)| id == "agents-test-siblings")
- .expect("the first context is still live");
- assert!(Arc::ptr_eq(&found, &first));
- assert!(context_for("agents-test-siblings").is_some());
- drop((found, first));
- assert!(!live_agents().contains(&"agents-test-siblings".to_string()));
- }
-
- #[test]
- fn reset_recorded_forgets_what_was_recorded() {
- RECORDED
- .lock()
- .unwrap()
- .insert("agents-test-recorded".into());
- reset_recorded();
- assert!(!RECORDED.lock().unwrap().contains("agents-test-recorded"));
- }
-
- fn memory_backend() -> Arc<dyn StorageBackend> {
- Arc::new(crate::storage::MemoryStorage::new())
++ AgentContextRegistry::deregister("agents-test-parent", &parent);
+}
+
+#[test]
+fn a_recorded_agent_is_visited_through_the_fallback_context() {
+ let backend = memory_backend();
- reset_recorded();
+ record_in(Arc::clone(&backend), "agents-test-recorded-only");
+ assert!(recorded(Arc::clone(&backend)).contains(&"agents-test-recorded-only".to_string()));
+
+ let fallback = CoreContext::for_test(DomainSet::full(), None);
- let visited = agent_contexts_in(Some(backend), Some(&fallback));
- let (_, context) = visited
++ let found = contexts_in(Some(backend), Some(&fallback));
++ let (_, context) = found
+ .iter()
+ .find(|(id, _)| id == "agents-test-recorded-only")
+ .expect("the recorded agent is visited");
+ assert_eq!(context.session_agent(), Some("agents-test-recorded-only"));
+}
+
+#[test]
- fn recording_is_skipped_for_an_agent_already_recorded_to_that_backend() {
++fn without_a_fallback_recorded_agents_are_not_visited() {
++ let backend = memory_backend();
++ record_in(Arc::clone(&backend), "agents-test-no-fallback");
++ assert!(!visited(Some(backend), None).contains(&"agents-test-no-fallback".to_string()));
++}
++
++#[test]
++fn an_agent_is_recorded_once_per_backend() {
++ let _serial = CACHE
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let first = memory_backend();
- reset_recorded();
+ record_in(Arc::clone(&first), "agents-test-once");
- // A second backend is only populated once the cache is reset.
++ // Removing the record behind the cache's back shows the second call is
++ // skipped: the cache says this backend already has it.
++ let docs = Arc::clone(first.for_scope(&Scope::local()).unwrap().documents());
++ block_on(async move {
++ docs.delete(AGENTS, "agents-test-once", Precondition::None)
++ .await
++ .map(|_| ())
++ })
++ .unwrap();
++ record_in(Arc::clone(&first), "agents-test-once");
++ assert!(recorded(first).is_empty());
++ // Another backend is a separate record.
+ let second = memory_backend();
+ record_in(Arc::clone(&second), "agents-test-once");
- assert!(recorded(Arc::clone(&second)).is_empty());
- reset_recorded();
- record_in(Arc::clone(&second), "agents-test-once");
+ assert_eq!(recorded(second), vec!["agents-test-once".to_string()]);
+}
+
+#[test]
- fn without_a_fallback_only_live_contexts_are_visited() {
++fn reset_recorded_empties_the_cache() {
++ let _serial = CACHE
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let backend = memory_backend();
++ record_in(Arc::clone(&backend), "agents-test-reset");
+ reset_recorded();
- record_in(Arc::clone(&backend), "agents-test-no-fallback");
- assert!(!agent_contexts_in(Some(backend), None)
- .iter()
- .any(|(id, _)| id == "agents-test-no-fallback"));
++ assert!(!RECORDED
++ .lock()
++ .unwrap()
++ .contains(&(backend_key(&backend), "agents-test-reset".to_string())));
++}
++
++#[tokio::test]
++async fn without_a_backend_only_the_local_scope_runs() {
++ // The lib test binary never installs a backend into the process slot.
++ if installed().is_some() {
++ return;
++ }
++ let agent = live_agent("agents-test-unvisited");
++ let runs = for_each_scope("test", || async {
++ CoreContext::current().and_then(|c| c.session_agent().map(str::to_string))
++ })
++ .await;
++ assert_eq!(runs.len(), 1);
++ assert_eq!(runs[0].0, None);
++ assert!(for_each_agent("test", || async {}).await.is_empty());
++ assert_eq!(
++ find_owner("test", || async { false }).await,
++ None,
++ "nothing anywhere"
++ );
++ assert_eq!(find_owner("test", || async { true }).await, Some(None));
++ let inside = within_agent(Some("agents-test-unvisited"), async {
++ CoreContext::current().and_then(|c| c.session_agent().map(str::to_string))
++ })
++ .await;
++ assert_eq!(inside.as_deref(), Some("agents-test-unvisited"));
++ assert_eq!(within_agent(None, async { 7 }).await, 7);
++ AgentContextRegistry::deregister("agents-test-unvisited", &agent);
+}
diff --cc tests/storage_scope_e2e.rs
index 20b064995e,0000000000..71c6ba29e5
mode 100644,000000..100644
--- a/tests/storage_scope_e2e.rs
+++ b/tests/storage_scope_e2e.rs
@@@ -1,94 -1,0 +1,98 @@@
+//! Background work reaches the records an agent keeps in its own storage
+//! scope.
+//!
+//! A job scheduled from inside an agent's context is stored in that agent's
+//! scope, so the `local` pass a background loop makes on its own never sees
+//! it; `storage::agents::for_each_scope` visits the agent too — through its
+//! live context while it exists, and through the agent id the backend
+//! recorded once it is gone (a restarted process).
+//!
+//! Its own test binary because it installs a backend into the process-wide
+//! storage slot and boots a core. One test, so nothing in it races either.
+
+use std::sync::Arc;
+
+use openhuman_core::config::Config;
+use openhuman_core::core::runtime::{
- ContextOverlay, CoreBuilder, CoreContext, DomainSet, ServiceSet,
++ AgentContextRegistry, ContextOverlay, CoreBuilder, CoreContext, DomainSet, ServiceSet,
+};
+use openhuman_core::cron::{self, Schedule};
+use openhuman_core::storage::agents::{find_owner, for_each_scope, within_agent};
+use openhuman_core::HostKind;
+
+fn job_names(config: &Config) -> Vec<String> {
+ cron::list_jobs(config)
+ .unwrap()
+ .into_iter()
+ .filter_map(|job| job.name)
+ .collect()
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn background_work_visits_every_agent_scope() {
+ let workspace = tempfile::tempdir().unwrap();
+ let config = Config {
+ workspace_dir: workspace.path().join("workspace"),
+ config_path: workspace.path().join("config.toml"),
+ ..Config::default()
+ };
+ let _runtime = CoreBuilder::new(HostKind::Library)
+ .config(config.clone())
+ .services(ServiceSet::none())
+ .domains(DomainSet::none())
+ .build()
+ .await
+ .unwrap();
+ openhuman_core::storage::install(Arc::new(openhuman_core::storage::MemoryStorage::new()));
+
+ let agent = CoreContext::current().unwrap().derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::none(), Default::default())
+ .session_agent("agent-e2e"),
+ );
++ // How a host's agent becomes known to background work (embed does this
++ // when it builds an agent).
++ AgentContextRegistry::register("agent-e2e", &agent);
+ // The store calls block on storage's own bridge thread, so they are
+ // made straight from the agent's task, where its context is in scope.
+ CoreContext::scope(Arc::clone(&agent), async {
+ cron::add_shell_job(
+ &config,
+ Some("agent-job".to_string()),
+ Schedule::Every { every_ms: 60_000 },
+ "echo hi",
+ )
+ .unwrap();
+ })
+ .await;
+
+ // The agent's job is invisible to the `local` scope.
+ assert!(job_names(&config).is_empty());
+
+ // Visited through the live agent context …
+ let live = for_each_scope("e2e", || async { job_names(&config) }).await;
+ assert!(
+ live.contains(&(Some("agent-e2e".to_string()), vec!["agent-job".to_string()])),
+ "{live:?}"
+ );
+
+ // An event naming only the job resolves to its owner, and handling it
+ // there sees the job.
+ let job_id = within_agent(Some("agent-e2e"), async {
+ cron::list_jobs(&config).unwrap()[0].id.clone()
+ })
+ .await;
+ let owner = find_owner("e2e", || async { cron::get_job(&config, &job_id).is_ok() }).await;
+ assert_eq!(owner, Some(Some("agent-e2e".to_string())));
+ let missing = find_owner("e2e", || async { cron::get_job(&config, "nope").is_ok() }).await;
+ assert_eq!(missing, None);
+
+ // … and, once the agent is gone, through the id the backend recorded.
++ assert!(AgentContextRegistry::deregister("agent-e2e", &agent));
+ drop(agent);
+ let recorded = for_each_scope("e2e", || async { job_names(&config) }).await;
+ assert!(
+ recorded.contains(&(Some("agent-e2e".to_string()), vec!["agent-job".to_string()])),
+ "{recorded:?}"
+ );
+ assert!(recorded.contains(&(None, Vec::new())), "{recorded:?}");
+}