Skip to content

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

refactor(storage): make agent backend selection injectable

Steven Enamakel73ae76f4fd9d
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs
index 5eaab97436..ba27d2fa91 100644
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@ -90,17 +90,10 @@ pub async fn run(config: Config) -> Result<()> {
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 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,
- ));
let mut steady = *health
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- tick_once(&config, &security, &mut steady).await;
+ tick_agent_scope(config, &mut steady).await;
*health
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = steady;
@@ -111,6 +104,19 @@ pub(crate) async fn tick_agents(config: &Config, last_emitted_health: &mut Optio
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
+/// 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;
+}
+
/// Single poll cycle of the scheduler loop, extracted so tests can drive
/// it without owning `tokio::time::interval`.
///
diff --git a/crates/openhuman-core/src/security/devices/owner_tests.rs b/crates/openhuman-core/src/security/devices/owner_tests.rs
index c756f226f1..4476e9adf8 100644
--- a/crates/openhuman-core/src/security/devices/owner_tests.rs
+++ b/crates/openhuman-core/src/security/devices/owner_tests.rs
@@ -42,3 +42,40 @@ fn the_agent_is_not_sent_over_the_wire_when_absent() {
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!(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!(cached("owner-test-missing"), None);
+}
diff --git a/crates/openhuman-core/src/storage/agents.rs b/crates/openhuman-core/src/storage/agents.rs
index 9d709001b2..53f430b070 100644
--- a/crates/openhuman-core/src/storage/agents.rs
+++ b/crates/openhuman-core/src/storage/agents.rs
@@ -98,6 +98,11 @@ fn record(agent: &str) {
let Some(backend) = installed() else {
return;
};
+ record_in(backend, agent);
+}
+
+/// [`record`] against an explicit `backend`.
+fn record_in(backend: Arc<dyn StorageBackend>, agent: &str) {
if RECORDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
@@ -143,6 +148,20 @@ fn recorded(backend: Arc<dyn StorageBackend>) -> Vec<String> {
/// 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>)> {
+ let backend = if crate::core::runtime::mode::is_saas() {
+ None
+ } else {
+ installed()
+ };
+ agent_contexts_in(backend, fallback)
+}
+
+/// [`agent_contexts`] with the backend whose recorded agents are visited
+/// made explicit (`None` visits live contexts only).
+fn agent_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
@@ -157,13 +176,11 @@ fn agent_contexts(fallback: Option<&Arc<CoreContext>>) -> Vec<(String, Arc<CoreC
!entries.is_empty()
});
}
- if !crate::core::runtime::mode::is_saas() {
- if let (Some(backend), Some(fallback)) = (installed(), fallback) {
- for agent in recorded(backend) {
- contexts
- .entry(agent.clone())
- .or_insert_with(|| fallback.for_agent(&agent));
- }
+ 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()
diff --git a/crates/openhuman-core/src/storage/agents_tests.rs b/crates/openhuman-core/src/storage/agents_tests.rs
index f5fd254db3..83c18ffdde 100644
--- a/crates/openhuman-core/src/storage/agents_tests.rs
+++ b/crates/openhuman-core/src/storage/agents_tests.rs
@@ -84,3 +84,47 @@ fn reset_recorded_forgets_what_was_recorded() {
reset_recorded();
assert!(!RECORDED.lock().unwrap().contains("agents-test-recorded"));
}
+
+fn memory_backend() -> Arc<dyn StorageBackend> {
+ Arc::new(crate::storage::MemoryStorage::new())
+}
+
+#[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
+ .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() {
+ 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.
+ 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() {
+ let backend = memory_backend();
+ 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"));
+}