Skip to content

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

feat(memory): run the layout migration from the app

M3gA-Mindbb6383f8c06d
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index 4048f496ce..353a0fcaf8 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -71,6 +71,11 @@ pub async fn run_system_job(config: &crate::config::Config, job: &str) {
}
BACKGROUND_JOB => {
super::import::resume_interrupted(config).await;
+ super::layout_migration::tick(
+ config,
+ std::sync::Arc::new(super::layout_migration::AppHost),
+ std::sync::Arc::new(super::import::scheduler_paused),
+ );
super::lifecycle::jobs::run_due(config).await;
}
_ => {}
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 3bd32d3900..da5ab60a3a 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -327,7 +327,7 @@ pub(crate) type PauseCheck = Arc<dyn Fn() -> bool + Send + Sync>;
pub(crate) type BillingCheck = Arc<dyn Fn(&Config) -> bool + Send + Sync>;
/// The scheduler's pause, which includes being signed out.
-fn scheduler_paused() -> bool {
+pub(crate) fn scheduler_paused() -> bool {
matches!(
crate::cron::scheduler_gate::current_policy(),
crate::cron::scheduler_gate::Policy::Paused { .. }
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
new file mode 100644
index 0000000000..24dc4b0c5f
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
@@ -0,0 +1,61 @@
+//! The host the app runs the migration with: the two engines from
+//! `memory::engine::bind_with_root`, placement and the switch from
+//! `memory::scope`, and the free period from `memory::billing`.
+
+use async_trait::async_trait;
+
+use super::copy::Engines;
+use super::host::LayoutHost;
+use super::map::{FlowPlacement, Placement};
+use crate::config::Config;
+use crate::memory::engine::{self, CORTEXDB_ENGINE};
+use crate::memory::error::{MemoryError, MemoryResult};
+use crate::memory::scope::{self, MemoryIdentity};
+
+/// The app's [`LayoutHost`].
+pub struct AppHost;
+
+#[async_trait]
+impl LayoutHost for AppHost {
+ fn engines(&self, config: &Config) -> MemoryResult<Engines> {
+ let root = scope::user_root(config).ok_or_else(|| {
+ MemoryError::Off("sign in to move memory into its own layout".to_string())
+ })?;
+ Ok(Engines {
+ legacy: engine::bind_with_root(config, None)?.engine,
+ tree: engine::bind_with_root(config, Some(&root))?.engine,
+ })
+ }
+
+ fn placement(&self, config: &Config) -> MemoryResult<Placement> {
+ let layout = MemoryIdentity::root().resolve(config).layout;
+ let chat_node = scope::chat_node(&layout);
+ Ok(Placement {
+ layout,
+ chat_node,
+ flows: FlowPlacement::WithRoot,
+ })
+ }
+
+ fn is_switched(&self, config: &Config) -> bool {
+ scope::layout_is_v3(config)
+ }
+
+ async fn switch(&self, _config: &Config) -> MemoryResult<()> {
+ scope::switch_to_v3().await
+ }
+
+ async fn free_now(&self, config: &Config) -> bool {
+ crate::memory::billing::free_period_active(config).await
+ }
+
+ fn shared_legacy(&self, config: &Config) -> bool {
+ // 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.
+ config.memory.engine.trim() == CORTEXDB_ENGINE
+ }
+}
+
+#[cfg(test)]
+#[path = "app_host_tests.rs"]
+mod tests;
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.rs
new file mode 100644
index 0000000000..2c44e0e1ec
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
@@ -0,0 +1,47 @@
+use std::sync::Arc;
+
+use tinymemory_api::conformance::ReferenceEngine;
+use tinymemory_api::MemoryEngine;
+
+use super::*;
+use crate::memory::engine::install_test_engine_for_root;
+use crate::memory::layout_migration::service::scan;
+use crate::memory::layout_migration::test_host::{count, fact};
+
+const ACCOUNT: &str = "0123456789abcdef01234567";
+
+/// A config that lives where a signed-in account's does.
+fn signed_in(tmp: &tempfile::TempDir) -> Config {
+ let mut config = crate::memory::test_fixtures::config_in(tmp);
+ config.config_path = tmp.path().join("users").join(ACCOUNT).join("config.toml");
+ config
+}
+
+#[tokio::test]
+async fn signed_out_there_is_nothing_to_move() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = crate::memory::test_fixtures::config_in(&tmp);
+ assert!(matches!(AppHost.engines(&config), Err(MemoryError::Off(_))));
+ assert!(!scan(&config, &AppHost).await.unwrap().needed);
+}
+
+#[tokio::test]
+async fn binds_the_legacy_tree_and_the_users_own() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = signed_in(&tmp);
+ let root = format!("user:{ACCOUNT}");
+ let legacy = Arc::new(ReferenceEngine::new());
+ let tree = Arc::new(ReferenceEngine::new());
+ install_test_engine_for_root(&config.workspace_dir, None, legacy.clone());
+ install_test_engine_for_root(&config.workspace_dir, Some(&root), tree.clone());
+ legacy.store(fact("legacy fact")).await.unwrap();
+
+ let engines = AppHost.engines(&config).unwrap();
+ assert_eq!(count(&*engines.legacy).await, 1);
+ assert_eq!(count(&*engines.tree).await, 0);
+ assert!(scan(&config, &AppHost).await.unwrap().needed);
+
+ let placement = AppHost.placement(&config).unwrap();
+ assert!(placement.chat_node.to_string().ends_with("ws:main"));
+ assert!(matches!(placement.flows, FlowPlacement::WithRoot));
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
index eed71d1703..143646b7f7 100644
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -12,6 +12,7 @@
//! engines. Binding the two engines, the switch to the per-user tree, the
//! catch-up pass, cleanup and the RPCs build on it.
+pub mod app_host;
pub mod cleanup;
pub mod copy;
pub mod host;
@@ -23,10 +24,11 @@ pub mod state;
#[cfg(test)]
mod test_host;
+pub use app_host::AppHost;
pub use cleanup::cleanup;
pub use copy::{copy, legacy_present, Engines};
pub use host::LayoutHost;
pub use job::{run, Outcome, Trigger};
pub use map::{FlowPlacement, Placement};
-pub use service::{retry, scan, start, status, tick, MigrationStatus, ScanView};
+pub use service::{retry, scan, start, status, tick, MigrationStatus, ScanView, StartParams};
pub use state::{MigrationState, Phase};
diff --git a/crates/openhuman-core/src/memory/layout_migration/service.rs b/crates/openhuman-core/src/memory/layout_migration/service.rs
index 9c7cb2207b..e497677e89 100644
--- a/crates/openhuman-core/src/memory/layout_migration/service.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/service.rs
@@ -27,6 +27,14 @@ use crate::memory::error::{MemoryError, MemoryResult};
/// Workspaces with a migration running now.
static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+/// `memory_migration_start` params.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+pub struct StartParams {
+ /// The user's consent to take a legacy tree other accounts may share.
+ #[serde(default)]
+ pub takeover: bool,
+}
+
/// What [`scan`] found.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ScanView {
@@ -60,10 +68,12 @@ pub async fn scan(config: &Config, host: &dyn LayoutHost) -> MemoryResult<ScanVi
let shared = host.shared_legacy(config);
let needed = match state.phase {
Phase::Cleaned => false,
- Phase::Idle if !state.switched => {
- let engines = host.engines(config)?;
- legacy_present(&*engines.legacy).await?
- }
+ Phase::Idle if !state.switched => match host.engines(config) {
+ // Memory off or signed out: nothing to show.
+ Err(MemoryError::Off(_)) => false,
+ Err(error) => return Err(error),
+ Ok(engines) => legacy_present(&*engines.legacy).await?,
+ },
_ => true,
};
Ok(ScanView { needed, shared })
diff --git a/crates/openhuman-core/src/memory/schemas.rs b/crates/openhuman-core/src/memory/schemas.rs
index 6cce875394..eed4022a2f 100644
--- a/crates/openhuman-core/src/memory/schemas.rs
+++ b/crates/openhuman-core/src/memory/schemas.rs
@@ -57,6 +57,10 @@ fn handler_for(function: &str) -> crate::core::all::ControllerHandler {
"import_scan" => handlers::import_scan,
"import_start" => handlers::import_start,
"import_retry_failed" => handlers::import_retry_failed,
+ "migration_scan" => handlers::migration_scan,
+ "migration_start" => handlers::migration_start,
+ "migration_status" => handlers::migration_status,
+ "migration_retry" => handlers::migration_retry,
_ => handlers::import_status,
}
}
diff --git a/crates/openhuman-core/src/memory/schemas/defs.rs b/crates/openhuman-core/src/memory/schemas/defs.rs
index 405dfc15bb..4c46c619b5 100644
--- a/crates/openhuman-core/src/memory/schemas/defs.rs
+++ b/crates/openhuman-core/src/memory/schemas/defs.rs
@@ -4,7 +4,7 @@
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
/// Every function of the namespace, in spec order.
-pub const FUNCTIONS: [&str; 30] = [
+pub const FUNCTIONS: [&str; 34] = [
"engines_list",
"engine_get",
"engine_set",
@@ -35,6 +35,10 @@ pub const FUNCTIONS: [&str; 30] = [
"import_start",
"import_status",
"import_retry_failed",
+ "migration_scan",
+ "migration_start",
+ "migration_status",
+ "migration_retry",
];
fn field(name: &'static str, ty: TypeSchema, comment: &'static str, required: bool) -> FieldSchema {
@@ -369,6 +373,34 @@ pub fn schema(function: &str) -> ControllerSchema {
inputs: vec![],
outputs: out("{state: ImportState}"),
},
+ "migration_scan" => ControllerSchema {
+ namespace: "memory",
+ function: "migration_scan",
+ description: "Whether memory from before the per-user layout is left to move.",
+ inputs: vec![],
+ outputs: out("{needed: bool, shared: bool}"),
+ },
+ "migration_start" => ControllerSchema {
+ namespace: "memory",
+ function: "migration_start",
+ description: "Move memory from before the per-user layout now. takeover: true agrees to take a legacy tree other accounts on this machine may share.",
+ inputs: vec![opt("takeover", TypeSchema::Bool, "Consent to take a shared legacy tree.")],
+ outputs: out("{state: MigrationState, running: bool, interrupted: bool}"),
+ },
+ "migration_status" => ControllerSchema {
+ namespace: "memory",
+ function: "migration_status",
+ description: "Progress of the move into the per-user layout.",
+ inputs: vec![],
+ outputs: out("{state: MigrationState, running: bool, interrupted: bool}"),
+ },
+ "migration_retry" => ControllerSchema {
+ namespace: "memory",
+ function: "migration_retry",
+ description: "Put the items the move could not store back in line for the next run.",
+ inputs: vec![],
+ outputs: out("MigrationState"),
+ },
_ => ControllerSchema {
namespace: "memory",
function: "unknown",
diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rs
index b326ae52a6..0436144694 100644
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@ -16,7 +16,7 @@ use crate::memory::types::{
ItemsListParams, LearnParams, RecallParams, SourceAddedView, SourceRemovedView,
SourcesAddParams, SourcesListView, SourcesRemoveParams, SourcesSyncParams, SourcesSyncView,
};
-use crate::memory::{backfill, brain, engine, import, ops, sources};
+use crate::memory::{backfill, brain, engine, import, layout_migration, ops, sources};
fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
serde_json::from_value(Value::Object(params))
@@ -295,3 +295,41 @@ pub(super) fn import_retry_failed(params: Map<String, Value>) -> ControllerFutur
)
})
}
+
+pub(super) fn migration_scan(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ parse::<EmptyParams>(params)?;
+ finish(layout_migration::scan(&load().await?, &layout_migration::AppHost).await)
+ })
+}
+
+pub(super) fn migration_start(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let params = parse::<layout_migration::StartParams>(params)?;
+ let config = load().await?;
+ let started = layout_migration::start(
+ config.clone(),
+ std::sync::Arc::new(layout_migration::AppHost),
+ layout_migration::Trigger::Manual {
+ takeover: params.takeover,
+ },
+ std::sync::Arc::new(import::scheduler_paused),
+ );
+ tracing::debug!(started, "[memory:layout_migration] start requested");
+ finish(layout_migration::status(&config))
+ })
+}
+
+pub(super) fn migration_status(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ parse::<EmptyParams>(params)?;
+ finish(layout_migration::status(&load().await?))
+ })
+}
+
+pub(super) fn migration_retry(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ parse::<EmptyParams>(params)?;
+ finish(layout_migration::retry(&load().await?))
+ })
+}
diff --git a/crates/openhuman-core/src/memory/schemas_tests.rs b/crates/openhuman-core/src/memory/schemas_tests.rs
index 137c704796..fd87e8fa57 100644
--- a/crates/openhuman-core/src/memory/schemas_tests.rs
+++ b/crates/openhuman-core/src/memory/schemas_tests.rs
@@ -6,7 +6,7 @@ use crate::memory::test_fixtures::{bind_reference, config_in};
use serde_json::{json, Map, Value};
/// Every method of the spec's RPC table (`docs/specs/memory-v2.md`), exactly.
-const SPEC_METHODS: [&str; 30] = [
+const SPEC_METHODS: [&str; 34] = [
"openhuman.memory_engines_list",
"openhuman.memory_engine_get",
"openhuman.memory_engine_set",
@@ -37,6 +37,10 @@ const SPEC_METHODS: [&str; 30] = [
"openhuman.memory_import_start",
"openhuman.memory_import_status",
"openhuman.memory_import_retry_failed",
+ "openhuman.memory_migration_scan",
+ "openhuman.memory_migration_start",
+ "openhuman.memory_migration_status",
+ "openhuman.memory_migration_retry",
];
fn object(value: Value) -> Map<String, Value> {
@@ -103,6 +107,7 @@ fn required_inputs_match_the_spec() {
assert_eq!(optional("sources_remove"), ["forget_items"]);
assert_eq!(optional("sources_sync"), ["id"]);
assert_eq!(required("import_start"), ["consent"]);
+ assert_eq!(optional("migration_start"), ["takeover"]);
assert_eq!(optional("pack_preview"), ["query", "thread_id", "agent_id"]);
assert_eq!(required("brain_search"), ["query"]);
assert_eq!(