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
chore: files changed crates/openhuman-core/src/flows/bus/run_digest.rs,crates/openhuman-core/src/flo
Steven Enamakel87dee69f9ca9
diff --git a/crates/openhuman-core/src/flows/bus/run_digest.rs b/crates/openhuman-core/src/flows/bus/run_digest.rsindex 5a122c7cf3..d3f6f4c4c1 100644--- a/crates/openhuman-core/src/flows/bus/run_digest.rs+++ b/crates/openhuman-core/src/flows/bus/run_digest.rs@@ -7,7 +7,7 @@ use crate::config::Config;use crate::core::events::DomainEvent;use crate::flows::store;use crate::memory::types::{ForgetParams, ItemsListParams, MAX_LIMIT};-use crate::memory::{MemoryError, MemoryResult};+use crate::memory::{Error, Result};use async_trait::async_trait;use std::sync::Arc;use tinybus::EventHandler;@@ -111,7 +111,7 @@ impl FlowRunDigestSubscriber {Ok(receipt) => {tracing::debug!(target: "flows", %flow_id, %run_id, replayed = receipt.replayed, "[flows] digest: run digest stored");}- Err(MemoryError::Off(_)) => {+ Err(Error::Off(_)) => {tracing::debug!(target: "flows", %flow_id, %run_id, "[flows] digest: memory is off — skipping");return;}@@ -139,7 +139,7 @@ pub(super) async fn enforce_retention_cap(config: &Config,flow_id: &str,cap: usize,-) -> MemoryResult<usize> {+) -> Result<usize> {let mut digests = Vec::new();let mut cursor = None;loop {diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rsindex 714d9b5e6a..36fd384884 100644--- a/crates/openhuman-core/src/flows/memory_tools.rs+++ b/crates/openhuman-core/src/flows/memory_tools.rs@@ -35,7 +35,7 @@ use tinytools::{PermissionLevel, Tool, ToolResult};use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};use crate::config::Config;use crate::memory::types::{LearnParams, RecallParams};-use crate::memory::{MemoryError, MemoryResult};+use crate::memory::{Error, Result};use crate::security::policy::ToolOperation;use crate::security::SecurityPolicy;@@ -133,15 +133,15 @@ pub fn flow_meta(flow_id: &str, extra: &[String]) -> MemoryMeta {/// Forgets every item matching `filter` (which must be non-empty). Memory/// off forgets nothing.-pub async fn forget_matching(config: &Config, filter: MetaFilter) -> MemoryResult<usize> {+pub async fn forget_matching(config: &Config, filter: MetaFilter) -> Result<usize> {if filter.is_empty() {- return Err(MemoryError::invalid(+ return Err(Error::invalid("refusing to forget with an empty filter",));}let bound = match crate::memory::engine::resolve(config).engine() {Ok(bound) => bound,- Err(MemoryError::Off(_)) => {+ Err(Error::Off(_)) => {tracing::debug!("[flows:memory] forget skipped: memory is off");return Ok(0);}@@ -164,7 +164,7 @@ pub async fn remember_keyed(key: &str,content: &str,kind: LearningKind,-) -> MemoryResult<String> {+) -> Result<String> {// Fail with MEMORY_OFF before touching anything.crate::memory::engine::resolve(config).engine()?;let key_tag = flow_key_tag(flow_id, key);diff --git a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rsindex bcf0b3238a..4970d32359 100644--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs@@ -47,7 +47,7 @@ use crate::flows::{FLOWS_TAG,};use crate::memory::types::{FetchParams, RecallParams};-use crate::memory::MemoryError;+use crate::memory::Error;use crate::security::approval::{redact_args, summarize_action, ApprovalGate, ExecutionOutcome, GateOutcome,};@@ -225,7 +225,7 @@ fn is_untrusted(meta: &MemoryMeta) -> bool {}/// Maps a memory failure onto the node's capability error.-fn capability_error(op: &str, error: &MemoryError) -> EngineError {+fn capability_error(op: &str, error: &Error) -> EngineError {EngineError::Capability(format!("memory node: {op} failed: {error}"))}diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rsindex 6ca58a683e..7315dc9409 100644--- a/crates/openhuman-core/src/memory/backfill.rs+++ b/crates/openhuman-core/src/memory/backfill.rs@@ -38,7 +38,7 @@ use serde::{Deserialize, Serialize};use crate::config::Config;use crate::memory::engine::{self, BoundEngine};-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};use crate::memory::scope::{MemoryIdentity, ResolvedIdentity};use crate::threads::store::blocking as threads;use tinymemory_integrations::import::ImportPhase;@@ -140,10 +140,10 @@ async fn plan(workspace_dir: &Path,bound: Option<&BoundEngine>,stored: &BTreeMap<String, u32>,-) -> MemoryResult<Vec<ThreadPlan>> {+) -> Result<Vec<ThreadPlan>> {let listed = threads::list_threads(ctx.clone(), workspace_dir.to_path_buf()).await- .map_err(|error| MemoryError::Engine(format!("reading chat threads failed: {error}")))?;+ .map_err(|error| Error::Engine(format!("reading chat threads failed: {error}")))?;let mut plans = Vec::new();for thread in listed {let messages = match threads::get_messages(@@ -192,7 +192,7 @@ fn is_running(workspace_dir: &Path) -> bool {}/// `memory_conversations_backfill_status`.-pub async fn status(ctx: &DispatchCtx, config: &Config) -> MemoryResult<BackfillView> {+pub async fn status(ctx: &DispatchCtx, config: &Config) -> Result<BackfillView> {let workspace_dir = &config.workspace_dir;let file = read_file(workspace_dir);let mut state = file.state;@@ -214,9 +214,9 @@ pub async fn start(ctx: &DispatchCtx,config: &Config,params: BackfillStartParams,-) -> MemoryResult<BackfillView> {+) -> Result<BackfillView> {if !params.consent {- return Err(MemoryError::invalid(+ return Err(Error::invalid("storing past chats uploads them to the selected engine; pass consent: true",));}@@ -303,7 +303,7 @@ async fn run(.engine.store_many_with(items, options).await- .map_err(MemoryError::from);+ .map_err(Error::from);if let Err(error) = stored {tracing::warn!(code = error.code(),diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rsindex 6e4ef57e65..7e890d43cf 100644--- a/crates/openhuman-core/src/memory/brain.rs+++ b/crates/openhuman-core/src/memory/brain.rs@@ -20,7 +20,7 @@ use crate::config::schema::MemorySourceKind;use crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::lifecycle::jobs;use super::scope::MemoryIdentity;@@ -47,7 +47,7 @@ pub fn brain_node(layout: &MemoryLayout,source: &BrainSource,item: &StoreItem,-) -> MemoryResult<Namespace> {+) -> Result<Namespace> {Ok(brain_node_with(config.memory.split_github_by_repo,layout,@@ -61,14 +61,14 @@ fn layout(config: &Config, identity: &MemoryIdentity) -> MemoryLayout {identity.resolve(config).layout}-fn brain(config: &Config, identity: &MemoryIdentity) -> MemoryResult<Brain> {+fn brain(config: &Config, identity: &MemoryIdentity) -> Result<Brain> {let bound = engine::resolve(config).engine()?;Ok(Brain::new(bound.engine, layout(config, identity)))}-fn parse_source(raw: &str) -> MemoryResult<BrainSource> {+fn parse_source(raw: &str) -> Result<BrainSource> {raw.parse()- .map_err(|error: tinymemory_api::Error| MemoryError::invalid(error.to_string()))+ .map_err(|error: tinymemory_api::Error| Error::invalid(error.to_string()))}/// One brain source and how many documents it holds.@@ -92,7 +92,7 @@ pub struct BrainSourcesView {}/// `memory_brain_sources`: the brain's sources and their sizes.-pub async fn sources(config: &Config, identity: &MemoryIdentity) -> MemoryResult<BrainSourcesView> {+pub async fn sources(config: &Config, identity: &MemoryIdentity) -> Result<BrainSourcesView> {let bound = engine::resolve(config).engine()?;let layout = layout(config, identity);let page = bound@@ -156,10 +156,10 @@ pub async fn search(config: &Config,identity: &MemoryIdentity,params: BrainSearchParams,-) -> MemoryResult<BrainSearchView> {+) -> Result<BrainSearchView> {let query = params.query.trim();if query.is_empty() {- return Err(MemoryError::invalid("the query is blank"));+ return Err(Error::invalid("the query is blank"));}let source = params.source.as_deref().map(parse_source).transpose()?;let limit = super::types::clamp_limit(params.limit);@@ -207,7 +207,7 @@ pub struct BrainIngestView {/// `action_dir`.////// [`SecurityPolicy::validate_path`]: crate::security::SecurityPolicy::validate_path-async fn ingest_path(config: &Config, path: &str) -> MemoryResult<std::path::PathBuf> {+async fn ingest_path(config: &Config, path: &str) -> Result<std::path::PathBuf> {let policy = crate::security::SecurityPolicy::from_config(&config.autonomy,&config.workspace_dir,@@ -215,7 +215,7 @@ async fn ingest_path(config: &Config, path: &str) -> MemoryResult<std::path::Pat);policy.validate_path(path.trim()).await.map_err(|error| {tracing::warn!("[memory:brain] ingest path refused by the security policy");- MemoryError::invalid(format!("cannot read the file: {error}"))+ Error::invalid(format!("cannot read the file: {error}"))})}@@ -225,23 +225,23 @@ pub async fn ingest(config: &Config,identity: &MemoryIdentity,params: BrainIngestParams,-) -> MemoryResult<BrainIngestView> {+) -> Result<BrainIngestView> {let source = params.source.as_deref().map(parse_source).transpose()?;let mut document = match (params.path.as_deref(), params.text.as_deref()) {(Some(path), None) => {let resolved = ingest_path(config, path).await?;let path = resolved.as_path();let size = std::fs::metadata(path)- .map_err(|error| MemoryError::invalid(format!("cannot read the file: {error}")))?+ .map_err(|error| Error::invalid(format!("cannot read the file: {error}")))?.len();if size > MAX_INGEST_BYTES {- return Err(MemoryError::invalid(format!(+ return Err(Error::invalid(format!("the file is {size} bytes; the limit is {MAX_INGEST_BYTES}")));}let bytes = tokio::fs::read(path).await- .map_err(|error| MemoryError::invalid(format!("cannot read the file: {error}")))?;+ .map_err(|error| Error::invalid(format!("cannot read the file: {error}")))?;let mut raw = RawDocument::new(bytes);if let Some(name) = path.file_name().and_then(|name| name.to_str()) {raw = raw.with_filename(name);@@ -255,12 +255,12 @@ pub async fn ingest(meta,).await- .map_err(|error| MemoryError::invalid(format!("cannot convert the file: {error}")))?+ .map_err(|error| Error::invalid(format!("cannot convert the file: {error}")))?}(None, Some(text)) => {tinymemory_tools::BrainDocument::new(source.unwrap_or_else(files_source), text)}- _ => return Err(MemoryError::invalid("pass exactly one of `path` or `text`")),+ _ => return Err(Error::invalid("pass exactly one of `path` or `text`")),};if let Some(title) = params.title.filter(|title| !title.trim().is_empty()) {document = document.titled(title);@@ -302,7 +302,7 @@ pub async fn forget(config: &Config,identity: &MemoryIdentity,params: BrainForgetParams,-) -> MemoryResult<BrainForgetView> {+) -> Result<BrainForgetView> {let source = parse_source(¶ms.source)?;let report = brain(config, identity)?.forget(&source).await?;tracing::info!(source = %source, forgotten = report.forgotten, "[memory:brain] source forgotten");diff --git a/crates/openhuman-core/src/memory/brain_tests.rs b/crates/openhuman-core/src/memory/brain_tests.rsindex ea7391bfa3..245532cb24 100644--- a/crates/openhuman-core/src/memory/brain_tests.rs+++ b/crates/openhuman-core/src/memory/brain_tests.rs@@ -189,7 +189,7 @@ async fn ingest_refuses_bad_input() {] {assert!(matches!(ingest(&config, &MemoryIdentity::root(), params).await,- Err(MemoryError::InvalidRequest(_))+ Err(Error::InvalidRequest(_))));}assert!(search(@@ -291,7 +291,7 @@ async fn ingest_refuses_a_credential_store_a_system_root_traversal_and_null_byte] {let result = ingest(&config, &MemoryIdentity::root(), path_params(path.clone())).await;assert!(- matches!(result, Err(MemoryError::InvalidRequest(_))),+ matches!(result, Err(Error::InvalidRequest(_))),"{path:?}: {result:?}");}@@ -317,7 +317,7 @@ async fn ingest_refuses_a_symlink_into_a_credential_store() {).await;assert!(- matches!(result, Err(MemoryError::InvalidRequest(_))),+ matches!(result, Err(Error::InvalidRequest(_))),"{result:?}");assert!(engine.is_empty());diff --git a/crates/openhuman-core/src/memory/channels.rs b/crates/openhuman-core/src/memory/channels.rsindex 32b51e1731..375d3d0a76 100644--- a/crates/openhuman-core/src/memory/channels.rs+++ b/crates/openhuman-core/src/memory/channels.rs@@ -15,7 +15,7 @@ use tinymemory_api::{ForgetTarget, ItemKind, MetaFilter};use crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};/// Serialises read-modify-writes of the file in this process.static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));@@ -94,11 +94,11 @@ pub fn threads_of(workspace_dir: &Path, channel: &str) -> Vec<String> {/// names the threads the channel owned at disconnect, so a thread the/// channel brings later is never caught by it. A failure is returned after/// the rest are tried.-pub async fn forget_channel(config: &Config, channel: &str) -> MemoryResult<usize> {+pub async fn forget_channel(config: &Config, channel: &str) -> Result<usize> {let threads = threads_of(&config.workspace_dir, channel);let bound = match engine::resolve(config).engine() {Ok(bound) => Some(bound),- Err(MemoryError::Off(_)) => None,+ Err(Error::Off(_)) => None,Err(error) => return Err(error),};let mut forgotten = 0;@@ -106,7 +106,7 @@ pub async fn forget_channel(config: &Config, channel: &str) -> MemoryResult<usizfor thread_id in threads {let result = match &bound {Some(bound) => forget_thread_with(bound, &thread_id).await,- None => Err(MemoryError::Off("memory is off".to_string())),+ None => Err(Error::Off("memory is off".to_string())),};match result {Ok(count) => forgotten += count,@@ -115,7 +115,7 @@ pub async fn forget_channel(config: &Config, channel: &str) -> MemoryResult<usiz&config.workspace_dir,super::deletion::PendingDeletion::Thread { thread_id },);- if !matches!(error, MemoryError::Off(_)) && failure.is_none() {+ if !matches!(error, Error::Off(_)) && failure.is_none() {failure = Some(error);}}@@ -141,7 +141,7 @@ pub async fn forget_channel(config: &Config, channel: &str) -> MemoryResult<usiz}}-async fn forget_thread_with(bound: &engine::BoundEngine, thread_id: &str) -> MemoryResult<usize> {+async fn forget_thread_with(bound: &engine::BoundEngine, thread_id: &str) -> Result<usize> {let filter = MetaFilter {thread_id: Some(thread_id.to_string()),..MetaFilter::kinds([ItemKind::Conversation])diff --git a/crates/openhuman-core/src/memory/confine.rs b/crates/openhuman-core/src/memory/confine.rsindex 1ffcb18c81..96827e339b 100644--- a/crates/openhuman-core/src/memory/confine.rs+++ b/crates/openhuman-core/src/memory/confine.rs@@ -21,7 +21,7 @@ use tinymemory_api::{ExplorePage, MemoryMeta, MetaFilter, Namespace, Reach};use crate::config::Config;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::explore::{self, ExploreParams, ItemsGetParams, ItemsGetView};use super::ops;use super::scope::MemoryIdentity;@@ -42,8 +42,8 @@ pub fn allowed_reach(config: &Config, identity: &MemoryIdentity) -> Reach {////// # Errors///-/// [`MemoryError::InvalidRequest`] when `reach` reads outside `allowed`.-pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> MemoryResult<Reach> {+/// [`Error::InvalidRequest`] when `reach` reads outside `allowed`.+pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> Result<Reach> {match reach {None => Ok(allowed.clone()),Some(reach) if reach.within(allowed) => Ok(reach),@@ -53,7 +53,7 @@ pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> MemoryResult<Reacallowed = %allowed.at,"[memory:confine] refused a reach outside the caller's root");- Err(MemoryError::invalid(format!(+ Err(Error::invalid(format!("the reach `{}` is outside this caller's memory (`{}`)",reach.at, allowed.at)))@@ -65,9 +65,9 @@ pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> MemoryResult<Reac////// # Errors///-/// [`MemoryError::InvalidRequest`] when the filter's reach reads outside+/// [`Error::InvalidRequest`] when the filter's reach reads outside/// `allowed`.-pub fn confine_filter(filter: Option<MetaFilter>, allowed: &Reach) -> MemoryResult<MetaFilter> {+pub fn confine_filter(filter: Option<MetaFilter>, allowed: &Reach) -> Result<MetaFilter> {let mut filter = filter.unwrap_or_default();filter.reach = Some(confine_reach(filter.reach.take(), allowed)?);Ok(filter)@@ -79,13 +79,13 @@ pub fn confine_filter(filter: Option<MetaFilter>, allowed: &Reach) -> MemoryResu////// # Errors///-/// [`MemoryError::InvalidRequest`] when the namespace is outside the+/// [`Error::InvalidRequest`] when the namespace is outside the/// layout's subtree.pub fn confine_learn_meta(config: &Config,identity: &MemoryIdentity,meta: Option<MemoryMeta>,-) -> MemoryResult<MemoryMeta> {+) -> Result<MemoryMeta> {let resolved = identity.resolve(config);let allowed = Reach::subtree(resolved.root().clone());let mut meta = meta.unwrap_or_default();@@ -98,7 +98,7 @@ pub fn confine_learn_meta(allowed = %allowed.at,"[memory:confine] refused a learning outside the caller's root");- return Err(MemoryError::invalid(format!(+ return Err(Error::invalid(format!("the namespace `{}` is outside this caller's memory (`{}`)",meta.namespace, allowed.at)));@@ -115,7 +115,7 @@ pub async fn recall(config: &Config,identity: &MemoryIdentity,mut params: RecallParams,-) -> MemoryResult<RecallView> {+) -> Result<RecallView> {params.filter = Some(confine_filter(params.filter,&allowed_reach(config, identity),@@ -132,7 +132,7 @@ pub async fn fetch(config: &Config,identity: &MemoryIdentity,mut params: FetchParams,-) -> MemoryResult<FetchView> {+) -> Result<FetchView> {params.filter = Some(confine_filter(params.filter,&allowed_reach(config, identity),@@ -149,7 +149,7 @@ pub async fn learn(config: &Config,identity: &MemoryIdentity,mut params: LearnParams,-) -> MemoryResult<LearnView> {+) -> Result<LearnView> {params.meta = Some(confine_learn_meta(config, identity, params.meta)?);ops::learn(config, params, None).await}@@ -164,7 +164,7 @@ pub async fn forget(config: &Config,identity: &MemoryIdentity,mut params: ForgetParams,-) -> MemoryResult<ForgetView> {+) -> Result<ForgetView> {params.reach = Some(confine_reach(params.reach,&allowed_reach(config, identity),@@ -183,7 +183,7 @@ pub async fn items_list(config: &Config,identity: &MemoryIdentity,mut params: ItemsListParams,-) -> MemoryResult<ItemsListView> {+) -> Result<ItemsListView> {let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;params.filter = Some(confine_filter(Some(narrowed),@@ -203,7 +203,7 @@ pub async fn explore(config: &Config,identity: &MemoryIdentity,mut params: ExploreParams,-) -> MemoryResult<ExplorePage> {+) -> Result<ExplorePage> {let narrowed = explore::narrowed(params.filter.take(), ¶ms.path)?;params.filter = Some(confine_filter(Some(narrowed),@@ -224,7 +224,7 @@ pub async fn items_get(config: &Config,identity: &MemoryIdentity,mut params: ItemsGetParams,-) -> MemoryResult<ItemsGetView> {+) -> Result<ItemsGetView> {params.reach = Some(confine_reach(params.reach,&allowed_reach(config, identity),diff --git a/crates/openhuman-core/src/memory/deletion.rs b/crates/openhuman-core/src/memory/deletion.rsindex e9bd32331a..9aa8a3bfe7 100644--- a/crates/openhuman-core/src/memory/deletion.rs+++ b/crates/openhuman-core/src/memory/deletion.rs@@ -25,7 +25,7 @@ pub use tinymemory_tools::deletion::PendingDeletion;use crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};fn path(workspace_dir: &Path) -> PathBuf {workspace_dir.join("memory").join("pending_deletions.json")@@ -152,7 +152,7 @@ pub async fn drain_due(config: &Config) -> usize {}/// Forgets every conversation item of `thread_id` now.-async fn forget_thread_now(config: &Config, thread_id: &str) -> MemoryResult<usize> {+async fn forget_thread_now(config: &Config, thread_id: &str) -> Result<usize> {let bound = engine::resolve(config).engine()?;let filter = MetaFilter {thread_id: Some(thread_id.to_string()),@@ -179,7 +179,7 @@ pub async fn forget_thread(config: &Config, thread_id: &str) -> usize {};match forget_thread_now(config, thread_id).await {Ok(forgotten) => forgotten,- Err(MemoryError::Off(_)) => {+ Err(Error::Off(_)) => {enqueue(&config.workspace_dir, deletion);0}diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rsindex 03cd5a2a6b..889d8cb60b 100644--- a/crates/openhuman-core/src/memory/engine.rs+++ b/crates/openhuman-core/src/memory/engine.rs@@ -46,7 +46,7 @@ use crate::config::Config;use crate::security::credentials::session_support::resolve_backend_credential;use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};/// Engine id of CortexDB behind the TinyHumans backend.pub const TINYHUMANS_ENGINE: &str = tinymemory_integrations::cortex::TINYHUMANS_ENGINE_ID;@@ -95,11 +95,11 @@ pub enum Binding {}impl Binding {- /// The bound engine, or [`MemoryError::Off`].- pub fn engine(self) -> MemoryResult<BoundEngine> {+ /// The bound engine, or [`Error::Off`].+ pub fn engine(self) -> Result<BoundEngine> {match self {Self::On(bound) => Ok(bound),- Self::Off { reason, .. } => Err(MemoryError::Off(reason)),+ Self::Off { reason, .. } => Err(Error::Off(reason)),}}@@ -280,9 +280,9 @@ pub fn resolve(config: &Config) -> Binding {/// Memory is off for `config`, or an embedding host's (or a test's)/// installed engine is bound, which has one layout of its own and cannot be/// bound below a scope root.-pub fn bind_with_root(config: &Config, root: Option<&str>) -> MemoryResult<BoundEngine> {+pub fn bind_with_root(config: &Config, root: Option<&str>) -> Result<BoundEngine> {if !config.components.memory {- return Err(MemoryError::Off(COMPONENT_OFF_REASON.to_string()));+ return Err(Error::Off(COMPONENT_OFF_REASON.to_string()));}#[cfg(test)]{@@ -305,7 +305,7 @@ pub fn bind_with_root(config: &Config, root: Option<&str>) -> MemoryResult<Boundif one_engine {return match root {None => resolve(config).engine(),- Some(_) => Err(MemoryError::Engine(+ Some(_) => Err(Error::Engine("the installed test engine cannot be bound below a scope root".to_string(),)),};@@ -332,14 +332,14 @@ pub(crate) fn host_binding_with<T>(saas: bool,host: Option<T>,root: Option<&str>,-) -> MemoryResult<Option<T>> {+) -> Result<Option<T>> {let host = if admits_host_engine_with(saas) {host} else {None};if host.is_some() && root.is_some() {- return Err(MemoryError::Engine(+ return Err(Error::Engine("the host's memory engine cannot be bound below a scope root".to_string(),));}@@ -627,10 +627,10 @@ pub fn read_cortexdb_key(config: &Config) -> anyhow::Result<Option<String>> {}/// Stores the CortexDB API key in the credential store (never in config).-pub fn store_cortexdb_key(config: &Config, key: &str) -> MemoryResult<()> {+pub fn store_cortexdb_key(config: &Config, key: &str) -> Result<()> {let key = key.trim();if key.is_empty() {- return Err(MemoryError::invalid("the API key is blank"));+ return Err(Error::invalid("the API key is blank"));}AuthService::from_config(config).store_provider_token(@@ -640,16 +640,16 @@ pub fn store_cortexdb_key(config: &Config, key: &str) -> MemoryResult<()> {HashMap::new(),true,)- .map_err(|error| MemoryError::Engine(format!("storing the API key failed: {error}")))?;+ .map_err(|error| Error::Engine(format!("storing the API key failed: {error}")))?;tracing::debug!("[memory:engine] cortexdb key stored");Ok(())}/// Removes the stored CortexDB API key.-pub fn clear_cortexdb_key(config: &Config) -> MemoryResult<bool> {+pub fn clear_cortexdb_key(config: &Config) -> Result<bool> {AuthService::from_config(config).remove_profile(MEMORY_CORTEXDB_KEY_NAME, DEFAULT_AUTH_PROFILE_NAME)- .map_err(|error| MemoryError::Engine(format!("removing the API key failed: {error}")))+ .map_err(|error| Error::Engine(format!("removing the API key failed: {error}")))}/// Whether the engine `id` has a credential available.diff --git a/crates/openhuman-core/src/memory/engine_tests.rs b/crates/openhuman-core/src/memory/engine_tests.rsindex e4de716b10..6822007568 100644--- a/crates/openhuman-core/src/memory/engine_tests.rs+++ b/crates/openhuman-core/src/memory/engine_tests.rs@@ -423,7 +423,7 @@ fn a_disabled_memory_component_binds_no_engine() {assert!(switched_off(&config));assert!(matches!(bind_with_root(&config, None),- Err(MemoryError::Off(_))+ Err(Error::Off(_))));}diff --git a/crates/openhuman-core/src/memory/error.rs b/crates/openhuman-core/src/memory/error.rsindex cb6e3d5862..fab30a3017 100644--- a/crates/openhuman-core/src/memory/error.rs+++ b/crates/openhuman-core/src/memory/error.rs@@ -30,7 +30,7 @@ pub const ENGINE: &str = "ENGINE";/// A memory operation failure.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]-pub enum MemoryError {+pub enum Error {/// Memory is off: no usable engine.#[error("memory is off: {0}")]Off(String),@@ -54,7 +54,7 @@ pub enum MemoryError {Engine(String),}-impl MemoryError {+impl Error {/// The stable wire code.#[must_use]pub fn code(&self) -> &'static str {@@ -101,7 +101,7 @@ impl MemoryError {}}-impl From<tinymemory_api::Error> for MemoryError {+impl From<tinymemory_api::Error> for Error {fn from(error: tinymemory_api::Error) -> Self {use tinymemory_api::Error as E;// A 402 arrives as `Engine` with the backend's code on its message.@@ -118,7 +118,7 @@ impl From<tinymemory_api::Error> for MemoryError {}}-impl MemoryError {+impl Error {/// The account-wide refusal behind a recall section's skip reason, if it/// was one.///@@ -142,14 +142,14 @@ impl MemoryError {}}-impl From<MemoryError> for String {- fn from(error: MemoryError) -> Self {+impl From<Error> for String {+ fn from(error: Error) -> Self {error.to_structured().encode()}}/// Result alias for memory operations.-pub type MemoryResult<T> = Result<T, MemoryError>;+pub type Result<T> = Result<T, Error>;#[cfg(test)]#[path = "error_tests.rs"]diff --git a/crates/openhuman-core/src/memory/explore.rs b/crates/openhuman-core/src/memory/explore.rsindex c10fe2cfe1..f36a9418d1 100644--- a/crates/openhuman-core/src/memory/explore.rs+++ b/crates/openhuman-core/src/memory/explore.rs@@ -18,7 +18,7 @@ use tinymemory_api::{ExplorePage, ExploreRequest, Facet, GetRequest, Hit, ItemIduse crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};/// Default bucket count of `memory_explore`.pub const DEFAULT_BUCKETS: usize = 50;@@ -75,11 +75,11 @@ pub struct ItemsGetView {////// # Errors///-/// [`MemoryError::invalid`] for a path that is too long or a step whose+/// [`Error::invalid`] for a path that is too long or a step whose/// value the facet cannot take (blank, or an unknown kind).-pub fn narrowed(filter: Option<MetaFilter>, path: &[PathStep]) -> MemoryResult<MetaFilter> {+pub fn narrowed(filter: Option<MetaFilter>, path: &[PathStep]) -> Result<MetaFilter> {if path.len() > MAX_PATH_STEPS {- return Err(MemoryError::invalid(format!(+ return Err(Error::invalid(format!("an explorer path takes at most {MAX_PATH_STEPS} steps")));}@@ -91,7 +91,7 @@ pub fn narrowed(filter: Option<MetaFilter>, path: &[PathStep]) -> MemoryResult<M}/// `memory_explore`.-pub async fn explore(config: &Config, params: ExploreParams) -> MemoryResult<ExplorePage> {+pub async fn explore(config: &Config, params: ExploreParams) -> Result<ExplorePage> {let bound = engine::resolve(config).engine()?;let mut request = ExploreRequest::new(params.facet, params.limit.unwrap_or(DEFAULT_BUCKETS));request.filter = super::ops::confine_filter(config, narrowed(params.filter, ¶ms.path)?)?;@@ -113,7 +113,7 @@ pub async fn explore(config: &Config, params: ExploreParams) -> MemoryResult<Exp}/// `memory_items_get`.-pub async fn items_get(config: &Config, params: ItemsGetParams) -> MemoryResult<ItemsGetView> {+pub async fn items_get(config: &Config, params: ItemsGetParams) -> Result<ItemsGetView> {let bound = engine::resolve(config).engine()?;let request = GetRequest {ids: params.ids.into_iter().map(ItemId::new).collect(),diff --git a/crates/openhuman-core/src/memory/guard.rs b/crates/openhuman-core/src/memory/guard.rsindex 40da0e01d8..7461254b1c 100644--- a/crates/openhuman-core/src/memory/guard.rs+++ b/crates/openhuman-core/src/memory/guard.rs@@ -24,7 +24,7 @@ use tinymemory_api::{Reach, RecallAnswer, RecallRequest, Result, StoreItem, StoreReceipt, WaitFor, WriteOptions,};-use super::error::MemoryError;+use super::error::Error;/// `inner` with every stored item scrubbed first, and every call timed.pub struct ScrubbingEngine {@@ -68,7 +68,7 @@ impl ScrubbingEngine {fn outcome<T>(result: &Result<T>) -> &'static str {match result {Ok(_) => "ok",- Err(error) => MemoryError::from(error.clone()).code(),+ Err(error) => Error::from(error.clone()).code(),}}diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rsindex 24ebe6e472..9f3a8b833c 100644--- a/crates/openhuman-core/src/memory/import.rs+++ b/crates/openhuman-core/src/memory/import.rs@@ -21,7 +21,7 @@ use crate::config::Config;use crate::security::secret_storage::file_store::write_atomic;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::types::{ImportCounts, ImportScanView};/// Whether background work is paused right now. An automatic resume asks@@ -104,8 +104,8 @@ pub(crate) fn listed_unconfirmed(workspace_dir: &Path) -> bool {read_file(workspace_dir).listed_unconfirmed}-fn import_error(error: &ImportError) -> MemoryError {- MemoryError::invalid(error.to_string())+fn import_error(error: &ImportError) -> Error {+ Error::invalid(error.to_string())}fn importer(@@ -122,7 +122,7 @@ fn importer(Arc::new(move || consent),).with_describe(Arc::new(|error| {- MemoryError::from(error.clone()).to_string()+ Error::from(error.clone()).to_string()}));if let Some(paused) = paused {importer = importer.with_pause(paused);@@ -131,13 +131,13 @@ fn importer(}/// `memory_import_scan`.-pub async fn scan(config: &Config) -> MemoryResult<ImportScanView> {+pub async fn scan(config: &Config) -> Result<ImportScanView> {let workspace_dir = config.workspace_dir.clone();let counts = tokio::task::spawn_blocking(move || {tinymemory_integrations::import::count_legacy(&workspace_dir)}).await- .map_err(|error| MemoryError::Engine(format!("import scan failed: {error}")))?;+ .map_err(|error| Error::Engine(format!("import scan failed: {error}")))?;let counts = counts.map(|counts: LegacyImportCounts| ImportCounts {documents: counts.documents,conversations: counts.conversations,@@ -275,7 +275,7 @@ pub async fn start(ctx: &crate::core::runtime::DispatchCtx,config: &Config,consent: bool,-) -> MemoryResult<ImportState> {+) -> Result<ImportState> {launch(ctx, config, Mode::Import, consent, None).await}@@ -284,7 +284,7 @@ pub async fn start(pub async fn retry_failed(ctx: &crate::core::runtime::DispatchCtx,config: &Config,-) -> MemoryResult<ImportState> {+) -> Result<ImportState> {launch(ctx, config, Mode::Retry, true, None).await}@@ -302,7 +302,7 @@ async fn launch(mode: Mode,consent: bool,paused: Option<PauseCheck>,-) -> MemoryResult<ImportState> {+) -> Result<ImportState> {if mode == Mode::Import && !consent {return Err(import_error(&ImportError::ConsentRequired));}@@ -315,7 +315,7 @@ async fn launch(// Items written to the legacy tree while it is being moved would be// left behind there.if super::layout_migration::service::is_running(config) {- return Err(MemoryError::invalid(if mode == Mode::Import {+ return Err(Error::invalid(if mode == Mode::Import {"memory is being organized; import once that finishes"} else {"memory is being organized; retry once that finishes"@@ -347,7 +347,7 @@ async fn launch(}Err(error) => {release(&workspace_dir);- return Err(MemoryError::Engine(format!("import start failed: {error}")));+ return Err(Error::Engine(format!("import start failed: {error}")));}};let state = begun.state.clone();diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rsindex 06107ad20c..fef9e22c98 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs@@ -12,7 +12,7 @@ use super::claim::ClaimKey;use super::state::FileStateStore;use crate::config::{Config, MemoryLayoutMode};use crate::memory::engine::{self, CORTEXDB_ENGINE};-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};use crate::memory::scope::{self, MemoryIdentity};/// The app's [`lm::LayoutHost`], bound to one account's config.@@ -37,28 +37,28 @@ const RECHECK_DELAY: std::time::Duration = std::time::Duration::from_secs(45);const RECHECK_DELAY: std::time::Duration = std::time::Duration::from_millis(300);/// The host's error as the module's: the engine's variants keep their codes.-pub(super) fn to_module(error: MemoryError) -> lm::Error {+pub(super) fn to_module(error: Error) -> lm::Error {match error {- MemoryError::Off(message) => lm::Error::Off(message),- MemoryError::InvalidRequest(message) => lm::Error::InvalidRequest(message),- MemoryError::Unsupported(message) => EngineError::Unsupported(message).into(),- MemoryError::Unauthorized(message) => EngineError::Unauthorized(message).into(),- MemoryError::Unavailable(message) => EngineError::Unavailable(message).into(),+ Error::Off(message) => lm::Error::Off(message),+ Error::InvalidRequest(message) => lm::Error::InvalidRequest(message),+ Error::Unsupported(message) => EngineError::Unsupported(message).into(),+ Error::Unauthorized(message) => EngineError::Unauthorized(message).into(),+ Error::Unavailable(message) => EngineError::Unavailable(message).into(),// The backend's `[CODE] ` prefix stays on the message, which is how// the module tells an exhausted balance.- MemoryError::InsufficientCredits(message) | MemoryError::Engine(message) => {+ Error::InsufficientCredits(message) | Error::Engine(message) => {EngineError::Engine(message).into()}}}/// The module's error as the host's wire taxonomy.-pub(super) fn from_module(error: lm::Error) -> MemoryError {+pub(super) fn from_module(error: lm::Error) -> Error {match error {lm::Error::Engine(error) => error.into(),- lm::Error::Off(message) => MemoryError::Off(message),- lm::Error::InvalidRequest(message) => MemoryError::InvalidRequest(message),- lm::Error::State(message) => MemoryError::Engine(message),+ lm::Error::Off(message) => Error::Off(message),+ lm::Error::InvalidRequest(message) => Error::InvalidRequest(message),+ lm::Error::State(message) => Error::Engine(message),}}@@ -70,7 +70,7 @@ impl lm::LayoutHost for AppHost {fn engines(&self) -> lm::Result<Engines> {let config = &self.config;- let bind = || -> MemoryResult<Engines> {+ let bind = || -> Result<Engines> {let root = signed_in_root(config)?;Ok(Engines {legacy: engine::bind_with_root(config, None)?.engine,@@ -126,7 +126,7 @@ impl lm::LayoutHost for AppHost {/// The claim on the legacy tree `config`'s account would move, if it is/// shared by every account on the machine.-pub(super) fn claim_key(config: &Config) -> MemoryResult<Option<ClaimKey>> {+pub(super) fn claim_key(config: &Config) -> Result<Option<ClaimKey>> {// A self-hosted key is the operator's: every local account using it// shares one legacy tree. The hosted engine is one tenant per person.if config.memory.engine.trim() != CORTEXDB_ENGINE {@@ -146,12 +146,12 @@ pub(super) fn claim_key(config: &Config) -> MemoryResult<Option<ClaimKey>> {Ok(Some(ClaimKey::new(app_dir, &endpoint, &owner)))}-fn signed_in_root(config: &Config) -> MemoryResult<String> {+fn signed_in_root(config: &Config) -> Result<String> {scope::user_root(config).ok_or_else(signed_out)}-fn signed_out() -> MemoryError {- MemoryError::Off("sign in to move memory into its own layout".to_string())+fn signed_out() -> Error {+ Error::Off("sign in to move memory into its own layout".to_string())}#[cfg(test)]diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rsindex bc4006ee83..0227663db7 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs@@ -176,13 +176,13 @@ async fn a_shared_tree_reaches_the_module_as_a_claim() {#[test]fn errors_keep_their_wire_codes_across_the_module_boundary() {for error in [- MemoryError::Off("x".into()),- MemoryError::Unsupported("x".into()),- MemoryError::invalid("x"),- MemoryError::Unauthorized("x".into()),- MemoryError::Unavailable("x".into()),- MemoryError::InsufficientCredits("[USER_INSUFFICIENT_CREDITS] x".into()),- MemoryError::Engine("x".into()),+ Error::Off("x".into()),+ Error::Unsupported("x".into()),+ Error::invalid("x"),+ Error::Unauthorized("x".into()),+ Error::Unavailable("x".into()),+ Error::InsufficientCredits("[USER_INSUFFICIENT_CREDITS] x".into()),+ Error::Engine("x".into()),] {let back = from_module(to_module(error.clone()));assert_eq!(back.code(), error.code(), "{error:?}");diff --git a/crates/openhuman-core/src/memory/layout_migration/claim.rs b/crates/openhuman-core/src/memory/layout_migration/claim.rsindex 7987629c6d..5b54cebaad 100644--- a/crates/openhuman-core/src/memory/layout_migration/claim.rs+++ b/crates/openhuman-core/src/memory/layout_migration/claim.rs@@ -16,7 +16,7 @@ use sha2::Digest;use tinymemory_tools::layout_migration::{LegacyClaim, Result as ModuleResult};use super::app_host::to_module;-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};/// Where a legacy tree's marker lives and who would own it.#[derive(Debug, Clone, PartialEq, Eq)]@@ -70,7 +70,7 @@ fn normalize(endpoint: &str) -> String {/// # Errors////// When the marker exists but cannot be read.-fn owner(key: &ClaimKey) -> MemoryResult<Option<String>> {+fn owner(key: &ClaimKey) -> Result<Option<String>> {match std::fs::read(&key.marker) {Ok(bytes) => serde_json::from_slice::<Marker>(&bytes).map(|marker| Some(marker.owner))@@ -85,7 +85,7 @@ fn owner(key: &ClaimKey) -> MemoryResult<Option<String>> {/// # Errors////// When the marker exists but cannot be read.-pub fn held_by_other(key: &ClaimKey) -> MemoryResult<bool> {+pub fn held_by_other(key: &ClaimKey) -> Result<bool> {Ok(owner(key)?.is_some_and(|owner| owner != key.owner))}@@ -95,7 +95,7 @@ pub fn held_by_other(key: &ClaimKey) -> MemoryResult<bool> {/// # Errors////// When the marker cannot be read or written.-pub fn take(key: &ClaimKey) -> MemoryResult<bool> {+pub fn take(key: &ClaimKey) -> Result<bool> {if let Some(owner) = owner(key)? {return Ok(owner == key.owner);}@@ -121,7 +121,7 @@ pub fn take(key: &ClaimKey) -> MemoryResult<bool> {Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {Ok(owner(key)?.is_some_and(|owner| owner == key.owner))}- Err(error) => Err(MemoryError::Engine(format!(+ Err(error) => Err(Error::Engine(format!("legacy tree claim not saved: {error}"))),}@@ -137,8 +137,8 @@ impl LegacyClaim for ClaimKey {}}-fn unreadable(error: &dyn std::fmt::Display) -> MemoryError {- MemoryError::Engine(format!("legacy tree claim unreadable: {error}"))+fn unreadable(error: &dyn std::fmt::Display) -> Error {+ Error::Engine(format!("legacy tree claim unreadable: {error}"))}#[cfg(test)]diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rsindex 005596e337..635e16153c 100644--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs@@ -9,9 +9,9 @@//! placement, the layout switch, the free period), with [`claim`] naming the//! account that takes a legacy tree several accounts share.//! - [`service`]: running in the background (one run per workspace, gated on-//! the import) and mapping the module's errors to [`MemoryError`].+//! the import) and mapping the module's errors to [`Error`].//!-//! [`MemoryError`]: crate::memory::error::MemoryError+//! [`Error`]: crate::memory::error::Errorpub mod app_host;pub mod claim;diff --git a/crates/openhuman-core/src/memory/layout_migration/service.rs b/crates/openhuman-core/src/memory/layout_migration/service.rsindex e08b4bc975..724488d6c4 100644--- a/crates/openhuman-core/src/memory/layout_migration/service.rs+++ b/crates/openhuman-core/src/memory/layout_migration/service.rs@@ -23,7 +23,7 @@ use tinymemory_tools::layout_migration as lm;use super::app_host::{from_module, AppHost};use super::{LayoutHost, MigrationState, MigrationStatus, ScanView, Trigger};use crate::config::Config;-use crate::memory::error::MemoryResult;+use crate::memory::error::Result;/// Workspaces with a migration running now.static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));@@ -42,7 +42,7 @@ pub struct StartParams {////// When the state cannot be read, the engines cannot be bound, or the legacy/// tree cannot be read.-pub async fn scan(host: &dyn LayoutHost) -> MemoryResult<ScanView> {+pub async fn scan(host: &dyn LayoutHost) -> Result<ScanView> {lm::scan(host).await.map_err(from_module)}@@ -51,7 +51,7 @@ pub async fn scan(host: &dyn LayoutHost) -> MemoryResult<ScanView> {/// # Errors////// When the state file cannot be read.-pub fn status(config: &Config) -> MemoryResult<MigrationStatus> {+pub fn status(config: &Config) -> Result<MigrationStatus> {lm::status(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)}@@ -126,7 +126,7 @@ pub fn start(/// # Errors////// When the state cannot be read or saved, or a run is going now.-pub fn retry(config: &Config) -> MemoryResult<MigrationState> {+pub fn retry(config: &Config) -> Result<MigrationState> {lm::retry(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)}diff --git a/crates/openhuman-core/src/memory/layout_migration/state.rs b/crates/openhuman-core/src/memory/layout_migration/state.rsindex a534a5b2ee..1cad056b75 100644--- a/crates/openhuman-core/src/memory/layout_migration/state.rs+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};use tinymemory_tools::layout_migration::{Error, Result};use super::{MigrationState, MigrationStateStore};-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};/// The state file of `workspace_dir`.#[must_use]@@ -43,9 +43,9 @@ impl MigrationStateStore for FileStateStore {}}-fn detail(error: MemoryError) -> String {+fn detail(error: Error) -> String {match error {- MemoryError::Engine(message) => message,+ Error::Engine(message) => message,other => other.to_string(),}}@@ -56,14 +56,14 @@ fn detail(error: MemoryError) -> String {////// A state file that cannot be read or parsed: the migration must not start/// over and copy everything again on a damaged file.-pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {+pub fn load(workspace_dir: &Path) -> Result<MigrationState> {let file = path(workspace_dir);match std::fs::read(&file) {Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {- MemoryError::Engine(format!("layout migration state unreadable: {error}"))+ Error::Engine(format!("layout migration state unreadable: {error}"))}),Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(MigrationState::default()),- Err(error) => Err(MemoryError::Engine(format!(+ Err(error) => Err(Error::Engine(format!("layout migration state unreadable: {error}"))),}@@ -74,7 +74,7 @@ pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {/// # Errors////// When the file cannot be written.-pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {+pub fn save(workspace_dir: &Path, state: &MigrationState) -> Result<()> {let file = path(workspace_dir);let write = || -> std::io::Result<()> {if let Some(dir) = file.parent() {@@ -88,7 +88,7 @@ pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {std::fs::rename(&temp, &file)};write()- .map_err(|error| MemoryError::Engine(format!("layout migration state not saved: {error}")))+ .map_err(|error| Error::Engine(format!("layout migration state not saved: {error}")))}#[cfg(test)]diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex 3916f723bc..c09901947e 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -20,7 +20,7 @@ use tinymemory_tools::{Compaction, ContextPack, PostTurn, PreTurn, SessionStart}use crate::config::Config;use crate::memory::engine;-use crate::memory::error::MemoryError;+use crate::memory::error::Error;use crate::memory::scope::ResolvedIdentity;use super::{agent_memory_on, jobs, log_only};@@ -54,7 +54,7 @@ pub struct TurnPack {#[serde(skip)]pub citations: Vec<crate::web_chat::TurnCitation>,/// Set when nothing was recalled because the engine refused the whole- /// account (a `MemoryError` code such as `INSUFFICIENT_CREDITS`): the+ /// account (a `Error` code such as `INSUFFICIENT_CREDITS`): the/// block is then a notice saying so, not recalled memory.#[serde(skip_serializing_if = "Option::is_none")]pub refusal: Option<&'static str>,@@ -85,13 +85,13 @@ impl TurnPack {/// The notice a turn is given when its recall was refused outright, so/// the model does not read an empty pack as "nothing is stored" and tell/// the user so (#6718). `None` for a failure that is not account-wide.- fn refused(error: &MemoryError, engine: String) -> Option<Self> {+ fn refused(error: &Error, engine: String) -> Option<Self> {let why = match error {- MemoryError::InsufficientCredits(_) => {+ Error::InsufficientCredits(_) => {"the account is out of credits; topping up restores it"}- MemoryError::Unauthorized(_) => "the memory engine rejected the sign-in or API key",- MemoryError::Unavailable(_) => "the memory engine could not be reached",+ Error::Unauthorized(_) => "the memory engine rejected the sign-in or API key",+ Error::Unavailable(_) => "the memory engine could not be reached",_ => return None,};let markdown = format!(@@ -247,7 +247,7 @@ pub(crate) async fn pre_turn_work(}Err(error) => {tracing::warn!(%error, "[memory:hooks] pre_turn refused");- Err(MemoryError::from(error))+ Err(Error::from(error))}}} else if resumed {@@ -259,12 +259,12 @@ pub(crate) async fn pre_turn_work(.await.map_err(|error| {tracing::warn!(%error, "[memory:hooks] recall failed");- MemoryError::from(error)+ Error::from(error)})} else {memory.recall(&user_text).await.map_err(|error| {tracing::warn!(%error, "[memory:hooks] recall failed");- MemoryError::from(error)+ Error::from(error)})}}@@ -294,7 +294,7 @@ pub(crate) async fn pre_turn_work(/// The account-wide refusal behind a recall that came back empty, if any:/// the first refusing error, else the first refusing skipped section.-fn refusal_of(outcomes: &[Result<ContextPack, MemoryError>]) -> Option<MemoryError> {+fn refusal_of(outcomes: &[Result<ContextPack, Error>]) -> Option<Error> {let failed = outcomes.iter().find_map(|outcome| {outcome.as_ref()@@ -307,7 +307,7 @@ fn refusal_of(outcomes: &[Result<ContextPack, MemoryError>]) -> Option<MemoryErr.iter().filter_map(|outcome| outcome.as_ref().ok()).flat_map(|pack| pack.skipped.iter())- .find_map(|skipped| MemoryError::refusal_from_skip_reason(&skipped.reason))+ .find_map(|skipped| Error::refusal_from_skip_reason(&skipped.reason))})}diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rsindex a0a9a06ec3..8df3e6af11 100644--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs@@ -29,7 +29,7 @@ use tinymemory_tools::queue::{JobRun, Selection};use crate::config::Config;use crate::memory::engine;-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};/// The cron job that runs the queue.pub const BACKGROUND_JOB: &str = "memory_background";@@ -111,7 +111,7 @@ pub async fn snapshot(config: &Config) -> QueueState {/// Runs the selected jobs on the configured engine. Returns the runs it/// recorded; see `tinymemory_tools::queue::JobQueue::run` for the retry rules.-pub async fn run(config: &Config, selection: Selection) -> MemoryResult<Vec<JobRun>> {+pub async fn run(config: &Config, selection: Selection) -> Result<Vec<JobRun>> {let bound = engine::resolve(config).engine()?;queue_of(&config.workspace_dir).run(@@ -121,7 +121,7 @@ pub async fn run(config: &Config, selection: Selection) -> MemoryResult<Vec<JobR).await.map_err(|error| match error {- QueueError::NoSuchJob(_) => MemoryError::invalid(error.to_string()),+ QueueError::NoSuchJob(_) => Error::invalid(error.to_string()),})}@@ -141,7 +141,7 @@ pub async fn run_due(config: &Config) {tracing::debug!(ran = runs.len(), "[memory:jobs] background run finished");}Ok(_) => {}- Err(MemoryError::Off(_)) => {}+ Err(Error::Off(_)) => {}Err(error) => tracing::warn!(%error, "[memory:jobs] background run failed"),}}diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rsindex f7999b25d4..749431e52a 100644--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs@@ -111,7 +111,7 @@ async fn one_job_runs_by_id_and_an_unknown_id_is_refused() {assert_eq!(snapshot(&config).await.pending.len(), 1);assert!(matches!(run(&config, Selection::One("nope".into())).await,- Err(MemoryError::InvalidRequest(_))+ Err(Error::InvalidRequest(_))));assert_eq!(snapshot(&config).await.pending.len(),@@ -127,7 +127,7 @@ async fn a_run_needs_an_engine() {enqueue(&config, &Namespace::ROOT, vec![build("a")]).await;assert!(matches!(run(&config, Selection::All).await,- Err(MemoryError::Off(_))+ Err(Error::Off(_))));run_due(&config).await;assert_eq!(snapshot(&config).await.pending.len(), 1);diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rsindex 0937e9add2..292cb8ef17 100644--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs@@ -32,7 +32,7 @@ use crate::config::schema::MemoryRecallConfig;use crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::scope::ResolvedIdentity;/// TinyMemory's recall policy from `[memory.recall]`.@@ -66,16 +66,16 @@ pub fn agent_memory_on(engine: Arc<dyn MemoryEngine>,config: &Config,identity: &ResolvedIdentity,-) -> MemoryResult<AgentMemory> {+) -> Result<AgentMemory> {Ok(AgentMemory::new(engine, identity.layout.clone(), &identity.agent_id)?.with_policy(policy(&config.memory.recall)),)}-/// `identity`'s memory on the configured engine; [`MemoryError::Off`] when no+/// `identity`'s memory on the configured engine; [`Error::Off`] when no/// engine is bound.-pub fn agent_memory(config: &Config, identity: &ResolvedIdentity) -> MemoryResult<AgentMemory> {+pub fn agent_memory(config: &Config, identity: &ResolvedIdentity) -> Result<AgentMemory> {let bound = engine::resolve(config).engine()?;agent_memory_on(bound.engine, config, identity)}@@ -84,7 +84,7 @@ pub fn agent_memory(config: &Config, identity: &ResolvedIdentity) -> MemoryResulpub fn current_agent_memory(config: &Config,identity: &super::scope::MemoryIdentity,-) -> MemoryResult<(AgentMemory, ResolvedIdentity)> {+) -> Result<(AgentMemory, ResolvedIdentity)> {let identity = identity.resolve(config);let memory = agent_memory(config, &identity)?;Ok((memory, identity))@@ -96,14 +96,14 @@ pub fn named_agent_memory(config: &Config,identity: &super::scope::MemoryIdentity,agent_id: Option<&str>,-) -> MemoryResult<(AgentMemory, ResolvedIdentity)> {+) -> Result<(AgentMemory, ResolvedIdentity)> {let mut identity = identity.resolve(config);if let Some(agent_id) = agent_id.map(str::trim).filter(|id| !id.is_empty()) {identity.agent_id = agent_id.to_string();}let memory = agent_memory(config, &identity).map_err(|error| match error {- MemoryError::InvalidRequest(message) => {- MemoryError::invalid(format!("agent `{}`: {message}", identity.agent_id))+ Error::InvalidRequest(message) => {+ Error::invalid(format!("agent `{}`: {message}", identity.agent_id))}other => other,})?;diff --git a/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs b/crates/openhuman-core/src/memory/lifecycle/mod_tests.rsindex 9f6a6ffd04..274b191e3c 100644--- a/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/mod_tests.rs@@ -44,7 +44,7 @@ async fn agent_memory_needs_an_engine_and_follows_the_identity() {let identity = MemoryIdentity::team_member("acme", "writer").resolve(&config);assert!(matches!(agent_memory(&config, &identity),- Err(MemoryError::Off(_))+ Err(Error::Off(_))));bind_reference(&config);diff --git a/crates/openhuman-core/src/memory/lifecycle/views.rs b/crates/openhuman-core/src/memory/lifecycle/views.rsindex 8221e86e29..e6abb5c021 100644--- a/crates/openhuman-core/src/memory/lifecycle/views.rs+++ b/crates/openhuman-core/src/memory/lifecycle/views.rs@@ -7,7 +7,7 @@ use tinymemory_tools::{ContextPack, SessionStart};use crate::config::schema::MemoryRecallConfig;use crate::config::Config;-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};use crate::memory::scope::{self, MemoryIdentity};use super::jobs;@@ -89,9 +89,9 @@ fn within<T: PartialOrd + std::fmt::Display + Copy>(value: Option<T>,min: T,max: T,-) -> MemoryResult<Option<T>> {+) -> Result<Option<T>> {match value {- Some(value) if value < min || value > max => Err(MemoryError::invalid(format!(+ Some(value) if value < min || value > max => Err(Error::invalid(format!("{name} must be between {min} and {max}"))),other => Ok(other),@@ -99,7 +99,7 @@ fn within<T: PartialOrd + std::fmt::Display + Copy>(}/// Applies `params` to `config`; the caller persists it.-pub fn apply_policy_set(config: &mut Config, params: &PolicySetParams) -> MemoryResult<()> {+pub fn apply_policy_set(config: &mut Config, params: &PolicySetParams) -> Result<()> {// Validate every value before changing the config. Callers may use this// function directly, without a persistence layer to discard partial edits.let budget_tokens = within("budget_tokens", params.budget_tokens, 100, 16_000)?;@@ -157,7 +157,7 @@ pub fn apply_policy_set(config: &mut Config, params: &PolicySetParams) -> MemoryOk(())}-fn validate_build_delay_secs(value: Option<u64>) -> MemoryResult<Option<u64>> {+fn validate_build_delay_secs(value: Option<u64>) -> Result<Option<u64>> {let Some(seconds) = value else {return Ok(None);};@@ -168,7 +168,7 @@ fn validate_build_delay_secs(value: Option<u64>) -> MemoryResult<Option<u64>> {.and_then(|delay| chrono::Utc::now().checked_sub_signed(delay)).is_none(){- return Err(MemoryError::invalid(+ return Err(Error::invalid("build_delay_secs must fit within the supported date range",));}@@ -208,7 +208,7 @@ pub async fn pack_preview(config: &Config,identity: &MemoryIdentity,params: PackPreviewParams,-) -> MemoryResult<PackPreviewView> {+) -> Result<PackPreviewView> {let (memory, identity) =super::named_agent_memory(config, identity, params.agent_id.as_deref())?;let query = params.query.filter(|query| !query.trim().is_empty());@@ -252,7 +252,7 @@ pub struct AgentsView {}/// `memory_agents_list`: the agents with conversations under the root.-pub async fn agents_list(config: &Config, identity: &MemoryIdentity) -> MemoryResult<AgentsView> {+pub async fn agents_list(config: &Config, identity: &MemoryIdentity) -> Result<AgentsView> {let (memory, identity) = super::current_agent_memory(config, identity)?;let page = memory.engine()@@ -301,7 +301,7 @@ pub struct JobsRunView {}/// `memory_jobs_run`: runs now, ignoring the build delay.-pub async fn jobs_run(config: &Config, params: JobsRunParams) -> MemoryResult<JobsRunView> {+pub async fn jobs_run(config: &Config, params: JobsRunParams) -> Result<JobsRunView> {Ok(JobsRunView {runs: jobs::run(config,diff --git a/crates/openhuman-core/src/memory/lifecycle/views_tests.rs b/crates/openhuman-core/src/memory/lifecycle/views_tests.rsindex aff0a1b7e6..1202682ca9 100644--- a/crates/openhuman-core/src/memory/lifecycle/views_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/views_tests.rs@@ -97,7 +97,7 @@ fn the_policy_round_trips_and_refuses_out_of_range_values() {..bad},);- assert!(matches!(result, Err(MemoryError::InvalidRequest(_))));+ assert!(matches!(result, Err(Error::InvalidRequest(_))));assert!(serde_json::to_value(&config).unwrap() == before,"invalid policy update must be atomic"diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rsindex 2004d8f3c4..fc7f08f4a2 100644--- a/crates/openhuman-core/src/memory/mod.rs+++ b/crates/openhuman-core/src/memory/mod.rs@@ -51,7 +51,7 @@ pub(crate) mod test_fixtures;pub use bus::register_memory_subscribers;pub use engine::is_on as memory_is_on;-pub use error::{MemoryError, MemoryResult};+pub use error::{Error, Result};pub use schemas::{all_controller_schemas as all_memory_controller_schemas,all_registered_controllers as all_memory_registered_controllers,diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rsindex cb0152a560..c8f238fb5d 100644--- a/crates/openhuman-core/src/memory/ops.rs+++ b/crates/openhuman-core/src/memory/ops.rs@@ -18,7 +18,7 @@ use crate::config::Config;use super::engine::{self, Binding, BoundEngine, CORTEXDB_ENGINE, DISABLED_ENGINE, TINYHUMANS_ENGINE,};-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::types::{clamp_limit, EngineSetParams, EngineStatus, EngineView, EnginesListView, EraseAllParams,EraseAllView, FetchParams, FetchView, ForgetParams, ForgetView, ItemsListParams, ItemsListView,@@ -86,13 +86,13 @@ pub async fn engine_get(config: &Config) -> EngineView {/// Applies `memory_engine_set` to `config` in memory (and to the credential/// store for a key). The caller persists `config`.-pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> MemoryResult<()> {+pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Result<()> {let engine_id = params.engine.trim();if engine_id == DISABLED_ENGINE {// Turning memory off keeps every engine's endpoint and key, so// switching back needs no re-entry.if params.endpoint.is_some() || params.api_key.is_some() {- return Err(MemoryError::invalid(+ return Err(Error::invalid("disabling memory takes no endpoint or API key",));}@@ -104,7 +104,7 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Memory.iter().any(|descriptor| descriptor.id == engine_id){- return Err(MemoryError::invalid(format!(+ return Err(Error::invalid(format!("unknown memory engine `{engine_id}`")));}@@ -129,11 +129,11 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Memory}CORTEXDB_ENGINE => engine::store_cortexdb_key(config, key)?,TINYHUMANS_ENGINE => {- return Err(MemoryError::invalid(+ return Err(Error::invalid("the tinyhumans engine uses your sign-in, not an API key",))}- _ => return Err(MemoryError::invalid("this engine takes no API key")),+ _ => return Err(Error::invalid("this engine takes no API key")),}}config.memory.engine = engine_id.to_string();@@ -141,34 +141,34 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> MemoryOk(())}-fn validate_endpoint(endpoint: &str) -> MemoryResult<()> {+fn validate_endpoint(endpoint: &str) -> Result<()> {let parsed = url::Url::parse(endpoint)- .map_err(|_| MemoryError::invalid("the endpoint is not a valid URL"))?;+ .map_err(|_| Error::invalid("the endpoint is not a valid URL"))?;if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {- return Err(MemoryError::invalid(+ return Err(Error::invalid("the endpoint must be an http(s) URL with a host",));}Ok(())}-fn bound(config: &Config) -> MemoryResult<BoundEngine> {+fn bound(config: &Config) -> Result<BoundEngine> {engine::resolve(config).engine()}/// The [`TimeHint`] for `refers_to`, in the user's time zone/// ([`Config::time_zone`]).-fn time_hint(config: &Config, refers_to: Option<RefersTo>) -> MemoryResult<Option<TimeHint>> {+fn time_hint(config: &Config, refers_to: Option<RefersTo>) -> Result<Option<TimeHint>> {let Some(RefersTo { from, to }) = refers_to else {return Ok(None);};TimeHint::new(from, to.unwrap_or(from), Some(config.time_zone())).map(Some)- .map_err(MemoryError::from)+ .map_err(Error::from)}/// `memory_recall`.-pub async fn recall(config: &Config, params: RecallParams) -> MemoryResult<RecallView> {+pub async fn recall(config: &Config, params: RecallParams) -> Result<RecallView> {recall_with(config, params, RecallMode::Answer, None).await}@@ -181,7 +181,7 @@ pub async fn recall_with(params: RecallParams,mode: RecallMode,exclude_thread: Option<ThreadWindow>,-) -> MemoryResult<RecallView> {+) -> Result<RecallView> {let bound = bound(config)?;let request = RecallRequest {question: params.question,@@ -209,7 +209,7 @@ pub async fn recall_with(/// `memory_fetch`. An unset mode uses the engine's first declared mode; a/// mode the engine does not declare is `UNSUPPORTED`.-pub async fn fetch(config: &Config, params: FetchParams) -> MemoryResult<FetchView> {+pub async fn fetch(config: &Config, params: FetchParams) -> Result<FetchView> {fetch_with(config, params, None).await}@@ -218,7 +218,7 @@ pub async fn fetch_with(config: &Config,params: FetchParams,exclude_thread: Option<ThreadWindow>,-) -> MemoryResult<FetchView> {+) -> Result<FetchView> {let bound = bound(config)?;let descriptor = bound.engine.descriptor();let mode = match params.mode {@@ -229,7 +229,7 @@ pub async fn fetch_with(None => *descriptor.fetch_modes.first()- .ok_or_else(|| MemoryError::Unsupported("the engine offers no fetch mode".into()))?,+ .ok_or_else(|| Error::Unsupported("the engine offers no fetch mode".into()))?,};let request = FetchRequest {query: params.query,@@ -257,10 +257,10 @@ pub async fn fetch_with(pub fn learning_item(params: LearnParams,host_meta: Option<MemoryMeta>,-) -> MemoryResult<StoreItem> {+) -> Result<StoreItem> {let confidence = params.confidence.unwrap_or(DEFAULT_LEARNING_CONFIDENCE);if !(0.0..=1.0).contains(&confidence) {- return Err(MemoryError::invalid("confidence must be between 0 and 1"));+ return Err(Error::invalid("confidence must be between 0 and 1"));}let mut meta = params.meta.unwrap_or_default();if let Some(host) = host_meta {@@ -319,7 +319,7 @@ pub async fn learn(config: &Config,params: LearnParams,host_meta: Option<MemoryMeta>,-) -> MemoryResult<LearnView> {+) -> Result<LearnView> {learn_with(config, params, host_meta, WriteOptions::visible()).await}@@ -331,7 +331,7 @@ pub async fn learn_with(params: LearnParams,host_meta: Option<MemoryMeta>,options: WriteOptions,-) -> MemoryResult<LearnView> {+) -> Result<LearnView> {let mut item = learning_item(params, host_meta)?;// The same confinement as `store_item`: a SaaS user's learning lands in// their own tree whatever namespace it names.@@ -345,7 +345,7 @@ pub async fn learn_with(}/// Scrubs `item` and stores it on the bound engine.-pub async fn store_item(config: &Config, item: StoreItem) -> MemoryResult<StoreReceipt> {+pub async fn store_item(config: &Config, item: StoreItem) -> Result<StoreReceipt> {store_item_with(config, item, WriteOptions::visible()).await}@@ -356,7 +356,7 @@ pub async fn store_item_with(config: &Config,mut item: StoreItem,options: WriteOptions,-) -> MemoryResult<StoreReceipt> {+) -> Result<StoreReceipt> {if let Some(root) = super::user_scope::confinement(config)? {super::user_scope::clamp_item(&mut item, &root);}@@ -367,7 +367,7 @@ pub async fn store_item_with(}/// `memory_forget`.-pub async fn forget(config: &Config, params: ForgetParams) -> MemoryResult<ForgetView> {+pub async fn forget(config: &Config, params: ForgetParams) -> Result<ForgetView> {let ids: Vec<ItemId> = params.ids.into_iter()@@ -376,7 +376,7 @@ pub async fn forget(config: &Config, params: ForgetParams) -> MemoryResult<Forge.map(ItemId).collect();if ids.is_empty() {- return Err(MemoryError::invalid("forget needs at least one id"));+ return Err(Error::invalid("forget needs at least one id"));}let bound = bound(config)?;// A SaaS user forgets only what lies in their own tree.@@ -419,9 +419,9 @@ pub async fn erase_all(ctx: &crate::core::runtime::DispatchCtx,config: &Config,params: EraseAllParams,-) -> MemoryResult<EraseAllView> {+) -> Result<EraseAllView> {if !params.confirm {- return Err(MemoryError::invalid(+ return Err(Error::invalid("erasing all memory needs confirm: true; nothing erased comes back",));}@@ -437,7 +437,7 @@ pub async fn erase_all(tracing::info!(engine = %bound.id, "[memory:ops] erase_all: erasing the whole memory");let report = bound.engine.erase(request).await.map_err(|error| {tracing::warn!(engine = %bound.id, error = %error, "[memory:ops] erase_all failed");- MemoryError::from(error)+ Error::from(error)})?;tracing::info!(engine = %bound.id,@@ -456,7 +456,7 @@ async fn within_reach(bound: &BoundEngine,ids: Vec<ItemId>,reach: tinymemory_api::Reach,-) -> MemoryResult<Vec<ItemId>> {+) -> Result<Vec<ItemId>> {let mut kept = Vec::new();for chunk in ids.chunks(tinymemory_api::explore::MAX_GET_IDS) {let found = bound@@ -472,7 +472,7 @@ async fn within_reach(}/// `memory_items_list`.-pub async fn items_list(config: &Config, params: ItemsListParams) -> MemoryResult<ItemsListView> {+pub async fn items_list(config: &Config, params: ItemsListParams) -> Result<ItemsListView> {let bound = bound(config)?;let request = ListRequest {filter: confine_filter(@@ -496,7 +496,7 @@ pub async fn items_list(config: &Config, params: ItemsListParams) -> MemoryResul/// `filter`, confined to the SaaS user's tree when `config` has one/// ([`super::user_scope`]).-pub(crate) fn confine_filter(config: &Config, filter: MetaFilter) -> MemoryResult<MetaFilter> {+pub(crate) fn confine_filter(config: &Config, filter: MetaFilter) -> Result<MetaFilter> {Ok(match super::user_scope::confinement(config)? {Some(root) => super::user_scope::clamp_filter(filter, &root),None => filter,diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rsindex fdebe64f8d..294bbe6589 100644--- a/crates/openhuman-core/src/memory/schemas/handlers.rs+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs@@ -7,7 +7,7 @@ use crate::config::Config;use crate::core::all::ControllerFuture;use crate::core::runtime::DispatchCtx;use crate::core::Outcome;-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};use crate::memory::explore::{ExploreParams, ItemsGetParams};use crate::memory::lifecycle::views::{self, JobsRunParams, PackPreviewParams, PolicySetParams};use crate::memory::scope::MemoryIdentity;@@ -24,7 +24,7 @@ use serde_json::{json, Map, Value};/// The operation run after the common request parsing and config load.trait RpcOperation<P, R>: Send + 'static {- type Future: Future<Output = MemoryResult<R>> + Send + 'static;+ type Future: Future<Output = Result<R>> + Send + 'static;fn call(self, ctx: DispatchCtx, config: Config, params: P) -> Self::Future;}@@ -32,7 +32,7 @@ trait RpcOperation<P, R>: Send + 'static {impl<P, R, F, Fut> RpcOperation<P, R> for FwhereF: FnOnce(DispatchCtx, Config, P) -> Fut + Send + 'static,- Fut: Future<Output = MemoryResult<R>> + Send + 'static,+ Fut: Future<Output = Result<R>> + Send + 'static,{type Future = Fut;@@ -60,14 +60,14 @@ wherefn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {serde_json::from_value(Value::Object(params))- .map_err(|error| MemoryError::invalid(format!("invalid params: {error}")).into())+ .map_err(|error| Error::invalid(format!("invalid params: {error}")).into())}fn to_json<T: Serialize>(value: T) -> Result<Value, String> {Outcome::new(value, Vec::new()).into_cli_compatible_json()}-fn finish<T: Serialize>(result: MemoryResult<T>) -> Result<Value, String> {+fn finish<T: Serialize>(result: Result<T>) -> Result<Value, String> {to_json(result.map_err(String::from)?)}@@ -75,11 +75,11 @@ async fn load(ctx: &DispatchCtx) -> Result<Config, String> {ctx.load_config().await}-async fn save(config: &Config) -> MemoryResult<()> {+async fn save(config: &Config) -> Result<()> {config.save().await- .map_err(|error| MemoryError::Engine(format!("saving config failed: {error:#}")))+ .map_err(|error| Error::Engine(format!("saving config failed: {error:#}")))}pub(super) fn engines_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {diff --git a/crates/openhuman-core/src/memory/scope.rs b/crates/openhuman-core/src/memory/scope.rsindex 99c7032ed0..0fcad29d17 100644--- a/crates/openhuman-core/src/memory/scope.rs+++ b/crates/openhuman-core/src/memory/scope.rs@@ -44,7 +44,7 @@ use tinymemory_api::{Namespace, Segment, SegmentKind};use tinymemory_tools::MemoryLayout;use crate::config::{Config, MemoryLayoutMode};-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};/// The memory agent id of work no agent is running (RPC, sync jobs, the UI).pub const DEFAULT_AGENT_ID: &str = "assistant";@@ -255,15 +255,15 @@ pub fn actor_of_root(root: &str) -> String {/// # Errors////// The config could not be loaded or saved.-pub async fn switch_to_v3(config: &Config) -> MemoryResult<()> {+pub async fn switch_to_v3(config: &Config) -> Result<()> {let mut config = Config::load_from_config_path(&config.config_path, &config.workspace_dir).await- .map_err(|error| MemoryError::Engine(format!("loading config failed: {error:#}")))?;+ .map_err(|error| Error::Engine(format!("loading config failed: {error:#}")))?;config.memory.layout = MemoryLayoutMode::V3;config.save().await- .map_err(|error| MemoryError::Engine(format!("saving config failed: {error:#}")))?;+ .map_err(|error| Error::Engine(format!("saving config failed: {error:#}")))?;super::engine::invalidate();tracing::info!("[memory:scope] memory switched to layout v3");Ok(())diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex b843d17d4e..ec066d0957 100644--- a/crates/openhuman-core/src/memory/sources/mod.rs+++ b/crates/openhuman-core/src/memory/sources/mod.rs@@ -16,7 +16,7 @@ use crate::config::schema::{MemorySourceConfig, MemorySourceKind};use crate::config::Config;use super::engine;-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::types::{SourceView, SourcesAddParams};pub use sync::{start_sync, sync_due, sync_one};@@ -56,10 +56,10 @@ pub fn list(config: &Config) -> Vec<SourceView> {/// Normalises a target for `kind`: GitHub accepts `owner/repo` or a URL;/// network kinds must be http(s) URLs.-pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<String> {+pub fn normalize_target(kind: MemorySourceKind, target: &str) -> Result<String> {let target = target.trim();if target.is_empty() {- return Err(MemoryError::invalid("target must not be empty"));+ return Err(Error::invalid("target must not be empty"));}match kind {MemorySourceKind::Folder | MemorySourceKind::File => Ok(target.to_string()),@@ -72,7 +72,7 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<St(Some(owner), Some(repo), None) if !owner.is_empty() && !repo.is_empty() => {Ok(format!("https://github.com/{owner}/{repo}"))}- _ => Err(MemoryError::invalid(+ _ => Err(Error::invalid("a GitHub target is `owner/repo` or a repository URL",)),}@@ -81,10 +81,10 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> MemoryResult<St}}-fn http_url(target: &str) -> MemoryResult<String> {- let url = url::Url::parse(target).map_err(|_| MemoryError::invalid("target is not a URL"))?;+fn http_url(target: &str) -> Result<String> {+ let url = url::Url::parse(target).map_err(|_| Error::invalid("target is not a URL"))?;if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {- return Err(MemoryError::invalid("target must be an http(s) URL"));+ return Err(Error::invalid("target must be an http(s) URL"));}Ok(url.to_string())}@@ -94,9 +94,9 @@ fn http_url(target: &str) -> MemoryResult<String> {pub fn apply_add(config: &mut Config,params: &SourcesAddParams,-) -> MemoryResult<MemorySourceConfig> {+) -> Result<MemorySourceConfig> {let kind = MemorySourceKind::parse(¶ms.kind).ok_or_else(|| {- MemoryError::invalid(format!(+ Error::invalid(format!("unknown source kind `{}` (folder, file, link, github, rss)",params.kind.trim()))@@ -104,7 +104,7 @@ pub fn apply_add(let target = normalize_target(kind, ¶ms.target)?;if let Some(mins) = params.schedule_mins {if mins < MIN_SCHEDULE_MINS {- return Err(MemoryError::invalid(format!(+ return Err(Error::invalid(format!("schedule_mins must be at least {MIN_SCHEDULE_MINS}")));}@@ -115,7 +115,7 @@ pub fn apply_add(.iter().any(|source| source.kind == kind && source.target == target){- return Err(MemoryError::invalid("that source is already added"));+ return Err(Error::invalid("that source is already added"));}let label = params.label@@ -127,7 +127,7 @@ pub fn apply_add(None | Some("") => None,Some(raw) => Some(raw.parse::<tinymemory_api::Namespace>()- .map_err(|error| MemoryError::invalid(error.to_string()))?+ .map_err(|error| Error::invalid(error.to_string()))?.to_string(),),};@@ -158,13 +158,13 @@ pub fn apply_remove(config: &mut Config, id: &str) -> Option<MemorySourceConfig>/// an explicit `redact_events` cascade). Memory off is not an error here:/// the deletion is queued ([`crate::memory::deletion`]) and runs on the next/// sign-in. A failure is queued the same way, and returned.-pub async fn forget_items(config: &Config, id: &str) -> MemoryResult<usize> {+pub async fn forget_items(config: &Config, id: &str) -> Result<usize> {let pending = || crate::memory::deletion::PendingDeletion::Source {source_id: id.to_string(),};let bound = match engine::resolve(config).engine() {Ok(bound) => bound,- Err(MemoryError::Off(_)) => {+ Err(Error::Off(_)) => {crate::memory::deletion::enqueue(&config.workspace_dir, pending());return Ok(0);}diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex ad7f184d8b..e4d0d7fbe4 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -20,7 +20,7 @@ use tinymemory_integrations::sources::SourceKind;use crate::config::schema::{MemorySourceConfig, MemorySourceKind};use crate::config::Config;use crate::memory::engine;-use crate::memory::error::{MemoryError, MemoryResult};+use crate::memory::error::{Error, Result};use crate::memory::types::SourceStatus;use super::state;@@ -43,18 +43,18 @@ fn registered(source: &MemorySourceConfig) -> RegisteredSource {}}-fn host_error(error: SyncError) -> MemoryError {+fn host_error(error: SyncError) -> Error {match error {- SyncError::Invalid(message) => MemoryError::invalid(message),+ SyncError::Invalid(message) => Error::invalid(message),SyncError::Read(message) => {- MemoryError::Engine(format!("reading the source failed: {message}"))+ Error::Engine(format!("reading the source failed: {message}"))}SyncError::Engine(error) => error.into(),}}/// Checks `source` is readable as configured, without reading it.-pub(super) fn validate(source: &MemorySourceConfig) -> MemoryResult<()> {+pub(super) fn validate(source: &MemorySourceConfig) -> Result<()> {module::entry_for(®istered(source)).map(|_| ()).map_err(host_error)@@ -128,7 +128,7 @@ fn syncer_for(config: &Config) -> Syncer {}/// Reads `source` and stores what it yields. Returns the number stored.-pub async fn sync_one(config: &Config, source: &MemorySourceConfig) -> MemoryResult<u64> {+pub async fn sync_one(config: &Config, source: &MemorySourceConfig) -> Result<u64> {engine::resolve(config).engine()?;run(config, source).await.map_err(host_error)}@@ -197,7 +197,7 @@ pub fn start_sync(ctx: &crate::core::runtime::DispatchCtx,config: &Config,id: Option<&str>,-) -> MemoryResult<Vec<String>> {+) -> Result<Vec<String>> {engine::resolve(config).engine()?;let claims = syncer_for(config).start(id).map_err(host_error)?;let mut started = Vec::new();diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rsindex 579f559d2a..b92789f4a9 100644--- a/crates/openhuman-core/src/memory/tool_writes.rs+++ b/crates/openhuman-core/src/memory/tool_writes.rs@@ -26,7 +26,7 @@ use tinymemory_tools::pending::{WriteGate, WriteOperation,};-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use super::tools::CallFacts;use super::types::{ForgetParams, LearnParams};use crate::config::Config;@@ -147,8 +147,8 @@ fn queue_path(config: &Config, root: &Namespace) -> PathBuf {))}-fn unavailable() -> MemoryError {- MemoryError::Unavailable(+fn unavailable() -> Error {+ Error::Unavailable("memory write queue unavailable; durable queueing was not confirmed".into(),)}@@ -159,9 +159,9 @@ pub(super) fn enqueue(config: &Config,args: &serde_json::Value,facts: &CallFacts,-) -> MemoryResult<serde_json::Value> {+) -> Result<serde_json::Value> {if super::engine::switched_off(config) {- return Err(MemoryError::Off("memory is disabled".into()));+ return Err(Error::Off("memory is disabled".into()));}let confinement = super::user_scope::confinement(config)?;let reach = match confinement {@@ -173,14 +173,14 @@ pub(super) fn enqueue(let operation = match args.get("action").and_then(serde_json::Value::as_str) {Some("learn") => {let mut params: LearnParams = serde_json::from_value(args.clone())- .map_err(|_| MemoryError::invalid("invalid learning arguments"))?;+ .map_err(|_| Error::invalid("invalid learning arguments"))?;params.meta = None;let mut item = super::ops::learning_item(params, Some(facts.learn_meta()))?;if let Some(root) = confinement {super::user_scope::clamp_item(&mut item, &root);}if !super::user_scope::within(&item.meta().namespace, &reach.at) || reach.inherit {- return Err(MemoryError::invalid(+ return Err(Error::invalid("learning namespace is outside the trusted reach",));}@@ -190,7 +190,7 @@ pub(super) fn enqueue(}Some("forget") => {let params: ForgetParams = serde_json::from_value(args.clone())- .map_err(|_| MemoryError::invalid("invalid forgetting arguments"))?;+ .map_err(|_| Error::invalid("invalid forgetting arguments"))?;let mut ids: Vec<_> = params.ids.into_iter()@@ -200,17 +200,17 @@ pub(super) fn enqueue(ids.sort();ids.dedup();if ids.is_empty() {- return Err(MemoryError::invalid("forget needs at least one id"));+ return Err(Error::invalid("forget needs at least one id"));}WriteOperation::Forget { ids, reach }}- _ => return Err(MemoryError::invalid("expected a memory write")),+ _ => return Err(Error::invalid("expected a memory write")),};let _guard = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);if !file.exists() && partitions(config)?.len() >= MAX_PENDING {- return Err(MemoryError::Unavailable(+ return Err(Error::Unavailable("memory write queue full; nothing was queued".into(),));}@@ -291,16 +291,16 @@ fn queue(file: &Path) -> Arc<Queue> {queue}-fn map_pending(error: PendingError) -> MemoryError {- MemoryError::Unavailable(error.to_string())+fn map_pending(error: PendingError) -> Error {+ Error::Unavailable(error.to_string())}-fn read_at(path: &Path) -> MemoryResult<Vec<Entry>> {+fn read_at(path: &Path) -> Result<Vec<Entry>> {queue(path).entries().map_err(map_pending)}#[cfg(test)]-fn write_at(file: &Path, entries: &[Entry]) -> MemoryResult<()> {+fn write_at(file: &Path, entries: &[Entry]) -> Result<()> {FileStore {file: file.to_path_buf(),}@@ -309,11 +309,11 @@ fn write_at(file: &Path, entries: &[Entry]) -> MemoryResult<()> {}#[cfg(test)]-fn read(workspace: &Path) -> MemoryResult<Vec<Entry>> {+fn read(workspace: &Path) -> Result<Vec<Entry>> {read_at(&path(workspace))}#[cfg(test)]-fn write(workspace: &Path, entries: &[Entry]) -> MemoryResult<()> {+fn write(workspace: &Path, entries: &[Entry]) -> Result<()> {write_at(&path(workspace), entries)}@@ -352,7 +352,7 @@ fn owner_state(config: &Config) -> Arc<OwnerState> {owner}-fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {+fn partitions(config: &Config) -> Result<Vec<PathBuf>> {let prefix = format!("{}-", owner_prefix(config));let entries = match std::fs::read_dir(config.workspace_dir.join("memory")) {Ok(entries) => entries,@@ -460,7 +460,7 @@ impl Drop for WriteFence {pub(crate) async fn fence_and_clear(ctx: &crate::core::runtime::DispatchCtx,config: &Config,-) -> MemoryResult<WriteFence> {+) -> Result<WriteFence> {let state = owner_state(config);let token = OwnedFenceToken::new(state.clone());let fencing_generation = token.generation();@@ -482,7 +482,7 @@ pub(crate) async fn fence_and_clear(.clear_stale(state.gate.process(), fencing_generation).map_err(map_pending)?;}- Ok::<_, MemoryError>(())+ Ok::<_, Error>(())}).await.map_err(|_| unavailable())??;diff --git a/crates/openhuman-core/src/memory/tool_writes_tests.rs b/crates/openhuman-core/src/memory/tool_writes_tests.rsindex 4d9bea075d..1f08abaf91 100644--- a/crates/openhuman-core/src/memory/tool_writes_tests.rs+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs@@ -417,7 +417,7 @@ async fn explicit_memory_disable_refuses_new_writes_and_keeps_old_writes_pending&json!({"action":"learn","text":"Must not persist"}),&call_facts),- Err(MemoryError::Off(_))+ Err(Error::Off(_))));assert_eq!(drain(&config).await, 0);assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rsindex 3f083d6cdf..fc43ebdf3d 100644--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@ -32,7 +32,7 @@ use crate::core::bus::BUS;use crate::core::events::DomainEvent;use crate::core::runtime::DispatchCtx;-use super::error::MemoryError;+use super::error::Error;use super::ops;pub use super::tool_budget::is_budget_refusal;use super::types::{FetchParams, ForgetParams, LearnParams, RecallParams, RecallView};@@ -417,7 +417,7 @@ fn confine(filter: &mut Option<tinymemory_api::MetaFilter>, facts: &CallFacts) {filter.get_or_insert_with(Default::default).reach = Some(facts.reach.clone());}-fn render_error(error: MemoryError) -> String {+fn render_error(error: Error) -> String {format!("{} ({})", error, error.code())}@@ -503,7 +503,7 @@ impl Tool for MemoryTool {.await;return Ok(match queued.unwrap_or_else(|_| {- Err(MemoryError::Unavailable(+ Err(Error::Unavailable("memory write queue unavailable".into(),))}) {diff --git a/crates/openhuman-core/src/memory/user_scope.rs b/crates/openhuman-core/src/memory/user_scope.rsindex 7ea7cccefd..c6416c5cdc 100644--- a/crates/openhuman-core/src/memory/user_scope.rs+++ b/crates/openhuman-core/src/memory/user_scope.rs@@ -22,18 +22,18 @@use tinymemory_api::{MetaFilter, Namespace, Reach, StoreItem};-use super::error::{MemoryError, MemoryResult};+use super::error::{Error, Result};use crate::config::Config;/// The root `config`'s memory is confined to, in SaaS mode (`None` in single/// user mode). A SaaS config without a valid root is refused: neither the/// global root (everyone's memory) nor no confinement at all is safe.-pub fn confinement(config: &Config) -> MemoryResult<Option<Namespace>> {+pub fn confinement(config: &Config) -> Result<Option<Namespace>> {confinement_in(crate::core::runtime::is_saas(), config)}/// [`confinement`] as a pure function of the mode.-pub fn confinement_in(saas: bool, config: &Config) -> MemoryResult<Option<Namespace>> {+pub fn confinement_in(saas: bool, config: &Config) -> Result<Option<Namespace>> {if !saas {return Ok(None);}@@ -45,7 +45,7 @@ pub fn confinement_in(saas: bool, config: &Config) -> MemoryResult<Option<Namesproot = raw,"[memory:user_scope] no valid confinement root in SaaS mode");- Err(MemoryError::invalid(+ Err(Error::invalid("memory is unavailable: this agent has no valid memory root",))}