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): run the layout migration end to end behind a host seam
M3gA-Mindc4817925102b
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup.rsindex 16bf90655b..6f72462594 100644--- a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup.rs@@ -17,8 +17,8 @@ use std::collections::BTreeMap;use std::path::Path;use tinymemory_api::{- EraseRequest, ForgetTarget, GetRequest, ItemId, ItemKind, ListRequest, MemoryEngine,- MetaFilter, Namespace, Reach, MAX_GET_IDS,+ EraseRequest, ForgetTarget, GetRequest, ItemId, ItemKind, ListRequest, MetaFilter, Namespace,+ Reach, MAX_GET_IDS,};use super::copy::Engines;@@ -104,13 +104,16 @@ async fn survey(engines: &Engines, placement: &Placement) -> MemoryResult<Survey////// When the state cannot be saved, or the legacy tree cannot be read or/// changed for a reason that is not account-wide.-pub async fn cleanup(+pub async fn cleanup<P>(workspace_dir: &Path,engines: &Engines,placement: &Placement,state: &mut MigrationState,- paused: impl Fn() -> bool,-) -> MemoryResult<()> {+ paused: impl Fn() -> P,+) -> MemoryResult<()>+where+ P: std::future::Future<Output = bool>,+{state.phase = Phase::Cleaning;state.cleaning = true;state.error = None;@@ -142,15 +145,18 @@ pub async fn cleanup(}/// One removal pass; `false` when it stopped for a pause.-async fn remove_moved(+async fn remove_moved<P>(engines: &Engines,placement: &Placement,- paused: &impl Fn() -> bool,-) -> MemoryResult<bool> {+ paused: &impl Fn() -> P,+) -> MemoryResult<bool>+where+ P: std::future::Future<Output = bool>,+{let found = survey(engines, placement).await?;let mut can_erase = !found.partial;for ((_, kind), (namespace, group)) in found.groups {- if paused() {+ if paused().await {return Ok(false);}if group.moved.is_empty() {diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rsindex 08a8390466..da56a1b8ae 100644--- a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs@@ -3,8 +3,8 @@ use std::sync::Arc;use tinymemory_api::conformance::ReferenceEngine;use tinymemory_api::{async_trait, EngineDescriptor, EngineHealth, ExportPage, FetchPage, FetchRequest, ForgetReport,- Hit, LearningKind, ListPage, MemoryMeta, RecallAnswer, RecallRequest, Result, StoreItem,- StoreReceipt,+ Hit, LearningKind, ListPage, MemoryEngine, MemoryMeta, RecallAnswer, RecallRequest, Result,+ StoreItem, StoreReceipt,};use tinymemory_tools::MemoryLayout;@@ -58,7 +58,7 @@ async fn texts(engine: &dyn MemoryEngine) -> Vec<String> {async fn copied(tmp: &Path, engines: &Engines) -> MigrationState {let mut state = MigrationState::default();- copy(tmp, engines, &placement(), &mut state, || false)+ copy(tmp, engines, &placement(), &mut state, || async { false }).await.unwrap();state@@ -108,9 +108,11 @@ async fn everything_moved_is_erased_from_the_legacy_tree() {tree: tree.clone(),};let mut state = copied(tmp.path(), &engines).await;- cleanup(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ cleanup(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Cleaned);assert!(texts(legacy.as_ref()).await.is_empty());assert_eq!(texts(tree.as_ref()).await.len(), 10, "the moved items stay");@@ -137,9 +139,11 @@ async fn an_item_without_its_twin_is_never_removed() {.unwrap();tree.forget(ForgetTarget::Ids(vec![lost.id])).await.unwrap();- cleanup(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ cleanup(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Cleaned);assert_eq!(texts(legacy.as_ref()).await, vec!["fact 3".to_string()]);}@@ -164,9 +168,11 @@ async fn an_engine_that_cannot_erase_forgets_by_id() {tree: Arc::new(ReferenceEngine::new()),};let mut state = copied(tmp.path(), &engines).await;- cleanup(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ cleanup(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Cleaned);assert!(texts(legacy.as_ref()).await.is_empty());}@@ -179,9 +185,11 @@ async fn a_paused_cleanup_says_it_was_cleaning() {tree: Arc::new(ReferenceEngine::new()),};let mut state = copied(tmp.path(), &engines).await;- cleanup(tmp.path(), &engines, &placement(), &mut state, || true)- .await- .unwrap();+ cleanup(tmp.path(), &engines, &placement(), &mut state, || async {+ true+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Paused);assert!(state.cleaning, "a resume goes back to cleanup");assert_eq!(texts(engines.legacy.as_ref()).await.len(), 4);diff --git a/crates/openhuman-core/src/memory/layout_migration/copy.rs b/crates/openhuman-core/src/memory/layout_migration/copy.rsindex 21f49a7dec..eb2b9ad3e3 100644--- a/crates/openhuman-core/src/memory/layout_migration/copy.rs+++ b/crates/openhuman-core/src/memory/layout_migration/copy.rs@@ -50,18 +50,21 @@ pub async fn legacy_present(legacy: &dyn MemoryEngine) -> MemoryResult<bool> {////// When the state cannot be saved, or the legacy tree cannot be read for a/// reason that is not account-wide.-pub async fn copy(+pub async fn copy<P>(workspace_dir: &Path,engines: &Engines,placement: &Placement,state: &mut MigrationState,- paused: impl Fn() -> bool,-) -> MemoryResult<()> {+ paused: impl Fn() -> P,+) -> MemoryResult<()>+where+ P: std::future::Future<Output = bool>,+{state.phase = Phase::Copying;state.error = None;state::save(workspace_dir, state)?;loop {- if paused() {+ if paused().await {return pause(workspace_dir,state,diff --git a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rsindex 0caec739f6..f0d34920e2 100644--- a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs@@ -78,9 +78,11 @@ async fn every_item_is_copied_placed_and_read_back() {tree: tree.clone(),};let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Copied);assert_eq!(state.copied, 121);assert!(state.failures.is_empty(), "{:?}", state.failures);@@ -116,7 +118,8 @@ async fn a_paused_copy_resumes_where_it_stopped_without_duplicates() {let pages = AtomicUsize::new(0);let mut state = MigrationState::default();copy(tmp.path(), &engines, &placement(), &mut state, || {- pages.fetch_add(1, Ordering::SeqCst) >= 1+ let stop = pages.fetch_add(1, Ordering::SeqCst) >= 1;+ async move { stop }}).await.unwrap();@@ -126,9 +129,11 @@ async fn a_paused_copy_resumes_where_it_stopped_without_duplicates() {// A crash here: resume from what was saved, not from memory.let mut resumed = state::load(tmp.path()).unwrap();- copy(tmp.path(), &engines, &placement(), &mut resumed, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut resumed, || async {+ false+ })+ .await+ .unwrap();assert_eq!(resumed.phase, Phase::Copied);assert_eq!(resumed.copied, 121);assert_eq!(count(tree.as_ref()).await, 121, "no item stored twice");@@ -144,13 +149,17 @@ async fn a_repeated_page_is_a_replay() {tree: tree.clone(),};let mut first = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut first, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut first, || async {+ false+ })+ .await+ .unwrap();let mut again = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut again, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut again, || async {+ false+ })+ .await+ .unwrap();assert_eq!(again.copied, 4);assert_eq!(again.replayed, 4);assert_eq!(count(tree.as_ref()).await, 4);@@ -164,9 +173,11 @@ async fn an_account_that_cannot_write_pauses_without_advancing() {tree: Arc::new(RefusingEngine::out_of_credits()),};let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Paused);assert_eq!(state.cursor, None, "the page is sent again on resume");assert_eq!(state.copied, 0);@@ -187,9 +198,11 @@ async fn a_legacy_tree_that_cannot_be_read_pauses() {tree: Arc::new(ReferenceEngine::new()),};let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Paused);}@@ -234,9 +247,11 @@ async fn old_brain_nodes_are_refiled_by_connector() {tree: tree.clone(),};let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || false)- .await- .unwrap();+ copy(tmp.path(), &engines, &placement(), &mut state, || async {+ false+ })+ .await+ .unwrap();assert_eq!(state.phase, Phase::Copied);let mut placed: Vec<(String, String)> = tree.list(ListRequest::new(MetaFilter::default(), 50))diff --git a/crates/openhuman-core/src/memory/layout_migration/host.rs b/crates/openhuman-core/src/memory/layout_migration/host.rsnew file mode 100644index 0000000000..9ad13f651e--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/host.rs@@ -0,0 +1,50 @@+//! What the migration needs from the host, behind one trait so the job is+//! tested without a TinyHumans session or a CortexDB server.+//!+//! The real host (the engine binding and the layout setting) implements it+//! over `memory::engine` and `memory::scope`; tests implement it over two+//! in-memory engines.++use async_trait::async_trait;++use super::copy::Engines;+use super::map::Placement;+use crate::config::Config;+use crate::memory::error::MemoryResult;++/// The host side of a layout migration.+#[async_trait]+pub trait LayoutHost: Send + Sync {+ /// The legacy-layout engine and the per-user engine for `config`'s+ /// account, on one endpoint and credential.+ ///+ /// # Errors+ ///+ /// When memory is off or the account has no per-user root.+ fn engines(&self, config: &Config) -> MemoryResult<Engines>;++ /// Where items go in the per-user tree.+ ///+ /// # Errors+ ///+ /// When the layout cannot be built.+ fn placement(&self, config: &Config) -> MemoryResult<Placement>;++ /// Whether reads and writes already use the per-user tree.+ fn is_switched(&self, config: &Config) -> bool;++ /// Moves reads and writes to the per-user tree.+ ///+ /// # Errors+ ///+ /// When the setting cannot be saved.+ fn switch(&self, config: &Config) -> MemoryResult<()>;++ /// Whether moving memory costs the user nothing right now (always, off+ /// the hosted engine).+ async fn free_now(&self, config: &Config) -> bool;++ /// Whether the legacy tree may be shared with other accounts on this+ /// machine (a self-hosted key), so taking it needs the user's consent.+ fn shared_legacy(&self, config: &Config) -> bool;+}diff --git a/crates/openhuman-core/src/memory/layout_migration/job.rs b/crates/openhuman-core/src/memory/layout_migration/job.rsnew file mode 100644index 0000000000..cf619f6313--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/job.rs@@ -0,0 +1,144 @@+//! A migration end to end: detect, copy, switch, catch up, clean up.+//!+//! - **Detect.** No legacy memory: switch at once, and that is all; there is+//! no job, no banner and no prompt.+//! - **Gates.** A legacy tree other accounts may share (a self-hosted key)+//! moves only with the user's consent ([`Trigger::Manual`] with+//! `takeover`). An automatic run starts, and goes on page by page, only+//! while moving costs the user nothing; when that ends mid-run it pauses+//! where it is, and resumes in a later free window or when the user starts+//! it.+//! - **Copy, then switch.** Reads and writes move to the per-user tree only+//! after every item that could be copied is verified there, so no turn+//! ever reads an empty memory.+//! - **Catch up.** Writes to the legacy tree between the copy and the switch+//! are picked up by copying once more; everything copied before replays.+//! - **Clean up.** Last, because it drops held recall packs.+//!+//! Every step saves its progress, so [`run`] called again (after a pause, a+//! crash or a restart) continues where the last one stopped.++use super::cleanup::cleanup;+use super::copy::{copy, legacy_present};+use super::host::LayoutHost;+use super::state::{self, MigrationState, Phase};+use crate::config::Config;+use crate::memory::error::MemoryResult;++/// What started a run.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Trigger {+ /// The background job: runs only while moving is free.+ Auto,+ /// The user's "Migrate now"; `takeover` is their consent to take a+ /// legacy tree other accounts may share.+ Manual {+ /// Consent to take a shared legacy tree.+ takeover: bool,+ },+}++/// How a run ended.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Outcome {+ /// There was no legacy memory; the per-user tree is in use.+ NothingToMove,+ /// Not started: the legacy tree may be shared, and the user has not+ /// agreed to take it.+ NeedsTakeover,+ /// Not started or not continued automatically: moving is not free now.+ NotFree,+ /// Stopped where it was; [`run`] again continues.+ Paused,+ /// Moved and cleaned up.+ Done,+}++/// Runs (or resumes) the migration of `config`'s account. `paused` is the+/// scheduler's own pause (background work held), asked before every page.+///+/// # Errors+///+/// When the state cannot be read or saved, the engines cannot be bound, or+/// the legacy tree cannot be read for a reason that is not account-wide.+pub async fn run<P>(+ config: &Config,+ host: &dyn LayoutHost,+ trigger: Trigger,+ paused: impl Fn() -> P,+) -> MemoryResult<Outcome>+where+ P: std::future::Future<Output = bool>,+{+ let dir = config.workspace_dir.as_path();+ let mut state = state::load(dir)?;+ if state.phase == Phase::Cleaned {+ return Ok(Outcome::Done);+ }+ let engines = host.engines(config)?;+ if state.phase == Phase::Idle && !state.switched && !legacy_present(&*engines.legacy).await? {+ return nothing_to_move(config, host, &mut state);+ }+ if let Trigger::Manual { takeover: true } = trigger {+ state.takeover = true;+ state::save(dir, &state)?;+ }+ if host.shared_legacy(config) && !state.takeover {+ return Ok(Outcome::NeedsTakeover);+ }+ let auto = trigger == Trigger::Auto;+ if auto && !host.free_now(config).await {+ return Ok(Outcome::NotFree);+ }+ let paused = &paused;+ let stop = move || async move { paused().await || (auto && !host.free_now(config).await) };+ let placement = host.placement(config)?;++ if !state.switched && !state.cleaning {+ copy(dir, &engines, &placement, &mut state, stop).await?;+ if state.phase != Phase::Copied {+ return Ok(Outcome::Paused);+ }+ if !host.is_switched(config) {+ host.switch(config)?;+ }+ state.switched = true;+ state.cursor = None;+ state::save(dir, &state)?;+ tracing::info!("[memory:layout_migration] switched to the per-user tree");+ }+ if !state.caught_up && !state.cleaning {+ copy(dir, &engines, &placement, &mut state, stop).await?;+ if state.phase != Phase::Copied {+ return Ok(Outcome::Paused);+ }+ state.caught_up = true;+ state::save(dir, &state)?;+ }+ cleanup(dir, &engines, &placement, &mut state, stop).await?;+ Ok(if state.phase == Phase::Cleaned {+ Outcome::Done+ } else {+ Outcome::Paused+ })+}++fn nothing_to_move(+ config: &Config,+ host: &dyn LayoutHost,+ state: &mut MigrationState,+) -> MemoryResult<Outcome> {+ if !host.is_switched(config) {+ host.switch(config)?;+ }+ state.switched = true;+ state.caught_up = true;+ state.phase = Phase::Cleaned;+ state::save(&config.workspace_dir, state)?;+ tracing::info!("[memory:layout_migration] no legacy memory; per-user tree in use");+ Ok(Outcome::NothingToMove)+}++#[cfg(test)]+#[path = "job_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs b/crates/openhuman-core/src/memory/layout_migration/job_tests.rsnew file mode 100644index 0000000000..8e30b57a26--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/job_tests.rs@@ -0,0 +1,220 @@+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};++use tinymemory_api::conformance::ReferenceEngine;+use tinymemory_api::{+ LearningKind, ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Namespace, StoreItem,+};+use tinymemory_tools::MemoryLayout;++use super::*;+use crate::memory::error::MemoryError;+use crate::memory::layout_migration::copy::Engines;+use crate::memory::layout_migration::map::{FlowPlacement, Placement};++/// Two in-memory engines and the switches a real host keeps.+struct FakeHost {+ legacy: Arc<ReferenceEngine>,+ tree: Arc<ReferenceEngine>,+ switched: AtomicBool,+ free: AtomicBool,+ shared: bool,+ /// Asks for free_now: after this many, moving stops being free.+ free_for: AtomicUsize,+ /// Written to the legacy tree as the switch happens (a turn racing it).+ racing_write: Mutex<Option<StoreItem>>,+}++impl FakeHost {+ async fn with(learnings: usize) -> Self {+ let legacy = Arc::new(ReferenceEngine::new());+ for i in 0..learnings {+ legacy.store(fact(&format!("fact {i}"))).await.unwrap();+ }+ Self {+ legacy,+ tree: Arc::new(ReferenceEngine::new()),+ switched: AtomicBool::new(false),+ free: AtomicBool::new(true),+ shared: false,+ free_for: AtomicUsize::new(usize::MAX),+ racing_write: Mutex::new(None),+ }+ }+}++fn fact(text: &str) -> StoreItem {+ StoreItem::learning(text, LearningKind::Fact, 0.5, MemoryMeta::default())+}++async fn count(engine: &dyn MemoryEngine) -> usize {+ let mut total = 0;+ let mut cursor = None;+ loop {+ let mut request = ListRequest::new(MetaFilter::default(), 100);+ request.cursor = cursor;+ let page = engine.list(request).await.unwrap();+ total += page.items.len();+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => return total,+ }+ }+}++#[async_trait::async_trait]+impl LayoutHost for FakeHost {+ fn engines(&self, _: &Config) -> MemoryResult<Engines> {+ Ok(Engines {+ legacy: self.legacy.clone(),+ tree: self.tree.clone(),+ })+ }++ fn placement(&self, _: &Config) -> MemoryResult<Placement> {+ Ok(Placement {+ layout: MemoryLayout::new(Namespace::ROOT)+ .map_err(|e| MemoryError::invalid(e.to_string()))?,+ chat_node: "ws:main".parse().unwrap(),+ flows: FlowPlacement::WithRoot,+ })+ }++ fn is_switched(&self, _: &Config) -> bool {+ self.switched.load(Ordering::SeqCst)+ }++ fn switch(&self, _: &Config) -> MemoryResult<()> {+ if let Some(item) = self.racing_write.lock().unwrap().take() {+ // Synchronous on purpose: the reference engine stores in memory.+ futures::executor::block_on(self.legacy.store(item)).unwrap();+ }+ self.switched.store(true, Ordering::SeqCst);+ Ok(())+ }++ async fn free_now(&self, _: &Config) -> bool {+ let left = self.free_for.fetch_sub(1, Ordering::SeqCst);+ self.free.load(Ordering::SeqCst) && left > 0+ }++ fn shared_legacy(&self, _: &Config) -> bool {+ self.shared+ }+}++async fn go(config: &Config, host: &FakeHost, trigger: Trigger) -> Outcome {+ run(config, host, trigger, || async { false })+ .await+ .unwrap()+}++#[tokio::test]+async fn no_legacy_memory_switches_at_once_and_nothing_else() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(0).await;+ assert_eq!(+ go(&config, &host, Trigger::Auto).await,+ Outcome::NothingToMove+ );+ assert!(host.is_switched(&config));+ assert_eq!(+ go(&config, &host, Trigger::Auto).await,+ Outcome::Done,+ "settled"+ );+}++#[tokio::test]+async fn an_automatic_run_waits_while_moving_is_not_free() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(3).await;+ host.free.store(false, Ordering::SeqCst);+ assert_eq!(go(&config, &host, Trigger::Auto).await, Outcome::NotFree);+ assert!(!host.is_switched(&config));+ assert_eq!(count(host.tree.as_ref()).await, 0);+ assert_eq!(+ go(&config, &host, Trigger::Manual { takeover: false }).await,+ Outcome::Done,+ "the user's own start does not wait for a free period"+ );+}++#[tokio::test]+async fn a_shared_legacy_tree_moves_only_with_consent() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let mut host = FakeHost::with(3).await;+ host.shared = true;+ assert_eq!(+ go(&config, &host, Trigger::Auto).await,+ Outcome::NeedsTakeover+ );+ assert_eq!(+ go(&config, &host, Trigger::Manual { takeover: false }).await,+ Outcome::NeedsTakeover+ );+ assert_eq!(+ go(&config, &host, Trigger::Manual { takeover: true }).await,+ Outcome::Done+ );+ assert_eq!(+ go(&config, &host, Trigger::Auto).await,+ Outcome::Done,+ "consent is kept"+ );+}++#[tokio::test]+async fn a_free_run_moves_switches_and_cleans_up() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(120).await;+ assert_eq!(go(&config, &host, Trigger::Auto).await, Outcome::Done);+ assert!(host.is_switched(&config));+ assert_eq!(count(host.tree.as_ref()).await, 120);+ assert_eq!(count(host.legacy.as_ref()).await, 0);+}++#[tokio::test]+async fn a_free_period_ending_mid_run_pauses_before_the_switch_and_resumes() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(120).await;+ // Free at the start and for the first page, then not.+ host.free_for.store(2, Ordering::SeqCst);+ assert_eq!(go(&config, &host, Trigger::Auto).await, Outcome::Paused);+ assert!(+ !host.is_switched(&config),+ "reads stay on the full legacy tree"+ );+ assert!(count(host.tree.as_ref()).await < 120);++ host.free_for.store(usize::MAX, Ordering::SeqCst);+ assert_eq!(go(&config, &host, Trigger::Auto).await, Outcome::Done);+ assert_eq!(count(host.tree.as_ref()).await, 120, "no item twice");+ assert_eq!(count(host.legacy.as_ref()).await, 0);+}++#[tokio::test]+async fn a_write_racing_the_switch_is_caught_up() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(5).await;+ *host.racing_write.lock().unwrap() = Some(fact("written as the switch happened"));+ assert_eq!(go(&config, &host, Trigger::Auto).await, Outcome::Done);+ let texts: Vec<String> = host+ .tree+ .list(ListRequest::new(MetaFilter::default(), 50))+ .await+ .unwrap()+ .items+ .into_iter()+ .map(|hit| hit.text)+ .collect();+ assert_eq!(texts.len(), 6);+ assert!(texts.iter().any(|t| t == "written as the switch happened"));+ assert_eq!(count(host.legacy.as_ref()).await, 0);+}diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rsindex da2aef5f34..9b610400a6 100644--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs@@ -14,10 +14,14 @@pub mod cleanup;pub mod copy;+pub mod host;+pub mod job;pub mod map;pub mod state;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 state::{MigrationState, Phase};diff --git a/crates/openhuman-core/src/memory/layout_migration/state.rs b/crates/openhuman-core/src/memory/layout_migration/state.rsindex b6dba03aca..012707ae7d 100644--- a/crates/openhuman-core/src/memory/layout_migration/state.rs+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs@@ -64,6 +64,15 @@ pub struct MigrationState {/// 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,}/// The state file of `workspace_dir`.diff --git a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs b/crates/openhuman-core/src/memory/layout_migration/state_tests.rsindex f4b39bd34e..c8bbe49231 100644--- a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs@@ -21,6 +21,9 @@ fn a_saved_state_loads_back_and_leaves_no_temporary_file() {incomplete: vec!["def".into()],error: Some("background work is paused".into()),cleaning: true,+ switched: true,+ caught_up: false,+ takeover: true,};save(tmp.path(), &state).unwrap();assert_eq!(load(tmp.path()).unwrap(), state);