The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(learning): read facets through the memory engine the user chose
Shanu2435c8f00cb5
diff --git a/crates/openhuman-core/src/agent/learning/cache.rs b/crates/openhuman-core/src/agent/learning/cache.rsindex ec9f1438a4..52a6e51936 100644--- a/crates/openhuman-core/src/agent/learning/cache.rs+++ b/crates/openhuman-core/src/agent/learning/cache.rs@@ -4,9 +4,11 @@//! The stability detector uses this to persist the result of each rebuild cycle.//! Prompt sections use [`FacetCache::list_active`] to read the ambient cache.+use std::path::{Path, PathBuf};use std::sync::Arc;use crate::agent::learning::candidate::FacetClass;+use crate::config::schema::MemorySubsystemConfig;use crate::memory::guard::MemoryGuard;use tinymemory_api::provider::{MemoryProfile, MemoryProvider, ProfileFacet, UserState};@@ -30,17 +32,41 @@ pub struct FacetCache {/// Where a cache reads its facets from.///-/// Production always takes [`Source::Guard`] — the bound driver, policy layer-/// included. [`Source::Direct`] exists for tests, which need somewhere to put-/// facets without standing up a driver; see+/// Production takes [`Source::Guard`] or [`Source::Workspace`] — the bound+/// driver, policy layer included. [`Source::Direct`] exists for tests, which+/// need somewhere to put facets without standing up a driver; see/// [`super::test_profile`] for why that is the right trade rather than parking/// the learning tests on a module artifact.enum Source {Guard(Arc<MemoryGuard>),+ /// Resolved again on every call; see [`FacetCache::for_workspace`].+ Workspace {+ dir: PathBuf,+ memory: MemorySubsystemConfig,+ },Direct(Arc<dyn MemoryProfile>),}+/// The driver one call reads through, held for that call.+enum Resolved<'a> {+ Guard(Arc<MemoryGuard>),+ Direct(&'a dyn MemoryProfile),+}++impl Resolved<'_> {+ /// The profile family, or a caller-facing error.+ fn profile(&self) -> anyhow::Result<&dyn MemoryProfile> {+ match self {+ Resolved::Guard(guard) => guard.as_profile().ok_or_else(|| {+ anyhow::anyhow!("memory driver does not support the profile family")+ }),+ Resolved::Direct(profile) => Ok(*profile),+ }+ }+}+impl FacetCache {+ /// A cache over one resolved driver, for the length of a request.#[must_use]pub fn new(guard: Arc<MemoryGuard>) -> Self {Self {@@ -48,6 +74,29 @@ impl FacetCache {}}+ /// A cache over whichever driver serves `workspace_dir`, resolved again on+ /// every call.+ ///+ /// For a cache that outlives a request: the rebuild loop and the PROFILE.md+ /// renderer hold theirs for the whole process. A cache over one resolved+ /// guard keeps that driver after an engine switch, since a switch re-points+ /// the workspace's context and only a new resolution sees the new engine+ /// (`memory::binding_rebind`). Each call goes through the context serving+ /// the workspace when there is one, so it follows a switch, and otherwise+ /// through the binding for `memory`, the workspace's own+ /// `[subsystems.memory]`. That is the case at boot, before the context+ /// exists, where the default config would bind the local engine whatever+ /// the user chose.+ #[must_use]+ pub fn for_workspace(workspace_dir: PathBuf, memory: MemorySubsystemConfig) -> Self {+ Self {+ source: Source::Workspace {+ dir: workspace_dir,+ memory,+ },+ }+ }+/// A cache over a caller-supplied profile family.////// Test-only: production must go through the guard so the policy layer is@@ -64,24 +113,23 @@ impl FacetCache {}}- /// The profile family, or a caller-facing error.- fn profile(&self) -> anyhow::Result<&dyn MemoryProfile> {+ /// The driver this call reads through.+ fn resolve(&self) -> anyhow::Result<Resolved<'_>> {match &self.source {- Source::Guard(guard) => guard.as_profile().ok_or_else(|| {- anyhow::anyhow!("memory driver does not support the profile family")- }),- Source::Direct(profile) => Ok(profile.as_ref()),+ Source::Guard(guard) => Ok(Resolved::Guard(Arc::clone(guard))),+ Source::Workspace { dir, memory } => workspace_guard(dir, memory).map(Resolved::Guard),+ Source::Direct(profile) => Ok(Resolved::Direct(profile.as_ref())),}}/// List all facets with `state = 'active'`, ordered by stability descending.pub async fn list_active(&self) -> anyhow::Result<Vec<ProfileFacet>> {- Ok(self.profile()?.list_active_facets().await?)+ Ok(self.resolve()?.profile()?.list_active_facets().await?)}/// List all facets (all states), ordered by stability descending.pub async fn list_all(&self) -> anyhow::Result<Vec<ProfileFacet>> {- Ok(self.profile()?.list_all_facets().await?)+ Ok(self.resolve()?.profile()?.list_all_facets().await?)}/// List active facets belonging to a specific class.@@ -98,12 +146,12 @@ impl FacetCache {/// Fetch a single facet by its full key (e.g. `"style/verbosity"`).pub async fn get(&self, key: &str) -> anyhow::Result<Option<ProfileFacet>> {- Ok(self.profile()?.get_facet(key).await?)+ Ok(self.resolve()?.profile()?.get_facet(key).await?)}/// Upsert a fully-formed facet row (rebuild path).pub async fn upsert(&self, facet: &ProfileFacet) -> anyhow::Result<()> {- Ok(self.profile()?.upsert_facet(facet).await?)+ Ok(self.resolve()?.profile()?.upsert_facet(facet).await?)}/// Override the `user_state` of a facet.@@ -111,6 +159,7 @@ impl FacetCache {/// Returns `Ok(true)` if a row was found and updated.pub async fn set_user_state(&self, key: &str, user_state: UserState) -> anyhow::Result<bool> {Ok(self+ .resolve()?.profile()?.set_facet_user_state(key, user_state).await?)@@ -118,17 +167,34 @@ impl FacetCache {/// Delete a facet by key. Returns `true` if a row was removed.pub async fn delete(&self, key: &str) -> anyhow::Result<bool> {- Ok(self.profile()?.delete_facet(key).await?)+ Ok(self.resolve()?.profile()?.delete_facet(key).await?)}/// Delete all `Dropped`-state facets whose stability is below `threshold`.////// Pinned facets are never deleted. Returns the number of rows removed.pub async fn drop_below_threshold(&self, threshold: f64) -> anyhow::Result<usize> {- Ok(self.profile()?.drop_facets_below(threshold).await?)+ Ok(self+ .resolve()?+ .profile()?+ .drop_facets_below(threshold)+ .await?)}}+/// The guarded driver serving `dir` now: through the context that serves the+/// workspace when there is one, which an engine switch re-points, else through+/// the binding for `memory`.+fn workspace_guard(dir: &Path, memory: &MemorySubsystemConfig) -> anyhow::Result<Arc<MemoryGuard>> {+ let context = crate::core::runtime::context::CoreContext::current()+ .filter(|ctx| ctx.workspace_dir().ok().as_deref() == Some(dir));+ let guard = match context {+ Some(ctx) => ctx.memory(),+ None => crate::memory::binding::for_workspace(dir, memory).map(|binding| binding.guard()),+ };+ guard.map_err(|error| anyhow::anyhow!("no memory binding for the facet cache: {error}"))+}+// ── Class ↔ key utilities ─────────────────────────────────────────────────────/// Extract the [`FacetClass`] from a full key string (e.g. `"style/verbosity"` → `Style`).diff --git a/crates/openhuman-core/src/agent/learning/startup.rs b/crates/openhuman-core/src/agent/learning/startup.rsindex 5be437d03a..1c4f58e1ca 100644--- a/crates/openhuman-core/src/agent/learning/startup.rs+++ b/crates/openhuman-core/src/agent/learning/startup.rs@@ -30,6 +30,8 @@ use std::sync::OnceLock;use tinybus::SubscriptionHandle;+use crate::config::schema::MemorySubsystemConfig;+static EMAIL_SIG_HANDLE: OnceLock<Option<SubscriptionHandle>> = OnceLock::new();/// Register the always-on learning subscribers on the global event bus.@@ -41,8 +43,14 @@ static EMAIL_SIG_HANDLE: OnceLock<Option<SubscriptionHandle>> = OnceLock::new();/// lifetime of the process (same pattern as `TracingSubscriber`).////// `workspace_dir` is the resolved workspace directory used by the-/// `ProfileMdRenderer` to locate `PROFILE.md`.-pub fn register_learning_subscribers(workspace_dir: std::path::PathBuf) {+/// `ProfileMdRenderer` to locate `PROFILE.md`, and `memory` its+/// `[subsystems.memory]` block: the engine learning reads and writes facets+/// through until the workspace's context exists. This runs at boot before it+/// does.+pub fn register_learning_subscribers(+ workspace_dir: std::path::PathBuf,+ memory: MemorySubsystemConfig,+) {// Phase 2 learning producer: email-signature subscriber reacts to// DocumentCanonicalized events and emits Identity candidates into the// buffer. Needs no memory client, so it always registers.@@ -57,8 +65,8 @@ pub fn register_learning_subscribers(workspace_dir: std::path::PathBuf) {// process globals.static CLIENT_HANDLES: OnceLock<(Option<SubscriptionHandle>, Option<SubscriptionHandle>)> =OnceLock::new();- let memory_ready = memory_is_bindable(&workspace_dir);- CLIENT_HANDLES.get_or_init(|| register_with_memory(memory_ready, &workspace_dir));+ let memory_ready = memory_is_bindable(&workspace_dir, &memory);+ CLIENT_HANDLES.get_or_init(|| register_with_memory(memory_ready, &workspace_dir, &memory));}/// Whether this workspace has a usable memory driver to register learning@@ -76,8 +84,7 @@ pub fn register_learning_subscribers(workspace_dir: std::path::PathBuf) {/// negative here is `MemoryBinding::disables_memory`: memory explicitly/// configured off, which is the one state in which a rebuild loop has nothing/// to rebuild against.-fn memory_is_bindable(workspace_dir: &Path) -> bool {- use crate::config::schema::MemorySubsystemConfig;+fn memory_is_bindable(workspace_dir: &Path, memory: &MemorySubsystemConfig) -> bool {// An explicit `driver = "null"` advertises no capabilities at all, which is// how the context reports "memory is off" without exposing the binding.if let Some(ctx) = ambient_context_for(workspace_dir) {@@ -89,7 +96,7 @@ fn memory_is_bindable(workspace_dir: &Path) -> bool {}return true;}- match crate::memory::binding::for_workspace(workspace_dir, &MemorySubsystemConfig::default()) {+ match crate::memory::binding::for_workspace(workspace_dir, memory) {Ok(binding) if binding.disables_memory() => {tracing::warn!(driver = %binding.driver_id(),@@ -115,8 +122,9 @@ fn memory_is_bindable(workspace_dir: &Path) -> bool {////// It carries the workspace's `[subsystems.memory]` config (including a/// memory-engine switch), so learning binds to the engine the user chose rather-/// than always to the default module. `None` means a bare boot with no context-/// for this workspace (unit tests), which falls back to the default config.+/// than always to the default module. `None` means no context serves this+/// workspace yet, as at boot, where the registration runs before the context+/// is installed: the caller's own copy of that config stands in.fn ambient_context_for(workspace_dir: &Path,) -> Option<std::sync::Arc<crate::core::runtime::context::CoreContext>> {@@ -143,38 +151,24 @@ where});}-/// Register the client-dependent learning subscribers.-///-/// The profile facet cache for `workspace_dir`.+/// The profile facet cache for `workspace_dir`, for a subscriber that lives as+/// long as the process: it resolves the workspace's driver on every call (see+/// [`FacetCache::for_workspace`]), so it reaches the engine the user chose at+/// boot and follows a switch made later.///-/// Resolved through the memory binding rather than the process-global client:-/// facets live behind the driver now, and `binding::for_workspace` is-/// synchronous and cached, so this stays callable from the boot path without-/// an await.+/// [`FacetCache::for_workspace`]: crate::agent::learning::cache::FacetCache::for_workspacefn facet_cache_for(- workspace_dir: &std::path::Path,-) -> Option<crate::agent::learning::cache::FacetCache> {- use crate::config::schema::MemorySubsystemConfig;- if let Some(ctx) = ambient_context_for(workspace_dir) {- return match ctx.memory() {- Ok(guard) => Some(crate::agent::learning::cache::FacetCache::new(guard)),- Err(error) => {- tracing::warn!("[learning::startup] no memory binding for facet cache: {error}");- None- }- };- }- match crate::memory::binding::for_workspace(workspace_dir, &MemorySubsystemConfig::default()) {- Ok(binding) => Some(crate::agent::learning::cache::FacetCache::new(- binding.guard(),- )),- Err(error) => {- tracing::warn!("[learning::startup] no memory binding for facet cache: {error}");- None- }- }+ workspace_dir: &Path,+ memory: &MemorySubsystemConfig,+) -> crate::agent::learning::cache::FacetCache {+ crate::agent::learning::cache::FacetCache::for_workspace(+ workspace_dir.to_path_buf(),+ memory.clone(),+ )}+/// Register the client-dependent learning subscribers.+////// Returns `(rebuild_trigger_handle, profile_md_renderer_handle)`.////// When `memory_ready` is true, both the Phase 3 rebuild trigger (plus its@@ -190,6 +184,7 @@ fn facet_cache_for(fn register_with_memory(memory_ready: bool,workspace_dir: &Path,+ memory: &MemorySubsystemConfig,) -> (Option<SubscriptionHandle>, Option<SubscriptionHandle>) {if !memory_ready {tracing::warn!(@@ -208,9 +203,7 @@ fn register_with_memory(use crate::agent::learning::scheduler::register_event_trigger;use crate::agent::learning::StabilityDetector;use std::sync::Arc;- let Some(cache) = facet_cache_for(workspace_dir) else {- return (None, None);- };+ let cache = facet_cache_for(workspace_dir, memory);let detector = Arc::new(StabilityDetector::new(cache).persisted_in(workspace_dir));// Also spawn the periodic rebuild loop (30-minute cadence).let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);@@ -239,10 +232,7 @@ fn register_with_memory(let profile_md = {use crate::agent::learning::ProfileMdRenderer;use std::sync::Arc;- let Some(cache) = facet_cache_for(workspace_dir) else {- return (rebuild_trigger, None);- };- let cache = Arc::new(cache);+ let cache = Arc::new(facet_cache_for(workspace_dir, memory));let renderer = Arc::new(ProfileMdRenderer::new(cache, workspace_dir.to_path_buf()));let handle = ProfileMdRenderer::subscribe(renderer);if handle.is_some() {diff --git a/crates/openhuman-core/src/agent/learning/startup_tests.rs b/crates/openhuman-core/src/agent/learning/startup_tests.rsindex b13226a1d7..855ac07350 100644--- a/crates/openhuman-core/src/agent/learning/startup_tests.rs+++ b/crates/openhuman-core/src/agent/learning/startup_tests.rs@@ -4,6 +4,8 @@ use crate::agent::learning::extract::signature::{parse_signature, register_email_signature_subscriber_on,};use crate::core::events::DomainEvent;+use crate::memory::guard::test_support::RecordingProvider;+use std::sync::Arc;use std::time::Duration;use tempfile::TempDir;@@ -61,7 +63,8 @@ async fn wait_for_candidates(buffer: &Buffer, expected: usize) -> usize {async fn register_with_memory_registers_both_handles_when_ready() {crate::core::bus::init().await.expect("bus init");let tmp = test_workspace();- let (trigger, renderer) = register_with_memory(true, tmp.path());+ let (trigger, renderer) =+ register_with_memory(true, tmp.path(), &MemorySubsystemConfig::default());assert!(trigger.is_some(),"rebuild trigger must register when memory is available"@@ -78,7 +81,8 @@ async fn register_with_memory_skips_and_warns_when_memory_absent() {// the (now loud) warn path is exercised. This is the else-arm the #5003// fix upgraded from a silent debug-level skip.let tmp = TempDir::new().expect("tempdir");- let (trigger, renderer) = register_with_memory(false, tmp.path());+ let (trigger, renderer) =+ register_with_memory(false, tmp.path(), &MemorySubsystemConfig::default());assert!(trigger.is_none(), "no trigger without a memory driver");assert!(renderer.is_none(), "no renderer without a memory driver");}@@ -133,3 +137,68 @@ async fn register_learning_subscribers_is_idempotent() {"double registration must not double the pushed candidates (#5003 idempotency)");}++/// An engine the test binds itself, so nothing reaches for the module.+fn chosen_engine() -> MemorySubsystemConfig {+ MemorySubsystemConfig {+ driver: "tinyhumans".into(),+ ..MemorySubsystemConfig::default()+ }+}++fn reached_profile(provider: &RecordingProvider) -> bool {+ provider+ .calls()+ .iter()+ .any(|call| call.method == "profile.list_all_facets")+}++/// Learning registers at boot, before the workspace's context exists, so it+/// asks the binding for the config the boot path hands it: the engine the user+/// chose reads as ready, and memory turned off reads as off.+#[test]+fn memory_readiness_comes_from_the_workspaces_own_config() {+ let tmp = test_workspace();+ let chosen = chosen_engine();+ crate::memory::binding::install_for_test(+ tmp.path(),+ &chosen,+ Arc::new(RecordingProvider::new()),+ );+ assert!(memory_is_bindable(tmp.path(), &chosen));++ let off = MemorySubsystemConfig {+ driver: "null".into(),+ ..MemorySubsystemConfig::default()+ };+ assert!(!memory_is_bindable(tmp.path(), &off));+}++/// The rebuild loop and the PROFILE.md renderer keep their cache for the whole+/// process. It reads through the engine the workspace's config names, and an+/// engine bound for the workspace later, as a switch binds one, is the one its+/// next call reaches.+#[tokio::test]+async fn a_long_lived_facet_cache_reads_the_engine_the_workspace_has_now() {+ let tmp = test_workspace();+ let chosen = chosen_engine();+ let first = Arc::new(RecordingProvider::new());+ crate::memory::binding::install_for_test(tmp.path(), &chosen, first.clone());+ let cache = facet_cache_for(tmp.path(), &chosen);+ cache+ .list_all()+ .await+ .expect("facets through the chosen engine");+ assert!(reached_profile(&first));++ let second = Arc::new(RecordingProvider::new());+ crate::memory::binding::install_for_test(tmp.path(), &chosen, second.clone());+ cache+ .list_all()+ .await+ .expect("facets through the engine bound since");+ assert!(+ reached_profile(&second),+ "a cache built before the switch must reach the engine bound after it"+ );+}diff --git a/crates/openhuman-core/src/core/runtime/subscribers.rs b/crates/openhuman-core/src/core/runtime/subscribers.rsindex 152483639b..f1d82ae6e1 100644--- a/crates/openhuman-core/src/core/runtime/subscribers.rs+++ b/crates/openhuman-core/src/core/runtime/subscribers.rs@@ -330,8 +330,13 @@ pub(super) fn register_domain_subscribers(// when no channel is configured — silently dropping ALL learning for// channel-less users (#5003). `agent::learning` is an Agent-family// domain; it sat on the Platform boot path only because `learning`- // used to be a top-level directory. Idempotent.- crate::agent::learning::startup::register_learning_subscribers(workspace_dir.clone());+ // used to be a top-level directory. Idempotent. The memory block+ // goes along because this runs before the workspace's context is+ // installed, and learning must bind the engine the user chose.+ crate::agent::learning::startup::register_learning_subscribers(+ workspace_dir.clone(),+ config.subsystems.memory.clone(),+ );}} else {log::debug!("[event_bus] learning subscribers SKIPPED — Agent domain disabled");