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
feat(memory): add layout migration for brain storage
Steven Enamakelc23097328639
diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rsindex 55b82cf0c6..f05d80a8ca 100644--- a/crates/openhuman-core/src/memory/brain.rs+++ b/crates/openhuman-core/src/memory/brain.rs@@ -48,7 +48,12 @@ pub fn brain_node(source: &BrainSource,item: &StoreItem,) -> MemoryResult<Namespace> {- brain_node_with(config.memory.split_github_by_repo, layout, source, item)+ Ok(brain_node_with(+ config.memory.split_github_by_repo,+ layout,+ source,+ item,+ )?)}/// The layout the brain RPCs act on: the in-scope identity's.diff --git a/crates/openhuman-core/src/memory/brain_tests.rs b/crates/openhuman-core/src/memory/brain_tests.rsindex 41f90d970b..fc948c54fb 100644--- a/crates/openhuman-core/src/memory/brain_tests.rs+++ b/crates/openhuman-core/src/memory/brain_tests.rs@@ -1,5 +1,7 @@use super::*;+use tinymemory_tools::layout::placement::file_into;+use tinymemory_api::{ItemKind, MemoryMeta, MetaFilter};use crate::memory::test_fixtures::{bind_reference, config_in, stored};diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rsindex f8a6706aa9..06107ad20c 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs@@ -1,35 +1,89 @@//! 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`.+//! `memory::scope`, the free period from `memory::billing`, and the legacy+//! claim and import state the module asks for through its ports.use async_trait::async_trait;+use tinymemory_api::Error as EngineError;+use tinymemory_tools::layout_migration as lm;+use tinymemory_tools::layout_migration::{Engines, FlowPlacement, LegacyClaim, Placement};use super::claim::ClaimKey;-use super::copy::Engines;-use super::job::LayoutHost;-use super::map::{FlowPlacement, Placement};+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::scope::{self, MemoryIdentity};-/// The app's [`LayoutHost`].-pub struct AppHost;+/// The app's [`lm::LayoutHost`], bound to one account's config.+pub struct AppHost {+ config: Config,+ store: FileStateStore,+}++impl AppHost {+ /// The host that migrates `config`'s account.+ #[must_use]+ pub fn new(config: Config) -> Self {+ let store = FileStateStore::new(&config.workspace_dir);+ Self { config, store }+ }+}++/// How long a recheck lets the engine's listing catch up before copying again.+#[cfg(not(test))]+const RECHECK_DELAY: std::time::Duration = std::time::Duration::from_secs(45);+#[cfg(test)]+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 {+ 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(),+ // The backend's `[CODE] ` prefix stays on the message, which is how+ // the module tells an exhausted balance.+ MemoryError::InsufficientCredits(message) | MemoryError::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 {+ 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),+ }+}#[async_trait]-impl LayoutHost for AppHost {- fn engines(&self, config: &Config) -> MemoryResult<Engines> {- let root = signed_in_root(config)?;- Ok(Engines {- legacy: engine::bind_with_root(config, None)?.engine,- tree: engine::bind_with_root(config, Some(&root))?.engine,- })+impl lm::LayoutHost for AppHost {+ fn store(&self) -> &dyn lm::MigrationStateStore {+ &self.store+ }++ fn engines(&self) -> lm::Result<Engines> {+ let config = &self.config;+ let bind = || -> MemoryResult<Engines> {+ let root = signed_in_root(config)?;+ Ok(Engines {+ legacy: engine::bind_with_root(config, None)?.engine,+ tree: engine::bind_with_root(config, Some(&root))?.engine,+ })+ };+ bind().map_err(to_module)}- fn placement(&self, config: &Config) -> MemoryResult<Placement> {+ fn placement(&self) -> lm::Result<Placement> {// The v3 layout, whatever the setting says: the copy runs before the// switch.- let mut v3 = config.clone();+ let mut v3 = self.config.clone();v3.memory.layout = MemoryLayoutMode::V3;let layout = MemoryIdentity::root().resolve(&v3).layout;let chat_node = scope::chat_node(&layout);@@ -37,43 +91,59 @@ impl LayoutHost for AppHost {layout,chat_node,flows: FlowPlacement::WithRoot,- split_github_by_repo: config.memory.split_github_by_repo,+ split_github_by_repo: self.config.memory.split_github_by_repo,})}- fn is_switched(&self, config: &Config) -> bool {- scope::layout_is_v3(config)+ fn is_switched(&self) -> bool {+ scope::layout_is_v3(&self.config)}- async fn switch(&self, config: &Config) -> MemoryResult<()> {+ async fn switch(&self) -> lm::Result<()> {// This person's own config file, loaded fresh: never the active// account's (someone else's after an account switch mid-move).- scope::switch_to_v3(config).await+ scope::switch_to_v3(&self.config).await.map_err(to_module)}- async fn free_now(&self, config: &Config) -> bool {- crate::memory::billing::free_period_active(config).await+ async fn free_now(&self) -> bool {+ crate::memory::billing::free_period_active(&self.config).await}- fn legacy_claim(&self, config: &Config) -> MemoryResult<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 {- return Ok(None);- }- // The account, by its actor (`user:<id>`): a claim made before- // `org:` roots named the same string, so it stays this account's.- let owner = scope::actor_of_root(&signed_in_root(config)?);- // `<app>/users/<id>/config.toml`: the app directory every account shares.- let app_dir = config- .config_path- .parent()- .and_then(std::path::Path::parent)- .and_then(std::path::Path::parent)- .ok_or_else(signed_out)?;- let endpoint = engine::bind_with_root(config, None)?.endpoint;- Ok(Some(ClaimKey::new(app_dir, &endpoint, &owner)))+ fn legacy_claim(&self) -> lm::Result<Option<Box<dyn LegacyClaim>>> {+ claim_key(&self.config)+ .map(|key| key.map(|key| Box::new(key) as Box<dyn LegacyClaim>))+ .map_err(to_module)+ }++ fn listed_unconfirmed(&self) -> bool {+ crate::memory::import::listed_unconfirmed(&self.config.workspace_dir)+ }++ async fn wait_for_listing(&self) {+ tokio::time::sleep(RECHECK_DELAY).await;+ }+}++/// 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>> {+ // 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 {+ return Ok(None);}+ // The account, by its actor (`user:<id>`): a claim made before+ // `org:` roots named the same string, so it stays this account's.+ let owner = scope::actor_of_root(&signed_in_root(config)?);+ // `<app>/users/<id>/config.toml`: the app directory every account shares.+ let app_dir = config+ .config_path+ .parent()+ .and_then(std::path::Path::parent)+ .and_then(std::path::Path::parent)+ .ok_or_else(signed_out)?;+ let endpoint = engine::bind_with_root(config, None)?.endpoint;+ Ok(Some(ClaimKey::new(app_dir, &endpoint, &owner)))}fn signed_in_root(config: &Config) -> MemoryResult<String> {diff --git a/crates/openhuman-core/src/memory/layout_migration/claim.rs b/crates/openhuman-core/src/memory/layout_migration/claim.rsindex d2b2f48747..7987629c6d 100644--- a/crates/openhuman-core/src/memory/layout_migration/claim.rs+++ b/crates/openhuman-core/src/memory/layout_migration/claim.rs@@ -13,6 +13,9 @@ use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use sha2::Digest;+use tinymemory_tools::layout_migration::{LegacyClaim, Result as ModuleResult};++use super::app_host::to_module;use crate::memory::error::{MemoryError, MemoryResult};/// Where a legacy tree's marker lives and who would own it.@@ -124,6 +127,16 @@ pub fn take(key: &ClaimKey) -> MemoryResult<bool> {}}+impl LegacyClaim for ClaimKey {+ fn held_by_other(&self) -> ModuleResult<bool> {+ held_by_other(self).map_err(to_module)+ }++ fn take(&self) -> ModuleResult<bool> {+ take(self).map_err(to_module)+ }+}+fn unreadable(error: &dyn std::fmt::Display) -> MemoryError {MemoryError::Engine(format!("legacy tree claim unreadable: {error}"))}diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rsindex d39d8a0b1b..005596e337 100644--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs@@ -1,23 +1,20 @@//! Moving memory from the legacy CortexDB tree into the per-user tree.//!-//! Memory written before layout v3 lives under `app:tinymemory/…`; layout v3-//! keeps each person's memory below `org:<id>`. Items are moved by being-//! stored again ([`copy`]) rather than by copying events, because an item's-//! namespace is part of its identity and its placement changes-//! ([`map`]). Progress is saved after every page ([`state`]), so the move-//! resumes where it stopped and repeats at most one page.+//! The engine-to-engine migration (copy, placement, cleanup, the job and its+//! service) lives in `tinymemory_tools::layout_migration`; this module is the+//! OpenHuman host adapter over its two ports://!-//! This module holds the parts that need no engine binding: detecting legacy-//! memory, placing items, and the copy-and-verify pass over a given pair of-//! engines. Binding the two engines, the switch to the per-user tree, the-//! catch-up pass, cleanup and the RPCs build on it.+//! - [`state`]: the file-backed [`MigrationStateStore`] under the workspace.+//! - [`app_host`]: the [`LayoutHost`] for one account (engine binding,+//! 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`].+//!+//! [`MemoryError`]: crate::memory::error::MemoryErrorpub mod app_host;pub mod claim;-pub mod cleanup;-pub mod copy;-pub mod job;-pub mod map;pub mod service;pub mod state;@@ -25,9 +22,9 @@ pub mod state;mod test_host;pub use app_host::AppHost;-pub use cleanup::cleanup;-pub use copy::{copy, legacy_present, Engines};-pub use job::{run, LayoutHost, Outcome, Trigger};-pub use map::{FlowPlacement, Placement};-pub use service::{retry, scan, start, status, tick, MigrationStatus, ScanView, StartParams};-pub use state::{MigrationState, Phase};+pub use service::{retry, scan, start, status, tick, StartParams};+pub use state::FileStateStore;+pub use tinymemory_tools::layout_migration::{+ LayoutHost, MigrationState, MigrationStateStore, MigrationStatus, Outcome, Phase, ScanView,+ Trigger,+};diff --git a/crates/openhuman-core/src/memory/layout_migration/state.rs b/crates/openhuman-core/src/memory/layout_migration/state.rsindex 06a0c8b779..a534a5b2ee 100644--- a/crates/openhuman-core/src/memory/layout_migration/state.rs+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs@@ -2,95 +2,52 @@//!//! Written whole after every page, through a temporary file and a rename,//! so a crash leaves the previous state or the new one, never a torn file.+//! The state itself is `tinymemory_tools::layout_migration::MigrationState`.use std::path::{Path, PathBuf};-use serde::{Deserialize, Serialize};+use tinymemory_tools::layout_migration::{Error, Result};+use super::{MigrationState, MigrationStateStore};use crate::memory::error::{MemoryError, MemoryResult};-/// Where the migration is.-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum Phase {- /// Not started.- #[default]- Idle,- /// Copying the legacy tree, page by page.- Copying,- /// Stopped where it was: paused by the scheduler, out of credits, or the- /// engine unreachable. Resumes from the cursor.- Paused,- /// Every item it could copy is copied and verified.- Copied,- /// Removing the legacy copies of what was moved.- Cleaning,- /// The legacy tree holds nothing that was moved; what is left there (if- /// anything) is in `failures` or `incomplete`.- Cleaned,+/// The state file of `workspace_dir`.+#[must_use]+pub fn path(workspace_dir: &Path) -> PathBuf {+ workspace_dir.join("memory").join("layout_migration.json")}-/// An item that could not be copied.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct Failure {- /// Its id in the legacy tree.- pub id: String,- /// Why (an error code, never content).- pub reason: String,+/// The migration state kept in one workspace.+#[derive(Debug, Clone)]+pub struct FileStateStore {+ workspace_dir: PathBuf,}-/// The migration's progress.-#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]-pub struct MigrationState {- /// Where it is.- pub phase: Phase,- /// The legacy export cursor of the next page; `None` before the first.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub cursor: Option<String>,- /// Items copied and confirmed readable in the per-user tree.- pub copied: u64,- /// Of those, items the per-user tree already held (a resumed page).- pub replayed: u64,- /// Items that could not be copied.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub failures: Vec<Failure>,- /// Items the legacy tree holds only part of (a chunked document missing- /// a piece).- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub incomplete: Vec<String>,- /// Why it is paused.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub error: Option<String>,- /// Cleanup has started, so a pause resumes it, not the copy.- #[serde(default)]- pub cleaning: bool,- /// Reads and writes moved to the per-user tree.- #[serde(default)]- pub switched: bool,- /// The catch-up copy after the switch is done.- #[serde(default)]- pub caught_up: bool,- /// The user agreed to take a legacy tree other accounts may share.- #[serde(default)]- pub takeover: bool,- /// Extra catch-up passes made because the import ended with its last- /// batch not confirmed listed (see `job::run`).- #[serde(default, skip_serializing_if = "is_zero")]- pub rechecks: u32,- /// Those passes are over (one moved nothing new, or the most were made).- /// The import's flag stays set, so cleanup keeps forgetting by id.- #[serde(default, skip_serializing_if = "std::ops::Not::not")]- pub rechecked: bool,+impl FileStateStore {+ /// The store of `workspace_dir`.+ #[must_use]+ pub fn new(workspace_dir: &Path) -> Self {+ Self {+ workspace_dir: workspace_dir.to_path_buf(),+ }+ }}-fn is_zero(n: &u32) -> bool {- *n == 0+impl MigrationStateStore for FileStateStore {+ fn load(&self) -> Result<MigrationState> {+ load(&self.workspace_dir).map_err(|error| Error::State(detail(error)))+ }++ fn save(&self, state: &MigrationState) -> Result<()> {+ save(&self.workspace_dir, state).map_err(|error| Error::State(detail(error)))+ }}-/// The state file of `workspace_dir`.-#[must_use]-pub fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("layout_migration.json")+fn detail(error: MemoryError) -> String {+ match error {+ MemoryError::Engine(message) => message,+ other => other.to_string(),+ }}/// The saved state, or a fresh one when none was saved.diff --git a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs b/crates/openhuman-core/src/memory/layout_migration/state_tests.rsnew file mode 100644index 0000000000..cfe5cfeccc--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs@@ -0,0 +1,58 @@+use tinymemory_tools::layout_migration::{Failure, Phase};++use super::*;++#[test]+fn a_missing_file_is_a_fresh_state() {+ let tmp = tempfile::tempdir().unwrap();+ assert_eq!(load(tmp.path()).unwrap(), MigrationState::default());+}++#[test]+fn a_saved_state_loads_back_and_leaves_no_temporary_file() {+ let tmp = tempfile::tempdir().unwrap();+ let state = MigrationState {+ phase: Phase::Paused,+ cursor: Some("l00ff".into()),+ copied: 7,+ replayed: 2,+ failures: vec![Failure {+ id: "abc".into(),+ reason: "invalid_request".into(),+ }],+ incomplete: vec!["def".into()],+ error: Some("background work is paused".into()),+ cleaning: true,+ switched: true,+ caught_up: false,+ takeover: true,+ rechecks: 1,+ rechecked: true,+ };+ save(tmp.path(), &state).unwrap();+ assert_eq!(load(tmp.path()).unwrap(), state);+ assert!(!path(tmp.path()).with_extension("json.tmp").exists());+}++#[test]+fn a_damaged_file_is_an_error_not_a_fresh_start() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(tmp.path().join("memory")).unwrap();+ std::fs::write(path(tmp.path()), b"{ not json").unwrap();+ assert!(load(tmp.path()).is_err());+ // Through the port the host hands the module, too.+ assert!(FileStateStore::new(tmp.path()).load().is_err());+}++#[test]+fn the_port_saves_where_the_status_reads() {+ let tmp = tempfile::tempdir().unwrap();+ let store = FileStateStore::new(tmp.path());+ let state = MigrationState {+ phase: Phase::Copying,+ copied: 3,+ ..MigrationState::default()+ };+ store.save(&state).unwrap();+ assert_eq!(load(tmp.path()).unwrap(), state);+}