Skip to content

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

Merge remote-tracking branch 'origin/main' into memory-engines

Steven Enamakel42ef54a874f4
diff --cc app/src/components/settings/settingsRouteRegistry.ts
index 1ba8eddfd1,0acd19f023..a11fe4fb79
--- a/app/src/components/settings/settingsRouteRegistry.ts
+++ b/app/src/components/settings/settingsRouteRegistry.ts
@@@ -495,18 -494,8 +494,18 @@@ export const SETTINGS_ROUTE_REGISTRY: S
devOnly: true,
searchKeywords: ['developer', 'diagnostics', 'debug'],
},
+ {
+ // memory-engine: choose the one active memory engine. Reached from the
+ // Brain page ("Memory engine · Change"); not a sidebar entry.
+ id: 'memory-engine',
+ titleKey: 'memoryEngine.title',
+ descriptionKey: 'memoryEngine.description',
+ section: 'features',
+ hiddenDeepLink: true,
+ searchKeywords: ['memory', 'engine', 'cortexdb', 'supermemory', 'mem0', 'cognee'],
+ },
// Knowledge & Memory group retired entirely — memory surfaces live on the
- // Brain page (graph / goals / sources / sync / subconscious).
+ // Brain page (graph / goals / sources / sync).
// voice-debug retired from the settings UI.
{
id: 'event-log',
diff --cc crates/openhuman-core/Cargo.toml
index 193e9fde54,7ce37dde6e..8b2b48e3a0
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@@ -757,28 -753,24 +758,24 @@@ proptest = "1
# (`modules`: Contrib=ON, Product=ON) and with `scripts/ci/product-features.txt`,
# which already lists it. This does NOT move the kernel floor: that profile is
# `--no-default-features --features flows` and never reads this list.
-default = ["media", "skills", "flows", "mcp", "channels", "http-server", "scheduler-gate", "file-logging", "modules"]
+default = ["media", "skills", "flows", "mcp", "channels", "http-server", "scheduler-gate", "file-logging", "modules", "memory-remote"]
- # HTTP + Socket.IO server transport (#5048): the `/rpc` JSON-RPC endpoint and
- # its auth middleware/CORS layer (`core::jsonrpc`, `core::auth`), the `/v1`
- # OpenAI-compatible router (`inference::http`), the ad-hoc static-dir file
- # server (`openhuman::http_host`), the AgentBox `/run` HTTP surface
- # (`agentbox::http`), the WebSocket dictation stream
- # (`inference::voice::streaming`), the `openhuman text-input run` dev server,
- # the MCP Streamable-HTTP transport (`mcp::server::http`, additionally gated by
- # `mcp`), and the Socket.IO live-event bridge (`core::socketio`). Default-ON —
- # the desktop shell REQUIRES it (see the `HTTP_SERVER_COMPILED_IN` compile
- # assert in `crates/openhuman-app/src/lib.rs`). Slim / headless-embedding builds opt
- # out via `--no-default-features --features "<explicit list without
- # http-server>"`, which drops the exclusive `axum` + `socketioxide` deps; the
- # core then runs background services without binding a listener (`serve()`
- # returns early) and is driven over the CLI / native dispatch surface instead.
- #
- # TYPE CARVE-OUT (see AGENTS.md): `core::socketio`'s inert event payload types
- # (`WebChannelEvent`, `TurnUsagePayload`, `SubagentUsagePayload`,
- # `SubagentProgressDetail`) stay compiled in BOTH builds — ~10 always-on
- # domains construct them — so `pub mod socketio;` is UNGATED and only the
- # socketioxide/axum-touching bodies are gated. Likewise `inference::http::types`
- # and `EXTERNAL_OPENAI_COMPAT_PROVIDER` stay compiled for `core::auth`.
+ # The core's domain-owned HTTP surfaces (#5048): the `/v1` OpenAI-compatible
+ # router (`inference::http`), the ad-hoc static-dir file server
+ # (`openhuman::http_host`), the WebSocket dictation handler
+ # (`voice::streaming`), the `openhuman text-input run` dev server, and the MCP
+ # Streamable-HTTP transport (`mcp::server::http`, additionally gated by `mcp`).
+ # The JSON-RPC server that mounts them — `/rpc`, auth, CORS, SSE, Socket.IO,
+ # the listener — lives in `openhuman-rpc`, whose `server` feature turns this
+ # gate on. Default-ON; the desktop shell REQUIRES it (see the
+ # `HTTP_SERVER_COMPILED_IN` compile assert in `crates/openhuman-app/src/lib.rs`).
+ # Slim / headless-embedding builds opt out via `--no-default-features
+ # --features "<explicit list without http-server>"`, which drops `axum`; the
+ # core is then driven over the CLI / native dispatch surface instead.
+ #
+ # `web_chat`'s event payload types (`WebChannelEvent`, `TurnUsagePayload`, …)
+ # stay compiled in BOTH builds, since ~10 always-on domains construct them.
+ # Likewise `inference::http::types` and `EXTERNAL_OPENAI_COMPAT_PROVIDER` stay
+ # compiled for the server's auth policy.
# Git-backed memory diff: snapshots as commits, checkpoints as tags, read
# markers as refs, diffs as git tree diffs (`openhuman::memory::diff`), plus the
# git-backed wiki content format in `memory::store::content::wiki_git`.
diff --cc crates/openhuman-core/src/core/bus.rs
index aa3c9d788b,ff81c49420..d76f2bd2c2
--- a/crates/openhuman-core/src/core/bus.rs
+++ b/crates/openhuman-core/src/core/bus.rs
@@@ -72,8 -72,9 +72,10 @@@ pub const EVENTS_INTERFACE: &str = "ai.
/// (`request_id`), the new `ThreadTodosChanged` and `ThreadRunModeChanged`
/// variants. All additions are optional/defaulted, so an older subscriber
/// keeps parsing what a newer publisher emits.
- /// `1.6.0` added `MemoryDriverChanged` (memory-engine switch, additive).
- pub const EVENTS_VERSION: Version = Version::new(1, 6, 0);
+ /// `1.6.0` retired `SubconsciousTriggerProcessed`, which nothing published
+ /// after the background-reasoning engine was removed.
-pub const EVENTS_VERSION: Version = Version::new(1, 6, 0);
++/// `1.7.0` added `MemoryDriverChanged` (memory-engine switch, additive).
++pub const EVENTS_VERSION: Version = Version::new(1, 7, 0);
/// The bus. Initialised once by [`init`]; safe to touch before that.
pub static BUS: OnceBus<DomainEvent> = OnceBus::new();
diff --cc crates/openhuman-core/src/memory/ops/documents.rs
index 8355925d71,112b36a789..dde55ee7ea
--- a/crates/openhuman-core/src/memory/ops/documents.rs
+++ b/crates/openhuman-core/src/memory/ops/documents.rs
@@@ -15,10 -16,8 +16,9 @@@ use crate::memory::
QueryNamespaceResponse, RecallContextRequest, RecallContextResponse, RecallMemoriesRequest,
RecallMemoriesResponse,
};
- use crate::rpc::RpcOutcome;
use super::envelope::{envelope, error_envelope, memory_counts};
+use super::fallback;
use super::guard::active_memory_guard;
use super::helpers::{
build_retrieval_context, current_workspace_dir, filter_hits_by_document_ids,
@@@ -164,19 -163,16 +164,16 @@@ pub struct PutDocResult
// ---------------------------------------------------------------------------
/// Lists all namespaces in the memory system.
- pub async fn namespace_list() -> Result<RpcOutcome<Vec<String>>, String> {
+ pub async fn namespace_list() -> Result<Outcome<Vec<String>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let namespaces = documents
- .list_namespaces()
- .await
- .map_err(|error| error.to_string())?;
+ let namespaces = match guard.as_documents() {
+ Some(documents) => documents
+ .list_namespaces()
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::namespace_names(&guard).await?,
+ };
- Ok(RpcOutcome::single_log(
- namespaces,
- "memory namespaces listed",
- ))
+ Ok(Outcome::single_log(namespaces, "memory namespaces listed"))
}
/// Upserts a document into a namespace.
@@@ -281,17 -275,16 +276,17 @@@ pub async fn doc_ingest(params: IngestD
/// Lists documents, optionally filtered by namespace.
pub async fn doc_list(
params: Option<NamespaceOnlyParams>,
- ) -> Result<RpcOutcome<serde_json::Value>, String> {
+ ) -> Result<Outcome<serde_json::Value>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let docs = documents
- .list_documents(params.as_ref().map(|value| value.namespace.as_str()))
- .await
- .map_err(|error| error.to_string())?;
+ let namespace = params.as_ref().map(|value| value.namespace.as_str());
+ let docs = match guard.as_documents() {
+ Some(documents) => documents
+ .list_documents(namespace)
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::document_list(&guard, namespace).await?,
+ };
- Ok(RpcOutcome::single_log(docs, "memory documents listed"))
+ Ok(Outcome::single_log(docs, "memory documents listed"))
}
/// Deletes a document from a namespace.
@@@ -418,15 -411,15 +413,15 @@@ pub async fn memory_init
/// Lists documents stored in memory, optionally filtered by namespace.
pub async fn memory_list_documents(
request: ListDocumentsRequest,
- ) -> Result<RpcOutcome<ApiEnvelope<ListDocumentsResponse>>, String> {
+ ) -> Result<Outcome<ApiEnvelope<ListDocumentsResponse>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let raw = documents
- .list_documents(request.namespace.as_deref())
- .await
- .map_err(|error| error.to_string())?;
+ let raw = match guard.as_documents() {
+ Some(documents) => documents
+ .list_documents(request.namespace.as_deref())
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::document_list(&guard, request.namespace.as_deref()).await?,
+ };
let documents = parse_memory_document_summaries(raw)?;
let count = documents.len();
Ok(envelope(
@@@ -478,15 -471,15 +473,15 @@@ pub async fn memory_namespace_summaries
/// Lists all namespaces that contain memory documents.
pub async fn memory_list_namespaces(
_request: EmptyRequest,
- ) -> Result<RpcOutcome<ApiEnvelope<ListNamespacesResponse>>, String> {
+ ) -> Result<Outcome<ApiEnvelope<ListNamespacesResponse>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let namespaces = documents
- .list_namespaces()
- .await
- .map_err(|error| error.to_string())?;
+ let namespaces = match guard.as_documents() {
+ Some(documents) => documents
+ .list_namespaces()
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::namespace_names(&guard).await?,
+ };
let count = namespaces.len();
Ok(envelope(
ListNamespacesResponse { namespaces, count },
@@@ -664,19 -644,15 +659,19 @@@ pub async fn memory_recall_context
/// Recalls memory items from a namespace with optional retention filtering.
pub async fn memory_recall_memories(
request: RecallMemoriesRequest,
- ) -> Result<RpcOutcome<ApiEnvelope<RecallMemoriesResponse>>, String> {
+ ) -> Result<Outcome<ApiEnvelope<RecallMemoriesResponse>>, String> {
let result = async {
let guard = active_memory_guard().await?;
- guard
- .as_retrieval()
- .ok_or_else(|| "memory driver does not support the retrieval family".to_string())?
- .recall_namespace_recent(&request.namespace, request.resolved_limit() as usize)
- .await
- .map_err(|e| format!("memory.recall_memories: {e}"))
+ let limit = request.resolved_limit() as usize;
+ match guard.as_retrieval() {
+ Some(retrieval) => retrieval
+ .recall_namespace_recent(&request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_memories: {e}")),
+ None => fallback::recent_hits(&guard, &request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_memories: {e}")),
+ }
}
.await;
diff --cc crates/openhuman-core/src/memory/ops/engine.rs
index e4600f44de,0000000000..d0b2bd7ff4
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/ops/engine.rs
+++ b/crates/openhuman-core/src/memory/ops/engine.rs
@@@ -1,554 -1,0 +1,552 @@@
+//! `memory.engines_list`, `memory.engine_get`, `memory.engine_set` — choosing
+//! which engine backs memory.
+//!
+//! The default engine is the compiled `tinymemory` module (local TinyCortex).
+//! With the `memory-remote` gate the user can also bind a remote engine
+//! (`tinyhumans`, `supermemory`, `mem0`, `cognee`, `cortex`, `agentmemory`)
+//! through `tinymemory::factory`. This file is the RPC-facing half: validation,
+//! keychain storage of the key, the `[subsystems.memory]` config write, and the
+//! in-process rebind. Migration between engines is in [`super::engine_migrate`].
+//!
+//! Secrets: an `api_key` is written to the keychain under
+//! `keychain:memory-<id>` and never appears in config, logs, events, errors or
+//! any response. Responses only say whether a credential exists.
+
+use serde::{Deserialize, Serialize};
+
+use crate::config::schema::{Config, MemoryDriverConfig};
++use crate::core::Outcome;
+use crate::memory::binding::{self, MODULE_ID};
+use crate::memory::binding_remote::{
+ credential_ref_for, is_remote_engine, keyring_user_id, CREDENTIAL_NAME_PREFIX, HOSTED_ENGINE_ID,
+};
- use crate::rpc::RpcOutcome;
+
+const LOG_PREFIX: &str = "[memory:engine]";
+
+/// Error prefix for "the hosted engine refused for lack of credits".
+pub const INSUFFICIENT_CREDITS_PREFIX: &str = "INSUFFICIENT_CREDITS:";
+/// Error prefix for "no valid TinyHumans session".
+pub const SESSION_EXPIRED_PREFIX: &str = "SESSION_EXPIRED:";
+
+/// One selectable engine, as `memory.engines_list` reports it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct EngineEntry {
+ pub id: String,
+ pub label: String,
+ pub description: String,
+ pub needs_endpoint: bool,
+ pub needs_key: bool,
+ pub key_optional: bool,
+ pub deployments: Vec<String>,
+ pub default_endpoint: Option<String>,
+ pub hosted: bool,
+ /// Capability families the engine is expected to advertise. Static: the
+ /// bound driver's own answer is `memory.provider_status`.
+ pub capabilities: Vec<String>,
+}
+
+/// Result of `memory.engines_list`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct EnginesList {
+ pub engines: Vec<EngineEntry>,
+ pub active: String,
+}
+
+/// Result of `memory.engine_get` / `memory.engine_set`. Never carries a secret.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct EngineState {
+ pub driver: String,
+ pub endpoint: Option<String>,
+ pub deployment: Option<String>,
+ pub has_credential: bool,
+ pub class: String,
+ pub fell_back_from: Option<String>,
+ pub last_error: Option<String>,
+}
+
+/// An engine a caller asks for (`memory.engine_set`, and `to` of a migration).
+///
+/// No `Debug` on purpose: `api_key` is a secret.
+#[derive(Clone, Deserialize)]
+pub struct EngineTargetParams {
+ pub driver: String,
+ #[serde(default)]
+ pub endpoint: Option<String>,
+ #[serde(default)]
+ pub deployment: Option<String>,
+ #[serde(default)]
+ pub api_key: Option<String>,
+}
+
+/// A validated [`EngineTargetParams`].
+pub(super) struct Prepared {
+ pub id: String,
+ pub endpoint: Option<String>,
+ pub deployment: Option<String>,
+ pub api_key: Option<String>,
+ /// The engine takes a user key, so its config entry carries a
+ /// `credential_ref`.
+ pub takes_key: bool,
+}
+
+impl std::fmt::Debug for Prepared {
+ // Manual: `api_key` is a secret and must never reach `Debug` output.
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Prepared")
+ .field("id", &self.id)
+ .field("endpoint", &self.endpoint)
+ .field("deployment", &self.deployment)
+ .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
+ .field("takes_key", &self.takes_key)
+ .finish()
+ }
+}
+
+fn blank_to_none(value: Option<String>) -> Option<String> {
+ value
+ .map(|v| v.trim().to_string())
+ .filter(|v| !v.is_empty())
+}
+
+/// The capability families each remote engine is expected to advertise, by id.
+///
+/// Mirrors what the adapters report at bind time (`tinymemory-remote`): the
+/// three mandatory families for all, plus what each dialect adds. The module
+/// engine advertises everything.
+fn expected_capabilities(id: &str) -> Vec<String> {
+ use tinymemory_api::capabilities::Capability as C;
+ let mut caps: Vec<&'static str> = C::MANDATORY.iter().map(|c| c.as_str()).collect();
+ let extra: &[C] = match id {
+ MODULE_ID => {
+ return crate::memory::api::capabilities::Capabilities::all()
+ .iter()
+ .map(|c| c.as_str().to_string())
+ .collect()
+ }
+ "mem0" => &[C::ConversationIngest, C::Graph],
+ "cognee" => &[C::Graph],
+ "cortex" | "tinyhumans" => &[
+ C::DocumentIngest,
+ C::ConversationIngest,
+ C::LearningIngest,
+ C::EventIngest,
+ C::Answer,
+ ],
+ _ => &[],
+ };
+ caps.extend(extra.iter().map(|c| c.as_str()));
+ caps.into_iter().map(str::to_string).collect()
+}
+
+/// Every engine this build offers, module first. Never includes `null`, nor the
+/// factory's in-memory `tinycortex` (not persistent).
+#[must_use]
+pub fn available_engines() -> Vec<EngineEntry> {
+ #[cfg_attr(not(feature = "memory-remote"), allow(unused_mut))]
+ let mut engines = vec![EngineEntry {
+ id: MODULE_ID.to_string(),
+ label: "TinyCortex (local)".to_string(),
+ description: "The built-in local memory engine. Nothing leaves your device.".to_string(),
+ needs_endpoint: false,
+ needs_key: false,
+ key_optional: false,
+ deployments: vec![],
+ default_endpoint: None,
+ hosted: false,
+ capabilities: expected_capabilities(MODULE_ID),
+ }];
+ #[cfg(feature = "memory-remote")]
+ for d in tinymemory::factory::list_engines() {
+ if d.id == tinymemory_api::drivers::TINYCORTEX_DRIVER_ID || d.id == MODULE_ID {
+ continue;
+ }
+ engines.push(EngineEntry {
+ id: d.id.to_string(),
+ label: d.label.to_string(),
+ description: d.description.to_string(),
+ needs_endpoint: d.needs_endpoint,
+ needs_key: d.needs_key,
+ key_optional: d.key_optional,
+ deployments: d.deployments.iter().map(|s| (*s).to_string()).collect(),
+ default_endpoint: d.default_endpoint.map(str::to_string),
+ hosted: d.hosted,
+ capabilities: expected_capabilities(d.id),
+ });
+ }
+ engines
+}
+
+/// The persisted driver id, with the legacy `tinycortex` alias folded onto the
+/// module.
+fn normalized_driver(config: &Config) -> String {
+ let id = config.subsystems.memory.driver.trim();
+ if id.is_empty() || id == "tinycortex" {
+ MODULE_ID.to_string()
+ } else {
+ id.to_string()
+ }
+}
+
+/// Map an engine-layer failure to the RPC error vocabulary the UI keys on:
+/// `INSUFFICIENT_CREDITS:`, `SESSION_EXPIRED:` or `BACKEND_UNAVAILABLE:`, else
+/// the message as is (already scrubbed of keys and endpoints by the engine
+/// layer).
+#[must_use]
+pub fn classify_engine_error(error: &anyhow::Error) -> String {
+ use crate::memory::api::error::MemoryError;
+ if let Some(me) = error.downcast_ref::<MemoryError>() {
+ match me {
+ // The hosted backend's 402 carries a `[USER_INSUFFICIENT_CREDITS]`
+ // message prefix (`tinymemory_remote::hosted`).
+ MemoryError::BudgetExceeded(message)
+ if message
+ .trim_start()
+ .starts_with("[USER_INSUFFICIENT_CREDITS]") =>
+ {
+ return format!(
+ "{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits"
+ );
+ }
+ MemoryError::Unauthorized(_) => {
+ return format!("{SESSION_EXPIRED_PREFIX} the memory engine rejected the session");
+ }
+ _ => {}
+ }
+ }
+ classify_engine_message(&format!("{error:#}"))
+}
+
+/// [`classify_engine_error`] for a failure that is already a string.
+#[must_use]
+pub fn classify_engine_message(message: &str) -> String {
+ if message.contains(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX)
+ || message.starts_with(SESSION_EXPIRED_PREFIX)
+ || message.starts_with(INSUFFICIENT_CREDITS_PREFIX)
+ {
+ return message.to_string();
+ }
+ if message.contains("USER_INSUFFICIENT_CREDITS") {
+ return format!("{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits");
+ }
+ if message.contains(SESSION_EXPIRED_PREFIX)
+ || message.contains("[UNAUTHORIZED]")
+ || (message.starts_with("unauthorized:") && message.contains("re-authenticate"))
+ {
+ return format!("{SESSION_EXPIRED_PREFIX} no TinyHumans session");
+ }
+ message.to_string()
+}
+
+/// Reject endpoints that carry credentials or point at link-local / cloud
+/// metadata addresses. Error text never echoes the endpoint (it may hold
+/// userinfo).
+fn validate_endpoint(endpoint: &str) -> Result<(), String> {
+ use std::net::{IpAddr, Ipv6Addr};
+ let Ok(parsed) = url::Url::parse(endpoint) else {
+ return Err("endpoint must be an http(s) URL".to_string());
+ };
+ if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
+ return Err("endpoint must be an http(s) URL".to_string());
+ }
+ if !parsed.username().is_empty() || parsed.password().is_some() {
+ return Err(
+ "endpoint must not embed credentials before the host; use the API key field"
+ .to_string(),
+ );
+ }
+ let link_local = match parsed.host() {
+ Some(url::Host::Ipv4(ip)) => ip.is_link_local(),
+ Some(url::Host::Ipv6(ip)) => {
+ let v6: Ipv6Addr = ip;
+ (v6.segments()[0] & 0xffc0) == 0xfe80
+ || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_link_local())
+ }
+ Some(url::Host::Domain(name)) => {
+ let name = name.trim_end_matches('.').to_ascii_lowercase();
+ name == "metadata.google.internal"
+ || name.parse::<IpAddr>().is_ok_and(|ip| match ip {
+ IpAddr::V4(v4) => v4.is_link_local(),
+ IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
+ })
+ }
+ None => false,
+ };
+ if link_local {
+ return Err("endpoint must not be a link-local or metadata address".to_string());
+ }
+ Ok(())
+}
+
+/// Validate a requested engine. No I/O.
+///
+/// # Errors
+///
+/// Unknown / non-selectable ids, a malformed endpoint or an unknown
+/// deployment.
+pub(super) fn prepare_target(params: EngineTargetParams) -> Result<Prepared, String> {
+ let raw = params.driver.trim();
+ let id = if raw == "tinycortex" { MODULE_ID } else { raw };
+ if id.is_empty() {
+ return Err("driver is required".to_string());
+ }
+ if id == MODULE_ID {
+ return Ok(Prepared {
+ id: MODULE_ID.to_string(),
+ endpoint: None,
+ deployment: None,
+ api_key: None,
+ takes_key: false,
+ });
+ }
+ let entry = available_engines()
+ .into_iter()
+ .find(|e| e.id == id)
+ .ok_or_else(|| {
+ if is_remote_engine(id) {
+ format!("memory engine '{id}' is not selectable")
+ } else {
+ format!("unknown memory engine '{id}'")
+ }
+ })?;
+
+ let endpoint = blank_to_none(params.endpoint);
+ if let Some(endpoint) = endpoint.as_deref() {
+ validate_endpoint(endpoint)?;
+ }
+ let hosted = entry.hosted || id == HOSTED_ENGINE_ID;
+ let deployment = blank_to_none(params.deployment);
+ if let Some(deployment) = deployment.as_deref().filter(|_| !hosted) {
+ if !entry.deployments.iter().any(|d| d == deployment) {
+ return Err(format!(
+ "deployment must be one of [{}]",
+ entry.deployments.join(", ")
+ ));
+ }
+ }
+ Ok(Prepared {
+ id: id.to_string(),
+ // First-party engines own their endpoint; a caller-supplied one is
+ // dropped so it can never redirect the session bearer.
+ endpoint: if hosted { None } else { endpoint },
+ deployment: if hosted { None } else { deployment },
+ api_key: if entry.needs_key {
+ blank_to_none(params.api_key)
+ } else {
+ None
+ },
+ takes_key: entry.needs_key && !hosted,
+ })
+}
+
+/// Build the provider a prepared target names, without binding or persisting
+/// anything.
+#[cfg(feature = "memory-remote")]
+pub(super) fn build_target_provider(
+ config: &Config,
+ prepared: &Prepared,
+) -> Result<std::sync::Arc<dyn crate::memory::api::provider::MemoryProvider>, String> {
+ use crate::memory::binding_remote::{build_engine, EngineTarget};
+ let target = EngineTarget {
+ id: prepared.id.clone(),
+ endpoint: prepared.endpoint.clone(),
+ deployment: prepared.deployment.clone(),
+ api_key: prepared.api_key.clone(),
+ credential_ref: prepared.takes_key.then(|| credential_ref_for(&prepared.id)),
+ };
+ build_engine(&config.workspace_dir, &config.api_url, &target)
+ .map_err(|e| classify_engine_message(&e))
+}
+
+#[cfg(not(feature = "memory-remote"))]
+pub(super) fn build_target_provider(
+ _config: &Config,
+ prepared: &Prepared,
+) -> Result<std::sync::Arc<dyn crate::memory::api::provider::MemoryProvider>, String> {
+ Err(format!(
+ "memory engine '{}' is not compiled into this build",
+ prepared.id
+ ))
+}
+
+/// Store an engine key in the keychain (never logged).
+fn store_key(config: &Config, id: &str, key: &str) -> Result<(), String> {
+ use crate::security::keyring_consent::{policy, PolicyDecision};
+ match policy::check_secret_access() {
+ PolicyDecision::Proceed => {}
+ PolicyDecision::ConsentRequired => {
+ return Err("keychain access is pending user consent".to_string())
+ }
+ PolicyDecision::Declined => return Err("keychain access was declined".to_string()),
+ }
+ if !crate::security::keyring::is_available() {
+ return Err("no keychain backend is available on this host".to_string());
+ }
+ let name = format!("{CREDENTIAL_NAME_PREFIX}{id}");
+ crate::security::keyring::set(&keyring_user_id(&config.workspace_dir), &name, key)
+ .map_err(|_| "could not store the engine key in the keychain".to_string())
+}
+
+fn env_pins_driver() -> bool {
+ std::env::var("OPENHUMAN_MEMORY_DRIVER")
+ .map(|v| !v.trim().is_empty())
+ .unwrap_or(false)
+}
+
+/// Persist `prepared` as the memory engine, then rebind in process.
+///
+/// Order: key → config → rebind. A failure before the config write leaves the
+/// previous engine active; the key write is the only step that survives a later
+/// failure, and it is harmless (an unused keychain entry).
+/// One process-wide lock serialises every engine switch (`engine_set` and a
+/// migration's commit), so two switches never interleave their config
+/// read-modify-write or their rebind.
+pub(super) static SWITCH_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// [`commit_engine_locked`] under the switch lock.
+pub(super) async fn commit_engine(prepared: &Prepared) -> Result<EngineState, String> {
+ let _switch = SWITCH_LOCK.lock().await;
+ commit_engine_locked(prepared).await
+}
+
+/// The commit itself; the caller holds [`SWITCH_LOCK`].
+///
+/// Reloads the config fresh and patches only `[subsystems.memory]` (the driver
+/// and that driver's entry), so a config edited while a migration ran, or a
+/// stale snapshot taken when the RPC started, is never written back. `from` is
+/// recomputed from that fresh config.
+pub(super) async fn commit_engine_locked(prepared: &Prepared) -> Result<EngineState, String> {
+ let mut config = load_config().await?;
+ if env_pins_driver() {
+ return Err(
+ "the memory engine is pinned by OPENHUMAN_MEMORY_DRIVER; unset it to switch engines"
+ .to_string(),
+ );
+ }
+ let from = normalized_driver(&config);
+ if let Some(key) = prepared.api_key.as_deref() {
+ store_key(&config, &prepared.id, key)?;
+ }
+
+ let memory = &mut config.subsystems.memory;
+ memory.driver = prepared.id.clone();
+ if prepared.id != MODULE_ID {
+ memory.drivers.insert(
+ prepared.id.clone(),
+ MemoryDriverConfig {
+ class: Some("external".to_string()),
+ transport: Some("http".to_string()),
+ endpoint: prepared.endpoint.clone(),
+ credential_ref: prepared.takes_key.then(|| credential_ref_for(&prepared.id)),
+ // The user chose this engine in the UI: that is the trust grant.
+ trust_state: "trusted".to_string(),
+ deployment: prepared.deployment.clone(),
+ },
+ );
+ }
+ config
+ .save()
+ .await
+ .map_err(|e| format!("could not save the memory engine setting: {e:#}"))?;
+ log::info!(
+ "{LOG_PREFIX} committed engine='{}' from='{from}' workspace={}",
+ prepared.id,
+ config.workspace_dir.display()
+ );
+ crate::memory::binding_remote::note_api_url(&config.workspace_dir, &config.api_url);
+ binding::rebind(&config.workspace_dir, &from, &config.subsystems.memory).map_err(|e| {
+ format!(
+ "the engine switch was saved but could not be applied in this session and takes \
+ effect after a restart: {e}"
+ )
+ })?;
+ state_for(&config)
+}
+
+/// Report the engine for `config`. Resolves (and if needed binds) the driver.
+pub(super) fn state_for(config: &Config) -> Result<EngineState, String> {
+ let binding = binding::for_config(config)?;
+ let driver = binding.driver_id().to_string();
+ let entry = config.subsystems.memory.drivers.get(&driver);
+ let hosted = driver == HOSTED_ENGINE_ID;
+ let endpoint = if hosted {
+ crate::backend::base_url(&config.api_url).ok()
+ } else {
+ entry.and_then(|e| e.endpoint.clone())
+ };
+ let has_credential = if hosted {
+ crate::security::credentials::session_support::backend_bearer_secret(config)
+ .ok()
+ .flatten()
+ .is_some_and(|t| !t.trim().is_empty())
+ } else {
+ entry
+ .and_then(|e| e.credential_ref.as_deref())
+ .and_then(|r| {
+ crate::security::credentials::credential_ref::CredentialRef::parse(r).ok()
+ })
+ .is_some_and(|r| r.resolve(&keyring_user_id(&config.workspace_dir)).is_ok())
+ };
+ Ok(EngineState {
+ driver,
+ endpoint,
+ deployment: entry.and_then(|e| e.deployment.clone()),
+ has_credential,
+ class: binding.class().as_str().to_string(),
+ fell_back_from: binding.fallback().map(|f| f.configured_driver.clone()),
+ last_error: binding.fallback().map(|f| f.reason.clone()),
+ })
+}
+
+async fn load_config() -> Result<Config, String> {
+ crate::config::rpc::load_config_with_timeout().await
+}
+
+/// `memory.engines_list`.
- pub async fn memory_engines_list() -> Result<RpcOutcome<EnginesList>, String> {
++pub async fn memory_engines_list() -> Result<Outcome<EnginesList>, String> {
+ let config = load_config().await?;
+ let active = state_for(&config).map_or_else(|_| normalized_driver(&config), |s| s.driver);
- Ok(RpcOutcome::new(
++ Ok(Outcome::new(
+ EnginesList {
+ engines: available_engines(),
+ active,
+ },
+ vec![],
+ ))
+}
+
+/// `memory.engine_get`.
- pub async fn memory_engine_get() -> Result<RpcOutcome<EngineState>, String> {
++pub async fn memory_engine_get() -> Result<Outcome<EngineState>, String> {
+ let config = load_config().await?;
- Ok(RpcOutcome::new(state_for(&config)?, vec![]))
++ Ok(Outcome::new(state_for(&config)?, vec![]))
+}
+
+/// `memory.engine_set`.
- pub async fn memory_engine_set(
- params: EngineTargetParams,
- ) -> Result<RpcOutcome<EngineState>, String> {
++pub async fn memory_engine_set(params: EngineTargetParams) -> Result<Outcome<EngineState>, String> {
+ let prepared = prepare_target(params)?;
+ // One switch at a time, and never while a migration owns the switch.
+ let _switch = SWITCH_LOCK.lock().await;
+ if super::engine_migrate::migration_running() {
+ return Err(
+ "a memory migration is running; wait for it to finish or cancel it before switching"
+ .to_string(),
+ );
+ }
+ log::debug!(
+ "{LOG_PREFIX} engine_set engine='{}' has_key={} has_endpoint={}",
+ prepared.id,
+ prepared.api_key.is_some(),
+ prepared.endpoint.is_some()
+ );
+ if prepared.id != MODULE_ID {
+ // Fail before touching the keychain or config when the engine cannot
+ // even be built (no transport, missing endpoint/key, bad deployment).
+ let config = load_config().await?;
+ build_target_provider(&config, &prepared)?;
+ }
+ let state = commit_engine_locked(&prepared).await?;
- Ok(RpcOutcome::new(state, vec![]))
++ Ok(Outcome::new(state, vec![]))
+}
+
+#[cfg(test)]
+#[path = "engine_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/memory/ops/engine_migrate.rs
index 929f9a2ada,0000000000..0a4987cf39
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/ops/engine_migrate.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_migrate.rs
@@@ -1,399 -1,0 +1,399 @@@
+//! `memory.engine_migrate` / `memory.engine_migrate_status` — copy everything
+//! from the active engine into another, then switch to it.
+//!
+//! The copy is `tinymemory::migrate::copy`: engine-neutral, at-least-once and
+//! non-destructive (the source keeps its data, and the target skips records it
+//! recognises), so a failed or repeated migration is safe and the previous
+//! engine stays usable. The switch is committed only after the copy finished
+//! with no failed records; on any failure the active engine is untouched.
+//!
+//! Jobs live in an in-process map (one at a time). They do not survive a
+//! restart: an interrupted migration is simply run again.
+//!
+//! - **Cancel** (`engine_migrate_cancel`): the copy future is raced against a
+//! cancel signal and dropped, which stops it between awaits (i.e. between
+//! pages). The previous engine is untouched.
+//! - **Timeout**: the whole copy is bounded by `OPENHUMAN_MEMORY_MIGRATE_TIMEOUT_SECS`
+//! (default 2 hours). A panic in the task also fails the job.
+//! - **Writes during the copy**: the export contract has no portable record
+//! timestamp, so no delta pass is attempted. A successful job carries a
+//! `note` saying records written while it ran may be missing from the new
+//! engine; the old engine still holds them and a second migration copies them
+//! (targets skip records they already have).
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use tokio::sync::Notify;
+
+use serde::{Deserialize, Serialize};
+
+use super::engine::{
+ build_target_provider, classify_engine_error, classify_engine_message, commit_engine,
+ prepare_target, EngineTargetParams, SWITCH_LOCK,
+};
+use crate::config::schema::Config;
+use crate::core::runtime::context::CoreContext;
++use crate::core::Outcome;
+use crate::memory::binding::{self, MODULE_ID};
- use crate::rpc::RpcOutcome;
+
+const LOG_PREFIX: &str = "[memory:engine-migrate]";
+/// Finished jobs kept for status polling.
+const MAX_FINISHED_JOBS: usize = 16;
+
+/// Parameters of `memory.engine_migrate`.
+#[derive(Clone, Deserialize)]
+pub struct MigrateParams {
+ pub to: EngineTargetParams,
+}
+
+/// Parameters of `memory.engine_migrate_cancel`.
+#[derive(Debug, Clone, Deserialize)]
+pub struct MigrateCancelParams {
+ pub job_id: String,
+}
+
+/// Result of `memory.engine_migrate_cancel`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct MigrateCancelled {
+ /// Whether a running job was signalled. `false` when it had already
+ /// finished (or is past the point of no return, committing the switch).
+ pub cancelled: bool,
+}
+
+/// Default bound on one migration's copy phase.
+const DEFAULT_TIMEOUT_SECS: u64 = 2 * 60 * 60;
+
+fn migrate_timeout() -> Duration {
+ let secs = std::env::var("OPENHUMAN_MEMORY_MIGRATE_TIMEOUT_SECS")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .filter(|s| *s > 0)
+ .unwrap_or(DEFAULT_TIMEOUT_SECS);
+ Duration::from_secs(secs)
+}
+
+/// Parameters of `memory.engine_migrate_status`.
+#[derive(Debug, Clone, Deserialize)]
+pub struct MigrateStatusParams {
+ pub job_id: String,
+}
+
+/// Result of `memory.engine_migrate`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct MigrateStarted {
+ pub job_id: String,
+}
+
+/// Result of `memory.engine_migrate_status`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct MigrateStatus {
+ /// `running` | `done` | `failed` | `cancelled`.
+ pub state: String,
+ /// Records read from the source and handed to the target so far.
+ pub copied: usize,
+ /// Total records when known; the export cursor does not report one.
+ pub total: Option<usize>,
+ pub error: Option<String>,
+ /// A caveat on a finished job (see the module docs on writes during the
+ /// copy); `None` otherwise.
+ pub note: Option<String>,
+}
+
+/// Cancel signals of the jobs in [`JOBS`].
+static CANCELS: OnceLock<Mutex<HashMap<String, Arc<Notify>>>> = OnceLock::new();
+
+fn cancels() -> std::sync::MutexGuard<'static, HashMap<String, Arc<Notify>>> {
+ CANCELS
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// Whether any migration job is still running. `engine_set` refuses meanwhile.
+pub(super) fn migration_running() -> bool {
+ jobs().values().any(|j| j.state == "running")
+}
+
+static JOBS: OnceLock<Mutex<HashMap<String, MigrateStatus>>> = OnceLock::new();
+
+fn jobs() -> std::sync::MutexGuard<'static, HashMap<String, MigrateStatus>> {
+ JOBS.get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+fn update_job(job_id: &str, f: impl FnOnce(&mut MigrateStatus)) {
+ if let Some(job) = jobs().get_mut(job_id) {
+ f(job);
+ }
+}
+
+fn fail_job(job_id: &str, error: String) {
+ log::warn!("{LOG_PREFIX} job={job_id} failed: {error}");
+ update_job(job_id, |j| {
+ j.state = "failed".to_string();
+ j.error = Some(error);
+ });
+}
+
+/// Register a new running job, refusing while another is running.
+fn start_job() -> Result<String, String> {
+ let mut map = jobs();
+ if map.values().any(|j| j.state == "running") {
+ return Err("a memory migration is already running".to_string());
+ }
+ // Only finished jobs can be here (a running one was refused above).
+ while map.len() >= MAX_FINISHED_JOBS {
+ let Some(oldest) = map.keys().next().cloned() else {
+ break;
+ };
+ map.remove(&oldest);
+ cancels().remove(&oldest);
+ }
+ let job_id = uuid::Uuid::new_v4().to_string();
+ map.insert(
+ job_id.clone(),
+ MigrateStatus {
+ state: "running".to_string(),
+ copied: 0,
+ total: None,
+ error: None,
+ note: None,
+ },
+ );
+ cancels().insert(job_id.clone(), Arc::new(Notify::new()));
+ Ok(job_id)
+}
+
+/// What a finished copy reports.
+struct CopyReport {
+ records: usize,
+ imported: usize,
+ skipped: usize,
+ failed: usize,
+ errors: Vec<String>,
+}
+
+#[cfg(feature = "memory-remote")]
+async fn run_copy(
+ source: &dyn crate::memory::api::provider::MemoryProvider,
+ target: &dyn crate::memory::api::provider::MemoryProvider,
+ on_progress: impl FnMut(usize),
+) -> anyhow::Result<CopyReport> {
+ let mut on_progress = on_progress;
+ let report = tinymemory::migrate::copy(source, target, |p| on_progress(p.records)).await?;
+ Ok(CopyReport {
+ records: report.records,
+ imported: report.imported,
+ skipped: report.skipped,
+ failed: report.failed,
+ errors: report.errors,
+ })
+}
+
+#[cfg(not(feature = "memory-remote"))]
+async fn run_copy(
+ _source: &dyn crate::memory::api::provider::MemoryProvider,
+ _target: &dyn crate::memory::api::provider::MemoryProvider,
+ _on_progress: impl FnMut(usize),
+) -> anyhow::Result<CopyReport> {
+ anyhow::bail!("memory engine migration is not compiled into this build")
+}
+
+/// How the copy phase ended.
+enum CopyEnd {
+ Finished(anyhow::Result<CopyReport>),
+ Cancelled,
+ TimedOut,
+}
+
+/// Run one job to a terminal state: copy (cancellable, bounded), then — only on
+/// a clean copy — `commit` the engine switch. Never panics into the caller; a
+/// failure at any point leaves the active engine unchanged.
+async fn run_job<F, Fut>(
+ job_id: String,
+ source: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ target: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ timeout: Duration,
+ commit: F,
+) where
+ F: FnOnce() -> Fut,
+ Fut: Future<Output = Result<(), String>>,
+{
+ let cancel = cancels().get(&job_id).cloned().unwrap_or_default();
+ let progress_id = job_id.clone();
+ let copy = run_copy(source.as_ref(), target.as_ref(), move |records| {
+ update_job(&progress_id, |j| j.copied = records);
+ });
+ // Dropping the copy future on cancel/timeout stops it at its next await,
+ // i.e. between export/import pages.
+ let end = tokio::select! {
+ result = tokio::time::timeout(timeout, copy) => match result {
+ Ok(result) => CopyEnd::Finished(result),
+ Err(_) => CopyEnd::TimedOut,
+ },
+ () = cancel.notified() => CopyEnd::Cancelled,
+ };
+ match end {
+ CopyEnd::Cancelled => {
+ log::info!("{LOG_PREFIX} job={job_id} cancelled");
+ update_job(&job_id, |j| j.state = "cancelled".to_string());
+ }
+ CopyEnd::TimedOut => fail_job(
+ &job_id,
+ format!(
+ "the migration timed out after {}s; the active engine was not changed",
+ timeout.as_secs()
+ ),
+ ),
+ CopyEnd::Finished(Err(error)) => fail_job(&job_id, classify_engine_error(&error)),
+ CopyEnd::Finished(Ok(report)) if report.failed > 0 => {
+ let first = report.errors.first().map_or("", String::as_str);
+ fail_job(
+ &job_id,
+ classify_engine_message(&format!(
+ "{} of {} records could not be copied; the active engine was not changed. {first}",
+ report.failed, report.records
+ )),
+ );
+ }
+ CopyEnd::Finished(Ok(report)) => {
+ update_job(&job_id, |j| j.copied = report.records);
+ match commit().await {
+ Ok(()) => {
+ log::info!(
+ "{LOG_PREFIX} job={job_id} done records={} imported={} skipped={}",
+ report.records,
+ report.imported,
+ report.skipped
+ );
+ update_job(&job_id, |j| {
+ j.state = "done".to_string();
+ j.note = Some(WRITES_DURING_COPY_NOTE.to_string());
+ });
+ }
+ Err(error) => fail_job(&job_id, classify_engine_message(&error)),
+ }
+ }
+ }
+}
+
+/// Shown on a finished job: what the copy cannot promise.
+const WRITES_DURING_COPY_NOTE: &str =
+ "Memories written while the copy was running may not have been \
+ copied. The previous engine still holds them; migrate again to copy any that are missing.";
+
+/// Spawn [`run_job`] under a supervisor so a panic fails the job instead of
+/// leaving it "running" forever.
+fn spawn_job<F, Fut>(
+ job_id: String,
+ source: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ target: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ timeout: Duration,
+ commit: F,
+) where
+ F: FnOnce() -> Fut + Send + 'static,
+ Fut: Future<Output = Result<(), String>> + Send + 'static,
+{
+ let worker_id = job_id.clone();
+ let worker = tokio::spawn(CoreContext::propagate(run_job(
+ worker_id, source, target, timeout, commit,
+ )));
+ tokio::spawn(async move {
+ if let Err(join_error) = worker.await {
+ let reason = if join_error.is_panic() {
+ "the migration task panicked; the active engine was not changed"
+ } else {
+ "the migration task was aborted; the active engine was not changed"
+ };
+ fail_job(&job_id, reason.to_string());
+ }
+ });
+}
+
+/// `memory.engine_migrate`.
+pub async fn memory_engine_migrate(
+ params: MigrateParams,
- ) -> Result<RpcOutcome<MigrateStarted>, String> {
++) -> Result<Outcome<MigrateStarted>, String> {
+ let config: Config = crate::config::rpc::load_config_with_timeout().await?;
+ let prepared = prepare_target(params.to)?;
+
+ let source_binding = binding::for_config(&config)?;
+ if source_binding.driver_id() == prepared.id && source_binding.fallback().is_none() {
+ return Err(format!("memory already uses engine '{}'", prepared.id));
+ }
+ if source_binding.disables_memory() {
+ return Err("memory is disabled (driver 'null'); there is nothing to migrate".to_string());
+ }
+ let source = Arc::clone(source_binding.provider());
+
+ // Build the target before the job exists, so a bad endpoint, a missing key
+ // or a missing backend transport answers this call instead of a poll.
+ let target = if prepared.id == MODULE_ID {
+ let mut cfg = config.subsystems.memory.clone();
+ cfg.driver = MODULE_ID.to_string();
+ Arc::clone(binding::for_subtree(&config.workspace_dir, "memory", &cfg)?.provider())
+ } else {
+ build_target_provider(&config, &prepared)?
+ };
+
+ // Registering the job under the switch lock keeps it from interleaving with
+ // an `engine_set` that has already checked for running jobs.
+ let job_id = {
+ let _switch = SWITCH_LOCK.lock().await;
+ start_job()?
+ };
+ log::info!(
+ "{LOG_PREFIX} job={job_id} started source='{}' target='{}'",
+ source_binding.driver_id(),
+ prepared.id
+ );
+
+ spawn_job(
+ job_id.clone(),
+ source,
+ target,
+ migrate_timeout(),
+ move || async move { commit_engine(&prepared).await.map(|_| ()) },
+ );
+
- Ok(RpcOutcome::new(MigrateStarted { job_id }, vec![]))
++ Ok(Outcome::new(MigrateStarted { job_id }, vec![]))
+}
+
+/// `memory.engine_migrate_cancel`.
+pub async fn memory_engine_migrate_cancel(
+ params: MigrateCancelParams,
- ) -> Result<RpcOutcome<MigrateCancelled>, String> {
++) -> Result<Outcome<MigrateCancelled>, String> {
+ let job_id = params.job_id.trim();
+ let running = jobs()
+ .get(job_id)
+ .map(|j| j.state == "running")
+ .ok_or_else(|| "unknown migration job".to_string())?;
+ let cancelled = running && {
+ if let Some(signal) = cancels().get(job_id) {
+ signal.notify_one();
+ true
+ } else {
+ false
+ }
+ };
- Ok(RpcOutcome::new(MigrateCancelled { cancelled }, vec![]))
++ Ok(Outcome::new(MigrateCancelled { cancelled }, vec![]))
+}
+
+/// `memory.engine_migrate_status`.
+pub async fn memory_engine_migrate_status(
+ params: MigrateStatusParams,
- ) -> Result<RpcOutcome<MigrateStatus>, String> {
++) -> Result<Outcome<MigrateStatus>, String> {
+ let status = jobs()
+ .get(params.job_id.trim())
+ .cloned()
+ .ok_or_else(|| "unknown migration job".to_string())?;
- Ok(RpcOutcome::new(status, vec![]))
++ Ok(Outcome::new(status, vec![]))
+}
+
+#[cfg(test)]
+#[path = "engine_migrate_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/memory/schemas/mod.rs
index fb9bd149e3,747c40db8e..bbd382cc6d
--- a/crates/openhuman-core/src/memory/schemas/mod.rs
+++ b/crates/openhuman-core/src/memory/schemas/mod.rs
@@@ -30,11 -28,10 +30,11 @@@ use serde::de::DeserializeOwned
use serde_json::{Map, Value};
use crate::core::all::RegisteredController;
+ use crate::core::Outcome;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
- use crate::rpc::RpcOutcome;
mod documents;
+mod engine;
mod files;
mod kv_graph;
mod learn;
diff --cc crates/openhuman-core/src/skills/webhooks/ops.rs
index 9f476f0af8,b58f68ab19..4456ef24c3
--- a/crates/openhuman-core/src/skills/webhooks/ops.rs
+++ b/crates/openhuman-core/src/skills/webhooks/ops.rs
@@@ -202,6 -200,14 +200,14 @@@ pub async fn trigger_agent
}),
format!("webhooks.trigger_agent deferred for {source}/{caller_id}"),
)),
- crate::agent::triage::TriageOutcome::Terminal { reason } => Ok(RpcOutcome::single_log(
++ crate::agent::triage::TriageOutcome::Terminal { reason } => Ok(Outcome::single_log(
+ serde_json::json!({
+ "decision": "terminal",
+ "resolution_path": "terminal",
+ "reason": reason,
+ }),
+ format!("webhooks.trigger_agent failed terminally for {source}/{caller_id}: {reason}"),
+ )),
}
}
diff --cc crates/openhuman-core/src/tools/impl/browser/browser.rs
index 287d12cece,6e07ca7260..516283ec66
--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs
@@@ -18,14 -26,12 +26,15 @@@ use std::
sync::{Arc, Mutex as StdMutex},
time::Instant,
};
- #[cfg(test)]
- use std::{collections::HashMap, time::Duration};
+ use task_actions::{approve_task_action, parse_action, required, task_inputs};
use tinycomputer_bus::agent::{ContinueTaskRequest, TaskId, TaskStatus, TaskView};
use tinycomputer_bus::browser::{
- Action, DownloadState, DownloadWaitRequest, LocateBy, Locator, NavigateRequest, ReadRequest,
- ScrollDirection, SessionId, SessionOptions, SnapshotRequest, Target, WaitState,
+ Action, DownloadState, DownloadWaitRequest, NavigateRequest, ReadRequest, SessionId,
- SessionOptions, SnapshotRequest, Target,
++ SessionOptions, SnapshotRequest,
};
++// Only the colocated tests name `Target` (through `use super::*`).
++#[cfg(test)]
++use tinycomputer_bus::browser::Target;
use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};
use tokio::sync::Mutex;
@@@ -524,136 -457,7 +460,6 @@@ impl BrowserTool
}
}
- fn task_inputs(args: &Value) -> anyhow::Result<BTreeMap<String, String>> {
- args["inputs"].as_object().map_or_else(
- || Ok(BTreeMap::new()),
- |inputs| {
- inputs
- .iter()
- .map(|(k, v)| {
- Ok((
- k.clone(),
- v.as_str()
- .ok_or_else(|| anyhow::anyhow!("Task input '{k}' must be text"))?
- .to_owned(),
- ))
- })
- .collect()
- },
- )
- }
-
- /// Ask the host approval gate about a paused task's exact action. A missing
- /// gate denies: a task never takes an irreversible step unapproved.
- async fn approve_task_action(pending: &Pending) -> anyhow::Result<bool> {
- let gate = ApprovalGate::try_global().ok_or_else(|| {
- anyhow::anyhow!("[policy-denied] Browser action needs an interactive host approval gate")
- })?;
- let clean = |raw: &str| {
- let cleaned = raw.chars().filter(|c| !c.is_control()).collect::<String>();
- let mut short = cleaned.chars().take(160).collect::<String>();
- if cleaned.chars().count() > 160 {
- short.push('…');
- }
- short
- };
- let digest = Sha256::digest(serde_json::to_vec(&json!({
- "task": pending.task, "action": pending.action, "target": pending.target
- }))?);
- let digest_hex = format!("{digest:x}");
- let summary = format!(
- "Browser task: {} — {} [action {}]",
- clean(&pending.action),
- clean(&pending.target),
- &digest_hex[..12]
- );
- let args = json!({"action": "task_step", "target": summary, "exact_action_sha256": digest_hex});
- Ok(
- match gate.intercept_forced("browser", &summary, args).await {
- GateOutcome::Allow => true,
- GateOutcome::Deny { reason } => {
- tracing::debug!(%reason, "[browser] task action denied by host");
- false
- }
- },
- )
- }
-
- fn required<'a>(args: &'a Value, key: &str) -> anyhow::Result<&'a str> {
- args.get(key)
- .and_then(Value::as_str)
- .filter(|s| !s.trim().is_empty())
- .ok_or_else(|| anyhow::anyhow!("Missing '{key}' parameter"))
- }
-
- fn parse_action(args: &Value) -> anyhow::Result<Action> {
- let target = || required(args, "selector").map(Target::parse);
- Ok(match required(args, "action")? {
- "click" => Action::Click {
- target: target()?,
- new_tab: false,
- },
- "fill" => Action::Fill {
- target: target()?,
- value: required(args, "value")?.into(),
- },
- "type" => Action::Type {
- target: args["selector"].as_str().map(Target::parse),
- text: required(args, "text")?.into(),
- delay_ms: None,
- },
- "get_text" => Action::GetText { target: target()? },
- "is_visible" => Action::IsVisible { target: target()? },
- "hover" => Action::Hover { target: target()? },
- "press" => Action::Press {
- key: required(args, "key")?.into(),
- },
- "scroll" => Action::Scroll {
- direction: match required(args, "direction")? {
- "up" => ScrollDirection::Up,
- "down" => ScrollDirection::Down,
- "left" => ScrollDirection::Left,
- "right" => ScrollDirection::Right,
- x => anyhow::bail!("Invalid direction: {x}"),
- },
- pixels: args["pixels"].as_u64().and_then(|v| u32::try_from(v).ok()),
- target: None,
- },
- "wait" => Action::WaitFor {
- target: args["selector"].as_str().map(Target::parse),
- text: args["text"].as_str().map(str::to_owned),
- state: WaitState::Visible,
- ms: args["ms"].as_u64(),
- timeout_ms: args["timeout_ms"].as_u64(),
- },
- "find" => {
- let by = match required(args, "by")? {
- "role" => LocateBy::Role,
- "text" => LocateBy::Text,
- "label" => LocateBy::Label,
- "placeholder" => LocateBy::Placeholder,
- "testid" => LocateBy::TestId,
- x => anyhow::bail!("Invalid locator: {x}"),
- };
- let target = Target::locator(Locator::new(by, required(args, "value")?));
- match required(args, "find_action")? {
- "click" => Action::Click {
- target,
- new_tab: false,
- },
- "fill" => Action::Fill {
- target,
- value: required(args, "fill_value")?.into(),
- },
- "text" => Action::GetText { target },
- "hover" => Action::Hover { target },
- x => anyhow::bail!("Invalid find action: {x}"),
- }
- }
- x => anyhow::bail!("Unsupported browser action: {x}"),
- })
- }
--
#[async_trait]
impl Tool for BrowserTool {
fn exposure(&self) -> tinytools::ToolExposure {
diff --cc tests/support/memory_engine_fixture.rs
index ddd5b87840,0000000000..8360927b45
mode 100644,000000..100644
--- a/tests/support/memory_engine_fixture.rs
+++ b/tests/support/memory_engine_fixture.rs
@@@ -1,531 -1,0 +1,531 @@@
+//! Shared harness for the memory-engine e2e suites: a hosted-CortexDB double,
+//! env isolation, and a `Fixture` that boots the JSON-RPC router with the
+//! module loaded and a backend API key stored.
+//!
+//! Include with `#[path = "support/memory_engine_fixture.rs"] mod fixture;`.
+
+#![allow(dead_code, clippy::await_holding_lock)]
+
+#[path = "memory_module.rs"]
+pub mod memory_module;
+#[path = "tinyhumans_boot.rs"]
+pub mod tinyhumans_boot;
+
+use std::collections::HashSet;
+use std::net::SocketAddr;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::extract::{Query, State};
+use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use serde_json::{json, Value};
+use tempfile::tempdir;
+
+use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
- use openhuman_core::core::jsonrpc::build_core_http_router;
++use openhuman_rpc::server::build_core_http_router;
+
+pub const TEST_RPC_TOKEN: &str = "memory-engine-e2e-token";
+pub const TEST_API_KEY: &str = "tiny_live_memory_engine_e2e";
+pub const NS: &str = "engine-e2e";
+
+// ── Hosted CortexDB double ──────────────────────────────────────────────────
+
+#[derive(Default)]
+pub struct HostedState {
+ pub events: Mutex<Vec<Value>>,
+ pub idempotency: Mutex<std::collections::BTreeMap<String, (String, String)>>,
+ pub claims: Mutex<HashSet<String>>,
+ pub bearers: Mutex<Vec<String>>,
+ pub next_id: Mutex<u64>,
+ /// When non-zero every `/memory/*` call fails with this status.
+ pub force_status: AtomicU16,
+ /// Milliseconds every `experience` write is delayed by (0 = none).
+ pub delay_ms: AtomicU64,
+}
+
+pub type Hosted = Arc<HostedState>;
+
+pub fn err(status: u16, code: &str) -> (StatusCode, Json<Value>) {
+ (
+ StatusCode::from_u16(status).unwrap(),
+ Json(json!({ "success": false, "error": format!("failed: {code}"), "errorCode": code })),
+ )
+}
+
+pub fn ok(data: Value) -> (StatusCode, Json<Value>) {
+ (
+ StatusCode::OK,
+ Json(json!({ "success": true, "data": data })),
+ )
+}
+
+pub fn gate(state: &Hosted, headers: &HeaderMap) -> Option<(StatusCode, Json<Value>)> {
+ let token = headers
+ .get(AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .unwrap_or_default()
+ .to_string();
+ state.bearers.lock().unwrap().push(token.clone());
+ if token.is_empty() {
+ return Some(err(401, "UNAUTHORIZED"));
+ }
+ match state.force_status.load(Ordering::SeqCst) {
+ 0 => None,
+ 401 => Some(err(401, "UNAUTHORIZED")),
+ 402 => Some(err(402, "USER_INSUFFICIENT_CREDITS")),
+ other => Some(err(other, "UPSTREAM_ERROR")),
+ }
+}
+
+pub async fn experience(
+ State(state): State<Hosted>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+) -> (StatusCode, Json<Value>) {
+ if let Some(early) = gate(&state, &headers) {
+ return early;
+ }
+ let delay = state.delay_ms.load(Ordering::SeqCst);
+ if delay > 0 {
+ tokio::time::sleep(Duration::from_millis(delay)).await;
+ }
+ if let Some(claim) = headers.get("idempotency-key").and_then(|v| v.to_str().ok()) {
+ if !state.claims.lock().unwrap().insert(claim.to_string()) {
+ return err(409, "CONFLICT");
+ }
+ }
+ let key = body["idempotency_key"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ let text = body["content"]["text"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ if let Some((seen, id)) = state.idempotency.lock().unwrap().get(&key) {
+ return if seen == &text {
+ ok(json!({ "event_id": id, "replayed_from_idempotency": true }))
+ } else {
+ err(409, "IDEMPOTENCY_CONFLICT")
+ };
+ }
+ let id = {
+ let mut next = state.next_id.lock().unwrap();
+ *next += 1;
+ format!("evt_{}", *next)
+ };
+ let offset = state.events.lock().unwrap().len() as u64 * 2 + 2;
+ state
+ .idempotency
+ .lock()
+ .unwrap()
+ .insert(key, (text, id.clone()));
+ state.events.lock().unwrap().push(json!({
+ "id": id,
+ "scope": body["scope"],
+ "modality": body["modality"],
+ "wal_offset": offset,
+ "content": body["content"],
+ "context": { "recorded_at": "2026-09-02T00:00:00Z" },
+ }));
+ ok(json!({ "event_id": id, "status": "captured", "replayed_from_idempotency": false }))
+}
+
+pub async fn events(
+ State(state): State<Hosted>,
+ headers: HeaderMap,
+ Query(params): Query<std::collections::BTreeMap<String, String>>,
+) -> (StatusCode, Json<Value>) {
+ if let Some(early) = gate(&state, &headers) {
+ return early;
+ }
+ let scope = params.get("scope").cloned().unwrap_or_default();
+ let cursor: usize = params
+ .get("cursor")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(0);
+ let limit: usize = params
+ .get("limit")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(50);
+ let mut stream = Vec::new();
+ for event in state.events.lock().unwrap().iter().rev() {
+ if event["scope"].as_str() == Some(scope.as_str()) {
+ stream.push(event.clone());
+ stream.push(event.clone());
+ }
+ }
+ let page: Vec<Value> = stream.iter().skip(cursor).take(limit).cloned().collect();
+ let next = cursor + page.len();
+ ok(json!({ "items": page, "has_more": next < stream.len(), "next_cursor": next.to_string() }))
+}
+
+pub async fn recall(
+ State(state): State<Hosted>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+) -> (StatusCode, Json<Value>) {
+ if let Some(early) = gate(&state, &headers) {
+ return early;
+ }
+ let scope = body["scope"].as_str().unwrap_or_default();
+ let query = body["query"].as_str().unwrap_or_default().to_lowercase();
+ let hits: Vec<Value> = state
+ .events
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|e| e["scope"].as_str() == Some(scope))
+ .filter(|e| {
+ query.is_empty()
+ || e["content"]["text"]
+ .as_str()
+ .is_some_and(|t| t.to_lowercase().contains(&query))
+ })
+ .map(|e| {
+ let mut hit = e.clone();
+ if let Some(text) = e["content"]["text"].as_str() {
+ hit["content"]["text"] = json!(format!("[user] {text}"));
+ }
+ hit
+ })
+ .collect();
+ ok(json!({ "pack_id": "pack_test", "layers": { "events": hits } }))
+}
+
+pub async fn scopes(
+ State(state): State<Hosted>,
+ headers: HeaderMap,
+ Query(params): Query<std::collections::HashMap<String, String>>,
+) -> (StatusCode, Json<Value>) {
+ if let Some(early) = gate(&state, &headers) {
+ return early;
+ }
+ let limit: usize = params
+ .get("limit")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(50);
+ let mut paths: Vec<String> = state
+ .events
+ .lock()
+ .unwrap()
+ .iter()
+ .filter_map(|e| e["scope"].as_str().map(str::to_string))
+ .collect();
+ paths.sort();
+ paths.dedup();
+ paths.truncate(limit);
+ ok(json!({ "items": paths.into_iter().map(|p| json!({ "path": p })).collect::<Vec<_>>() }))
+}
+
+pub async fn forget(
+ State(state): State<Hosted>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+) -> (StatusCode, Json<Value>) {
+ if let Some(early) = gate(&state, &headers) {
+ return early;
+ }
+ let ids: Vec<String> = body["selector"]["memory_ids"]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect()
+ })
+ .unwrap_or_default();
+ let before = state.events.lock().unwrap().len();
+ state
+ .events
+ .lock()
+ .unwrap()
+ .retain(|e| !ids.contains(&e["id"].as_str().unwrap_or_default().to_string()));
+ let deleted = before - state.events.lock().unwrap().len();
+ ok(json!({ "deleted": { "events": deleted }, "requested": ids.len(), "matched": deleted }))
+}
+
+pub async fn start_hosted() -> (String, Hosted) {
+ let state: Hosted = Arc::new(HostedState::default());
+ let app = Router::new()
+ .route("/memory/experience", post(experience))
+ .route("/memory/events", get(events))
+ .route("/memory/recall", post(recall))
+ .route("/memory/forget", post(forget))
+ .route("/memory/scopes", get(scopes))
+ .with_state(state.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr: SocketAddr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await });
+ (format!("http://{addr}"), state)
+}
+
+// ── Harness ─────────────────────────────────────────────────────────────────
+
+pub struct EnvVarGuard {
+ key: &'static str,
+ old: Option<String>,
+}
+
+impl EnvVarGuard {
+ pub fn set_to_path(key: &'static str, path: &Path) -> Self {
+ let old = std::env::var(key).ok();
+ std::env::set_var(key, path.as_os_str());
+ Self { key, old }
+ }
+ pub fn unset(key: &'static str) -> Self {
+ let old = std::env::var(key).ok();
+ std::env::remove_var(key);
+ Self { key, old }
+ }
+}
+
+impl Drop for EnvVarGuard {
+ fn drop(&mut self) {
+ match &self.old {
+ Some(v) => std::env::set_var(self.key, v),
+ None => std::env::remove_var(self.key),
+ }
+ }
+}
+
+pub static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+pub static KEYRING_INIT: OnceLock<()> = OnceLock::new();
+pub static AUTH_INIT: OnceLock<()> = OnceLock::new();
+pub static SEAMS_INIT: OnceLock<()> = OnceLock::new();
+
+pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ KEYRING_INIT.get_or_init(|| unsafe {
+ std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
+ });
+ match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ }
+}
+
+/// The one workspace the process's memory module and every case share.
+pub fn shared_workspace() -> &'static Path {
+ static SHARED: OnceLock<PathBuf> = OnceLock::new();
+ SHARED.get_or_init(|| {
+ let tmp = tempdir().expect("shared workspace tempdir");
+ let path = tmp.path().join("workspace");
+ std::fs::create_dir_all(&path).expect("shared workspace dir");
+ std::mem::forget(tmp);
+ path
+ })
+}
+
+/// The config file that workspace resolves to (legacy sibling layout).
+pub fn shared_config_path() -> PathBuf {
+ shared_workspace()
+ .parent()
+ .expect("workspace parent")
+ .join(".openhuman")
+ .join("config.toml")
+}
+
+pub fn ensure_seams() {
+ SEAMS_INIT.get_or_init(|| {
+ std::thread::Builder::new()
+ .name("memory-engine-e2e-seams".to_string())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(|| {
+ let config = Arc::new(openhuman_core::config::Config {
+ workspace_dir: shared_workspace().to_path_buf(),
+ ..openhuman_core::config::Config::default()
+ });
+ #[cfg(feature = "modules")]
+ openhuman_core::modules::memory::set_modules_policy(config);
+ #[cfg(not(feature = "modules"))]
+ let _ = config;
+ })
+ .expect("spawn seam installer")
+ .join()
+ .expect("seam installer panicked");
+ });
+}
+
+pub fn ensure_rpc_auth() {
+ AUTH_INIT.get_or_init(|| {
+ tinyhumans_boot::boot();
+ unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
+ let dir = std::env::temp_dir().join("openhuman-memory-engine-e2e-auth");
+ init_rpc_token(&dir).expect("init rpc token");
+ });
+}
+
+pub fn run_on_big_stack<F, Fut>(name: &str, factory: F)
+where
+ F: FnOnce() -> Fut + Send + 'static,
+ Fut: std::future::Future<Output = ()> + 'static,
+{
+ std::thread::Builder::new()
+ .name(name.to_string())
+ .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(move || {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .enable_all()
+ .build()
+ .expect("runtime");
+ rt.block_on(factory());
+ })
+ .expect("spawn")
+ .join()
+ .expect("test body panicked");
+}
+
+pub async fn rpc(base: &str, method: &str, params: Value) -> Value {
+ let resp = reqwest::Client::builder()
+ .timeout(Duration::from_secs(120))
+ .build()
+ .unwrap()
+ .post(format!("{base}/rpc"))
+ .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params }))
+ .send()
+ .await
+ .unwrap_or_else(|e| panic!("POST {method}: {e}"));
+ assert!(
+ resp.status().is_success(),
+ "HTTP {} for {method}",
+ resp.status()
+ );
+ resp.json().await.expect("json body")
+}
+
+pub fn result_of<'a>(v: &'a Value, ctx: &str) -> &'a Value {
+ if let Some(e) = v.get("error") {
+ panic!("{ctx}: JSON-RPC error: {e}");
+ }
+ let r = v
+ .get("result")
+ .unwrap_or_else(|| panic!("{ctx}: no result: {v}"));
+ if r.get("logs").is_some() {
+ r.get("result").unwrap_or(r)
+ } else {
+ r
+ }
+}
+
+pub fn error_message(v: &Value, ctx: &str) -> String {
+ v.pointer("/error/message")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("{ctx}: expected a JSON-RPC error, got {v}"))
+ .to_string()
+}
+
+/// Everything a case needs: the hosted double, the RPC base URL and the env.
+pub struct Fixture {
+ pub _lock: std::sync::MutexGuard<'static, ()>,
+ pub _guards: Vec<EnvVarGuard>,
+ pub _tmp: tempfile::TempDir,
+ pub hosted: Hosted,
+ pub origin: String,
+ pub base: String,
+ pub join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
+}
+
+impl Fixture {
+ pub async fn new() -> Self {
+ let lock = env_lock();
+ let tmp = tempdir().expect("home tempdir");
+ let guards = vec![
+ EnvVarGuard::set_to_path("HOME", tmp.path()),
+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", shared_workspace()),
+ EnvVarGuard::unset("OPENHUMAN_MEMORY_DRIVER"),
+ EnvVarGuard::unset("BACKEND_URL"),
+ EnvVarGuard::unset("VITE_BACKEND_URL"),
+ EnvVarGuard::unset("OPENHUMAN_BACKEND_API_KEY"),
+ ];
+ ensure_rpc_auth();
+ ensure_seams();
+ let (origin, hosted) = start_hosted().await;
+
+ // A fresh config every case: the previous case's committed engine must
+ // not leak into this one.
+ let config_path = shared_config_path();
+ std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
+ std::fs::write(
+ &config_path,
+ format!(
+ "api_url = \"{origin}\"\ndefault_model = \"e2e-mock-model\"\n\n[secrets]\nencrypt = false\n"
+ ),
+ )
+ .unwrap();
+
+ memory_module::settle().await;
+ let config = openhuman_core::config::load_config_with_timeout()
+ .await
+ .expect("load config");
+ openhuman_core::security::credentials::api_key::store_api_key(&config, TEST_API_KEY)
+ .expect("store the backend api key");
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let app = build_core_http_router(false);
+ let join = tokio::spawn(async move { axum::serve(listener, app).await });
+ Self {
+ _lock: lock,
+ _guards: guards,
+ _tmp: tmp,
+ hosted,
+ origin,
+ base: format!("http://{addr}"),
+ join,
+ }
+ }
+
+ pub async fn call(&self, method: &str, params: Value) -> Value {
+ rpc(&self.base, method, params).await
+ }
+
+ pub async fn state(&self) -> Value {
+ let v = self.call("openhuman.memory_engine_get", json!({})).await;
+ result_of(&v, "engine_get").clone()
+ }
+
+ /// Poll a migration job to a terminal state.
+ pub async fn wait_job(&self, job_id: &str) -> Value {
+ for _ in 0..200 {
+ let v = self
+ .call(
+ "openhuman.memory_engine_migrate_status",
+ json!({ "job_id": job_id }),
+ )
+ .await;
+ let status = result_of(&v, "engine_migrate_status").clone();
+ if status["state"] != "running" {
+ return status;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("migration job {job_id} did not finish");
+ }
+
+ pub async fn put_doc(&self, key: &str, content: &str) {
+ let v = self
+ .call(
+ "openhuman.memory_doc_put",
+ json!({
+ "namespace": NS, "key": key, "title": key, "content": content,
+ "source_type": "doc", "priority": "medium", "tags": [],
+ "metadata": null, "category": "core"
+ }),
+ )
+ .await;
+ result_of(&v, "doc_put");
+ }
+}
+
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ self.join.abort();
+ }
+}