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 memory storage
Steven Enamakelc7620a7ff1e6
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup.rsdeleted file mode 100644index e610a77712..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs+++ /dev/null@@ -1,205 +0,0 @@-//! Cleanup: removing the legacy copies of what was moved.-//!-//! Nothing is removed on the strength of the state file: the legacy tree is-//! exported again, each item placed again, and its twin in the per-user tree-//! read back by id. Only items whose twin is there are removed.-//!-//! - **A legacy scope whose every item has its twin**, with no partial item-//! anywhere, is erased whole ([`MemoryEngine::erase`]), which releases the-//! write keys.-//! - **Otherwise**, on an engine that cannot erase (the hosted one), and on-//! a legacy tree other accounts share (whose writes can land between the-//! survey and an erase), the items with a twin are forgotten by id; the-//! rest stay where they are.-//!-//! The pass ends by exporting the legacy tree once more: [`Phase::Cleaned`]-//! is written only if nothing left there has a twin.--use std::collections::BTreeMap;-use std::path::Path;--use tinymemory_api::{- EraseRequest, ForgetTarget, GetRequest, ItemId, ItemKind, ListRequest, MetaFilter, Namespace,- Reach, MAX_GET_IDS,-};--use super::copy::Engines;-use super::map::Placement;-use super::state::{self, MigrationState, Phase};-use crate::memory::error::{MemoryError, MemoryResult};--/// The legacy items of one kind at one node: their ids, and whether every-/// one of them has its twin.-#[derive(Default)]-struct Group {- moved: Vec<ItemId>,- complete: bool,-}--/// What a pass over the legacy tree found.-#[derive(Default)]-struct Survey {- groups: BTreeMap<(String, ItemKind), (Namespace, Group)>,- partial: bool,-}--/// Exports the whole legacy tree and finds, for every item, whether its twin-/// is in the per-user tree.-async fn survey(engines: &Engines, placement: &Placement) -> MemoryResult<Survey> {- let mut found = Survey::default();- let mut cursor = None;- loop {- let mut request = ListRequest::new(MetaFilter::default(), MAX_GET_IDS);- request.cursor = cursor;- let page = engines.legacy.export(request).await?;- found.partial |= !page.incomplete.is_empty();- let mut twins = Vec::with_capacity(page.items.len());- for exported in &page.items {- let twin = placement- .place(exported.item.clone())- .map(|item| ItemId(item.fingerprint()))- .ok();- twins.push(twin);- }- let ids: Vec<ItemId> = twins.iter().flatten().cloned().collect();- let present = if ids.is_empty() {- Vec::new()- } else {- engines- .tree- .get(GetRequest { ids, reach: None })- .await?- .into_iter()- .map(|hit| hit.id)- .collect()- };- for (exported, twin) in page.items.into_iter().zip(twins) {- let namespace = exported.item.meta().namespace.clone();- let key = (namespace.to_string(), exported.item.kind());- let (_, group) = found.groups.entry(key).or_insert_with(|| {- (- namespace,- Group {- complete: true,- ..Group::default()- },- )- });- if twin.is_some_and(|twin| present.contains(&twin)) {- group.moved.push(exported.id);- } else {- group.complete = false;- }- }- match page.next_cursor {- Some(next) => cursor = Some(next),- None => return Ok(found),- }- }-}--/// Removes the legacy copies of everything moved, then checks nothing moved-/// is left. Pauses (resumably) when `paused` says so or the account cannot-/// go on.-///-/// # Errors-///-/// 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<P>(- workspace_dir: &Path,- engines: &Engines,- placement: &Placement,- shared: bool,- state: &mut MigrationState,- paused: impl Fn() -> P,-) -> MemoryResult<()>-where- P: std::future::Future<Output = bool>,-{- state.phase = Phase::Cleaning;- state.cleaning = true;- state.error = None;- state::save(workspace_dir, state)?;- // An import that finished without its last batch confirmed listed may- // hold items the survey cannot see yet: never erase a scope whole then,- // forget by verified id as for a shared tree.- let unconfirmed = crate::memory::import::listed_unconfirmed(workspace_dir);- if unconfirmed {- tracing::info!("[memory:layout_migration] import not confirmed listed; forgetting by id");- }- match remove_moved(engines, placement, shared || unconfirmed, &paused).await {- Ok(true) => {}- Ok(false) => return pause(workspace_dir, state, "background work is paused".into()),- Err(error) if error.is_account_wide() => {- return pause(workspace_dir, state, error.to_string())- }- Err(error) => return Err(error),- }- let left = survey(engines, placement).await?;- let still_moved: usize = left.groups.values().map(|(_, g)| g.moved.len()).sum();- if still_moved > 0 {- return pause(- workspace_dir,- state,- format!("{still_moved} moved items are still in the legacy tree"),- );- }- state.phase = Phase::Cleaned;- state::save(workspace_dir, state)?;- tracing::info!(- left = left.groups.len(),- "[memory:layout_migration] legacy tree cleaned"- );- Ok(())-}--/// One removal pass; `false` when it stopped for a pause.-async fn remove_moved<P>(- engines: &Engines,- placement: &Placement,- shared: 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 && !shared;- for ((_, kind), (namespace, group)) in found.groups {- if paused().await {- return Ok(false);- }- if group.moved.is_empty() {- continue;- }- if can_erase && group.complete {- let mut erase = EraseRequest::new(Reach::exact(namespace.clone()));- erase.kinds = vec![kind];- match engines.legacy.erase(erase).await {- Ok(_) => continue,- Err(tinymemory_api::Error::Unsupported(_)) => can_erase = false,- Err(error) => return Err(error.into()),- }- }- for batch in group.moved.chunks(100) {- engines- .legacy- .forget(ForgetTarget::Ids(batch.to_vec()))- .await- .map_err(MemoryError::from)?;- }- }- Ok(true)-}--fn pause(workspace_dir: &Path, state: &mut MigrationState, why: String) -> MemoryResult<()> {- tracing::info!(%why, "[memory:layout_migration] cleanup paused");- state.phase = Phase::Paused;- state.error = Some(why);- state::save(workspace_dir, state)-}--#[cfg(test)]-#[path = "cleanup_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rsdeleted file mode 100644index 38f38b2d92..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs+++ /dev/null@@ -1,332 +0,0 @@-use std::sync::Arc;--use tinymemory_api::conformance::ReferenceEngine;-use tinymemory_api::{- async_trait, EngineDescriptor, EngineHealth, EraseReport, ExportPage, FetchPage, FetchRequest,- ForgetReport, Hit, LearningKind, ListPage, MemoryEngine, MemoryMeta, RecallAnswer,- RecallRequest, Result, StoreItem, StoreReceipt,-};-use tinymemory_tools::MemoryLayout;--use super::*;-use crate::memory::layout_migration::copy::copy;-use crate::memory::layout_migration::map::FlowPlacement;--fn placement() -> Placement {- Placement {- layout: MemoryLayout::new(Namespace::ROOT).unwrap(),- chat_node: "ws:main".parse().unwrap(),- flows: FlowPlacement::WithRoot,- split_github_by_repo: false,- }-}--async fn seeded(n: usize) -> Arc<ReferenceEngine> {- let legacy = Arc::new(ReferenceEngine::new());- for i in 0..n {- legacy- .store(StoreItem::learning(- format!("fact {i}"),- LearningKind::Fact,- 0.5,- MemoryMeta {- namespace: if i % 2 == 0 {- Namespace::ROOT- } else {- "agent:a".parse().unwrap()- },- ..MemoryMeta::default()- },- ))- .await- .unwrap();- }- legacy-}--async fn texts(engine: &dyn MemoryEngine) -> Vec<String> {- let mut texts: Vec<String> = engine- .list(ListRequest::new(MetaFilter::default(), 100))- .await- .unwrap()- .items- .into_iter()- .map(|hit| hit.text)- .collect();- texts.sort();- texts-}--async fn copied(tmp: &Path, engines: &Engines) -> MigrationState {- let mut state = MigrationState::default();- copy(tmp, engines, &placement(), &mut state, || async { false })- .await- .unwrap();- state-}--/// A reference engine that cannot erase, as the hosted one cannot.-struct NoErase(ReferenceEngine);--/// A reference engine whose erase must never be called.-struct NeverErase(ReferenceEngine);--#[async_trait]-impl MemoryEngine for NeverErase {- fn descriptor(&self) -> &EngineDescriptor {- self.0.descriptor()- }- async fn health(&self) -> EngineHealth {- self.0.health().await- }- async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {- self.0.recall(req).await- }- async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {- self.0.fetch(req).await- }- async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {- self.0.store(item).await- }- async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {- self.0.forget(target).await- }- async fn list(&self, req: ListRequest) -> Result<ListPage> {- self.0.list(req).await- }- async fn export(&self, req: ListRequest) -> Result<ExportPage> {- self.0.export(req).await- }- async fn get(&self, req: GetRequest) -> Result<Vec<Hit>> {- self.0.get(req).await- }- async fn erase(&self, _: EraseRequest) -> Result<EraseReport> {- panic!("a shared legacy tree is never erased scope-wide");- }-}--#[async_trait]-impl MemoryEngine for NoErase {- fn descriptor(&self) -> &EngineDescriptor {- self.0.descriptor()- }- async fn health(&self) -> EngineHealth {- self.0.health().await- }- async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {- self.0.recall(req).await- }- async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {- self.0.fetch(req).await- }- async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {- self.0.store(item).await- }- async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {- self.0.forget(target).await- }- async fn list(&self, req: ListRequest) -> Result<ListPage> {- self.0.list(req).await- }- async fn export(&self, req: ListRequest) -> Result<ExportPage> {- self.0.export(req).await- }- async fn get(&self, req: GetRequest) -> Result<Vec<Hit>> {- self.0.get(req).await- }-}--#[tokio::test]-async fn everything_moved_is_erased_from_the_legacy_tree() {- let tmp = tempfile::tempdir().unwrap();- let legacy = seeded(10).await;- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy: legacy.clone(),- tree: tree.clone(),- };- let mut state = copied(tmp.path(), &engines).await;- cleanup(- tmp.path(),- &engines,- &placement(),- false,- &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");-}--#[tokio::test]-async fn an_item_without_its_twin_is_never_removed() {- let tmp = tempfile::tempdir().unwrap();- let legacy = seeded(10).await;- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy: legacy.clone(),- tree: tree.clone(),- };- let mut state = copied(tmp.path(), &engines).await;- // The per-user copy of "fact 3" is lost after the copy.- let lost = tree- .list(ListRequest::new(MetaFilter::default(), 100))- .await- .unwrap()- .items- .into_iter()- .find(|hit| hit.text == "fact 3")- .unwrap();- tree.forget(ForgetTarget::Ids(vec![lost.id])).await.unwrap();-- cleanup(- tmp.path(),- &engines,- &placement(),- false,- &mut state,- || async { false },- )- .await- .unwrap();- assert_eq!(state.phase, Phase::Cleaned);- assert_eq!(texts(legacy.as_ref()).await, vec!["fact 3".to_string()]);-}--#[tokio::test]-async fn an_engine_that_cannot_erase_forgets_by_id() {- let tmp = tempfile::tempdir().unwrap();- let legacy = Arc::new(NoErase(ReferenceEngine::new()));- for i in 0..5 {- legacy- .store(StoreItem::learning(- format!("fact {i}"),- LearningKind::Fact,- 0.5,- MemoryMeta::default(),- ))- .await- .unwrap();- }- let engines = Engines {- legacy: legacy.clone(),- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = copied(tmp.path(), &engines).await;- cleanup(- tmp.path(),- &engines,- &placement(),- false,- &mut state,- || async { false },- )- .await- .unwrap();- assert_eq!(state.phase, Phase::Cleaned);- assert!(texts(legacy.as_ref()).await.is_empty());-}--#[tokio::test]-async fn a_paused_cleanup_says_it_was_cleaning() {- let tmp = tempfile::tempdir().unwrap();- let engines = Engines {- legacy: seeded(4).await,- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = copied(tmp.path(), &engines).await;- cleanup(- tmp.path(),- &engines,- &placement(),- false,- &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);-}--#[tokio::test]-async fn a_shared_legacy_tree_is_forgotten_by_id_never_erased() {- let tmp = tempfile::tempdir().unwrap();- let legacy = Arc::new(NeverErase(ReferenceEngine::new()));- for i in 0..5 {- legacy- .store(StoreItem::learning(- format!("fact {i}"),- LearningKind::Fact,- 0.5,- MemoryMeta::default(),- ))- .await- .unwrap();- }- let engines = Engines {- legacy: legacy.clone(),- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = copied(tmp.path(), &engines).await;- cleanup(- tmp.path(),- &engines,- &placement(),- true,- &mut state,- || async { false },- )- .await- .unwrap();- assert_eq!(state.phase, Phase::Cleaned);- assert!(texts(legacy.as_ref()).await.is_empty());-}--/// An import that finished without its last batch confirmed listed may hold-/// items no export shows yet: cleanup must not erase a scope whole then, and-/// forgets only the moved items by id (an erase would panic here).-#[tokio::test]-async fn after_an_unconfirmed_import_moved_items_are_forgotten_by_id_never_erased() {- let tmp = tempfile::tempdir().unwrap();- std::fs::create_dir_all(tmp.path().join("memory")).unwrap();- std::fs::write(- tmp.path().join("memory").join("import_state.json"),- r#"{"listed_unconfirmed": true}"#,- )- .unwrap();- assert!(crate::memory::import::listed_unconfirmed(tmp.path()));- let legacy = Arc::new(NeverErase(ReferenceEngine::new()));- for i in 0..5 {- legacy- .store(StoreItem::learning(- format!("fact {i}"),- LearningKind::Fact,- 0.5,- MemoryMeta::default(),- ))- .await- .unwrap();- }- let engines = Engines {- legacy: legacy.clone(),- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = copied(tmp.path(), &engines).await;- cleanup(- tmp.path(),- &engines,- &placement(),- false,- &mut state,- || async { false },- )- .await- .unwrap();- assert_eq!(state.phase, Phase::Cleaned);- assert!(texts(legacy.as_ref()).await.is_empty());-}diff --git a/crates/openhuman-core/src/memory/layout_migration/copy.rs b/crates/openhuman-core/src/memory/layout_migration/copy.rsdeleted file mode 100644index ffab5888c6..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/copy.rs+++ /dev/null@@ -1,193 +0,0 @@-//! The copy pass: the legacy tree into the per-user tree, page by page.-//!-//! Each page is exported whole from the legacy engine-//! ([`tinymemory_api::MemoryEngine::export`]), placed ([`Placement`]),-//! stored in the per-user engine, and read back by id before the state-//! moves past it. A page is never marked copied before its items are-//! readable where they now live, and a crash or a pause repeats at most one-//! page: storing an item the tree already holds is a replay.--use std::path::Path;-use std::sync::Arc;--use tinymemory_api::{GetRequest, ItemId, ListRequest, MemoryEngine, MetaFilter, StoreItem};--use super::map::Placement;-use super::state::{self, Failure, MigrationState, Phase};-use crate::memory::error::{MemoryError, MemoryResult};-use crate::memory::import::skips_item;--/// Items one page exports and stores.-pub const PAGE: usize = 50;--/// The two engines a migration works between, on one endpoint and-/// credential: the legacy tree it reads, and the per-user tree it writes.-pub struct Engines {- /// The legacy layout (`app:tinymemory/…`).- pub legacy: Arc<dyn MemoryEngine>,- /// The per-user layout.- pub tree: Arc<dyn MemoryEngine>,-}--/// Whether the legacy tree holds anything to move: one export of one item.-///-/// # Errors-///-/// The legacy engine's failures, including a tree too large to list whole.-pub async fn legacy_present(legacy: &dyn MemoryEngine) -> MemoryResult<bool> {- let page = legacy- .export(ListRequest::new(MetaFilter::default(), 1))- .await?;- Ok(!page.items.is_empty() || !page.incomplete.is_empty())-}--/// Copies from `state.cursor` to the end of the legacy tree, saving the-/// state after every page. Returns with [`Phase::Copied`] at the end, or-/// [`Phase::Paused`] when `paused` says so or the account cannot go on-/// (credits, credential, engine unreachable).-///-/// # Errors-///-/// 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<P>(- workspace_dir: &Path,- engines: &Engines,- placement: &Placement,- state: &mut MigrationState,- paused: impl Fn() -> P,-) -> MemoryResult<()>-where- P: std::future::Future<Output = bool>,-{- state.phase = Phase::Copying;- state.error = None;- if state.cursor.is_none() {- // A pass from the top (the first, or the catch-up after the switch)- // meets every item again: count it afresh.- state.copied = 0;- state.replayed = 0;- state.failures.clear();- state.incomplete.clear();- }- state::save(workspace_dir, state)?;- loop {- if paused().await {- return pause(- workspace_dir,- state,- "background work is paused".to_string(),- );- }- let mut request = ListRequest::new(MetaFilter::default(), PAGE);- request.cursor = state.cursor.clone();- let page = match engines.legacy.export(request).await {- Ok(page) => page,- Err(error) => {- let error = MemoryError::from(error);- if error.is_account_wide() {- return pause(workspace_dir, state, error.to_string());- }- return Err(error);- }- };- for id in page.incomplete {- if !state.incomplete.contains(&id.0) {- state.incomplete.push(id.0);- }- }- let mut placed = Vec::with_capacity(page.items.len());- for exported in page.items {- match placement.place(exported.item) {- Ok(item) => placed.push((exported.id.0, item)),- Err(error) => note_failure(state, exported.id.0, error.code()),- }- }- if let Err(error) = store_and_check(engines.tree.as_ref(), placed, state).await {- return pause(workspace_dir, state, error.to_string());- }- state.cursor = page.next_cursor;- if state.cursor.is_none() {- state.phase = Phase::Copied;- state::save(workspace_dir, state)?;- tracing::info!(- copied = state.copied,- failures = state.failures.len(),- incomplete = state.incomplete.len(),- "[memory:layout_migration] legacy tree copied"- );- return Ok(());- }- state::save(workspace_dir, state)?;- }-}--/// Records `id` as not copied, once: a page sent again after a pause meets-/// the same items.-fn note_failure(state: &mut MigrationState, id: String, reason: &str) {- if !state.failures.iter().any(|failure| failure.id == id) {- state.failures.push(Failure {- id,- reason: reason.to_string(),- });- }-}--fn pause(workspace_dir: &Path, state: &mut MigrationState, why: String) -> MemoryResult<()> {- tracing::info!(%why, copied = state.copied, "[memory:layout_migration] paused");- state.phase = Phase::Paused;- state.error = Some(why);- state::save(workspace_dir, state)-}--/// Stores `placed` in the per-user tree and reads every item back by id.-/// An item the engine refuses on its own is recorded as a failure; an-/// account-wide failure stops the page (the caller pauses, and the page is-/// sent again on resume).-async fn store_and_check(- tree: &dyn MemoryEngine,- placed: Vec<(String, StoreItem)>,- state: &mut MigrationState,-) -> Result<(), MemoryError> {- if placed.is_empty() {- return Ok(());- }- let items: Vec<StoreItem> = placed.iter().map(|(_, item)| item.clone()).collect();- let mut stored: Vec<(String, ItemId, bool)> = Vec::new();- match tree.store_many(items).await {- Ok(receipts) => stored.extend(- placed- .iter()- .zip(receipts)- .map(|((legacy, _), receipt)| (legacy.clone(), receipt.id, receipt.replayed)),- ),- Err(error) if !skips_item(&error) => return Err(error.into()),- Err(_) => {- for (legacy, item) in placed {- match tree.store(item).await {- Ok(receipt) => stored.push((legacy, receipt.id, receipt.replayed)),- Err(error) if !skips_item(&error) => return Err(error.into()),- Err(error) => note_failure(state, legacy, MemoryError::from(error).code()),- }- }- }- }- let ids: Vec<ItemId> = stored.iter().map(|(_, id, _)| id.clone()).collect();- let found = tree- .get(GetRequest { ids, reach: None })- .await- .map_err(MemoryError::from)?;- for (legacy, id, replayed) in stored {- if found.iter().any(|hit| hit.id == id) {- state.copied += 1;- state.replayed += u64::from(replayed);- } else {- note_failure(state, legacy, "not_readable_after_store");- }- }- Ok(())-}--#[cfg(test)]-#[path = "copy_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rsdeleted file mode 100644index 66e879fcc1..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs+++ /dev/null@@ -1,298 +0,0 @@-use std::sync::atomic::{AtomicUsize, Ordering};--use tinymemory_api::conformance::ReferenceEngine;-use tinymemory_api::{LearningKind, MemoryMeta, Namespace, SourceKind, SourceRef};-use tinymemory_tools::MemoryLayout;--use super::*;-use crate::memory::layout_migration::map::FlowPlacement;-use crate::memory::test_fixtures::RefusingEngine;--fn placement() -> Placement {- Placement {- layout: MemoryLayout::new(Namespace::ROOT).unwrap(),- chat_node: "ws:main".parse().unwrap(),- flows: FlowPlacement::WithRoot,- split_github_by_repo: false,- }-}--/// A legacy tree of `learnings` root learnings and one PDF in `source:pdf`.-async fn legacy_tree(learnings: usize) -> Arc<ReferenceEngine> {- let legacy = Arc::new(ReferenceEngine::new());- for n in 0..learnings {- legacy- .store(StoreItem::learning(- format!("fact {n}"),- LearningKind::Fact,- 0.5,- MemoryMeta::default(),- ))- .await- .unwrap();- }- legacy- .store(StoreItem::document(- "handbook",- MemoryMeta {- namespace: "source:pdf".parse().unwrap(),- source: SourceRef {- kind: SourceKind::File,- id: None,- },- ..MemoryMeta::default()- },- ))- .await- .unwrap();- legacy-}--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,- }- }-}--#[tokio::test]-async fn an_empty_legacy_tree_has_nothing_to_move() {- assert!(!legacy_present(&ReferenceEngine::new()).await.unwrap());- assert!(legacy_present(legacy_tree(0).await.as_ref()).await.unwrap());-}--#[tokio::test]-async fn every_item_is_copied_placed_and_read_back() {- let tmp = tempfile::tempdir().unwrap();- let legacy = legacy_tree(120).await;- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy: legacy.clone(),- tree: tree.clone(),- };- let mut state = MigrationState::default();- 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);- assert_eq!(count(tree.as_ref()).await, 121);- assert_eq!(- count(legacy.as_ref()).await,- 121,- "the copy deletes nothing"- );- let files = tree- .list(ListRequest::new(- MetaFilter {- kinds: vec![tinymemory_api::ItemKind::Document],- ..MetaFilter::default()- },- 10,- ))- .await- .unwrap();- assert_eq!(files.items[0].meta.namespace.to_string(), "source:files");- assert_eq!(state::load(tmp.path()).unwrap(), state, "saved as it ended");-}--#[tokio::test]-async fn a_paused_copy_resumes_where_it_stopped_without_duplicates() {- let tmp = tempfile::tempdir().unwrap();- let legacy = legacy_tree(120).await;- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy,- tree: tree.clone(),- };- let pages = AtomicUsize::new(0);- let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || {- let stop = pages.fetch_add(1, Ordering::SeqCst) >= 1;- async move { stop }- })- .await- .unwrap();- assert_eq!(state.phase, Phase::Paused);- assert_eq!(state.copied, PAGE as u64, "one page before the pause");- assert!(state.cursor.is_some());-- // 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, || 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");-}--#[tokio::test]-async fn a_repeated_page_is_a_replay() {- let tmp = tempfile::tempdir().unwrap();- let legacy = legacy_tree(3).await;- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy,- tree: tree.clone(),- };- let mut first = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut first, || async {- false- })- .await- .unwrap();- let mut again = MigrationState::default();- 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);-}--#[tokio::test]-async fn the_catch_up_pass_counts_each_item_once() {- let tmp = tempfile::tempdir().unwrap();- let engines = Engines {- legacy: legacy_tree(3).await,- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = MigrationState::default();- for _ in 0..2 {- // The first pass, then the catch-up pass on the same state.- copy(tmp.path(), &engines, &placement(), &mut state, || async {- false- })- .await- .unwrap();- }- assert_eq!(state.copied, 4, "not 8");- assert_eq!(state.replayed, 4, "the second pass replays every item");-}--#[tokio::test]-async fn an_account_that_cannot_write_pauses_without_advancing() {- let tmp = tempfile::tempdir().unwrap();- let engines = Engines {- legacy: legacy_tree(3).await,- tree: Arc::new(RefusingEngine::out_of_credits()),- };- let mut state = MigrationState::default();- 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);- assert!(state- .error- .as_deref()- .unwrap_or_default()- .contains("credits"));-}--#[tokio::test]-async fn a_legacy_tree_that_cannot_be_read_pauses() {- let tmp = tempfile::tempdir().unwrap();- let engines = Engines {- legacy: Arc::new(RefusingEngine::with(tinymemory_api::Error::Unavailable(- "down".into(),- ))),- tree: Arc::new(ReferenceEngine::new()),- };- let mut state = MigrationState::default();- copy(tmp.path(), &engines, &placement(), &mut state, || async {- false- })- .await- .unwrap();- assert_eq!(state.phase, Phase::Paused);-}--#[tokio::test]-async fn old_brain_nodes_are_refiled_by_connector() {- let tmp = tempfile::tempdir().unwrap();- let legacy = Arc::new(ReferenceEngine::new());- let doc = |text: &str, node: &str, kind: SourceKind, path: Option<&str>| {- StoreItem::document(- text,- MemoryMeta {- namespace: node.parse().unwrap(),- source: SourceRef { kind, id: None },- file_path: path.map(str::to_string),- ..MemoryMeta::default()- },- )- };- for item in [- doc("a pdf", "source:pdf", SourceKind::File, Some("a.pdf")),- doc("a note", "source:markdown", SourceKind::File, Some("a.md")),- doc("a link", "source:web", SourceKind::Link, None),- doc(- "an upload",- "source:web",- SourceKind::Link,- Some("page.html"),- ),- doc(- "a drive doc",- "source:google_drive",- SourceKind::Import,- None,- ),- doc("a notion page", "source:notion", SourceKind::Import, None),- ] {- legacy.store(item).await.unwrap();- }- let tree = Arc::new(ReferenceEngine::new());- let engines = Engines {- legacy,- tree: tree.clone(),- };- let mut state = MigrationState::default();- 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))- .await- .unwrap()- .items- .into_iter()- .map(|hit| (hit.text, hit.meta.namespace.to_string()))- .collect();- placed.sort();- let expect = |text: &str, node: &str| (text.to_string(), node.to_string());- assert_eq!(- placed,- vec![- expect("a drive doc", "source:googledrive"),- expect("a link", "source:web"),- expect("a note", "source:files"),- expect("a notion page", "source:notion"),- expect("a pdf", "source:files"),- expect("an upload", "source:files"),- ]- );-}diff --git a/crates/openhuman-core/src/memory/layout_migration/job.rs b/crates/openhuman-core/src/memory/layout_migration/job.rsdeleted file mode 100644index 2ec1943ad4..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/job.rs+++ /dev/null@@ -1,291 +0,0 @@-//! 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 async_trait::async_trait;--use super::claim::{self, ClaimKey};-use super::cleanup::cleanup;-use super::copy::{copy, legacy_present, Engines};-use super::map::Placement;-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: another account on this machine took the shared legacy- /// tree.- ClaimedElsewhere,- /// 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,-}--/// 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.-#[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: persists the layout- /// setting and drops the cached engines. The real host loads the migrated- /// person's own config file fresh, so a setting changed during a long- /// migration is never reverted and an account switch mid-move never- /// writes another person's config.- ///- /// # Errors- ///- /// When the setting cannot be saved.- async 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;-- /// The claim on the legacy tree when other accounts on this machine may- /// share it (a self-hosted engine), so taking it needs the user's- /// consent and only one account may; `None` when it is the account's own.- ///- /// # Errors- ///- /// When memory is off or the account has no per-user root.- fn legacy_claim(&self, config: &Config) -> MemoryResult<Option<ClaimKey>>;-}--/// The most extra catch-up passes after an import that ended with its last-/// batch not confirmed listed.-const MAX_RECHECKS: u32 = 3;--/// How long a recheck lets the 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);--/// 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)?;- // Cleaned with the import still unconfirmed (a stop between cleanup and- // the re-check below) goes round once more rather than counting as done.- if state.phase == Phase::Cleaned- && (state.rechecked || !crate::memory::import::listed_unconfirmed(dir))- {- 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).await;- }- if let Trigger::Manual { takeover: true } = trigger {- state.takeover = true;- state::save(dir, &state)?;- }- let shared = host.legacy_claim(config)?;- if let Some(key) = &shared {- if claim::held_by_other(key)? {- return claimed_elsewhere(config, host, &mut state).await;- }- if !state.takeover {- return Ok(Outcome::NeedsTakeover);- }- if !claim::take(key)? {- return claimed_elsewhere(config, host, &mut state).await;- }- }- 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).await?;- }- 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,- shared.is_some(),- &mut state,- stop,- )- .await?;- // An import that ended with its last batch not confirmed listed may hold- // items no copy saw yet: in this same run, wait for the listing to catch- // up, then copy, verify and clean up again; at least once, then while a- // pass still moves something new, at most MAX_RECHECKS times. A late item- // is never erased meanwhile (`cleanup`). Each recheck is saved before its- // wait, so a stop or a restart resumes it.- while state.phase == Phase::Cleaned- && !state.rechecked- && crate::memory::import::listed_unconfirmed(dir)- {- let new = state.copied > state.replayed;- if !((state.rechecks == 0 || new) && state.rechecks < MAX_RECHECKS) {- // Done re-checking. The import's flag stays: nothing here proves- // its last batch is listed, so cleanup keeps forgetting by id.- state.rechecked = true;- state::save(dir, &state)?;- break;- }- state.rechecks += 1;- state.caught_up = false;- state.cleaning = false;- state.cursor = None;- // Parked as paused, not copied: a scan must not offer a fresh move.- state.phase = Phase::Paused;- state.error = Some("copying again for items the import may list late".to_string());- state::save(dir, &state)?;- tracing::info!(- rechecks = state.rechecks,- "[memory:layout_migration] import not confirmed listed; copying again"- );- tokio::time::sleep(RECHECK_DELAY).await;- 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,- shared.is_some(),- &mut state,- stop,- )- .await?;- }- Ok(if state.phase == Phase::Cleaned {- Outcome::Done- } else {- Outcome::Paused- })-}--/// Another account took the shared legacy tree: this one has nothing to-/// move, and goes on in its own per-user tree like an account that never had-/// legacy memory, rather than in the tree the other account emptied.-async fn claimed_elsewhere(- config: &Config,- host: &dyn LayoutHost,- state: &mut MigrationState,-) -> MemoryResult<Outcome> {- nothing_to_move(config, host, state).await?;- Ok(Outcome::ClaimedElsewhere)-}--async fn nothing_to_move(- config: &Config,- host: &dyn LayoutHost,- state: &mut MigrationState,-) -> MemoryResult<Outcome> {- if !host.is_switched(config) {- host.switch(config).await?;- }- 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.rsdeleted file mode 100644index b387c21c2d..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs+++ /dev/null@@ -1,216 +0,0 @@-use std::sync::atomic::Ordering;--use tinymemory_api::{ListRequest, MemoryEngine, MetaFilter};--use super::*;-use crate::memory::layout_migration::claim::ClaimKey;-use crate::memory::layout_migration::test_host::{count, fact, FakeHost};--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.claim = Some(ClaimKey::new(tmp.path(), "http://127.0.0.1:3141", "user:a"));- 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);-}--#[tokio::test]-async fn a_tree_another_account_took_is_left_alone() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let theirs = ClaimKey::new(tmp.path(), "http://127.0.0.1:3141", "user:b");- assert!(claim::take(&theirs).unwrap());- let mut host = FakeHost::with(3).await;- host.claim = Some(ClaimKey::new(- tmp.path(),- "http://127.0.0.1:3141/",- "user:a",- ));- assert_eq!(- go(&config, &host, Trigger::Manual { takeover: true }).await,- Outcome::ClaimedElsewhere- );- assert_eq!(count(&*host.legacy).await, 3, "nothing moved");- assert_eq!(count(&*host.tree).await, 0);- assert!(- host.switched.load(Ordering::SeqCst),- "this account goes on in its own tree, not the one another took"- );- assert!(- !crate::memory::layout_migration::scan(&config, &host)- .await- .unwrap()- .needed- );-}--/// After an import that ended with its last batch not confirmed listed, an-/// item the listing shows only after the first pass is still moved, in the-/// same run: it copies again after a short wait instead of finishing, and-/// finishes (clearing the flag) once a pass moves nothing new.-#[tokio::test]-async fn after_an_unconfirmed_import_an_item_listed_late_is_still_moved() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let memory_dir = config.workspace_dir.join("memory");- std::fs::create_dir_all(&memory_dir).unwrap();- std::fs::write(- memory_dir.join("import_state.json"),- r#"{"listed_unconfirmed": true}"#,- )- .unwrap();- assert!(crate::memory::import::listed_unconfirmed(- &config.workspace_dir- ));- let host = FakeHost::with(3).await;-- // The item is accepted by the import but listed only once the first- // pass is over: stored while the run waits before its first recheck.- let late = async {- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);- while state::load(&config.workspace_dir).unwrap().rechecks == 0 {- if std::time::Instant::now() > deadline {- return false;- }- tokio::time::sleep(std::time::Duration::from_millis(2)).await;- }- host.legacy.store(fact("listed late")).await.unwrap();- true- };- let (outcome, stored_late) = tokio::join!(- go(&config, &host, Trigger::Manual { takeover: false }),- late- );-- assert!(stored_late, "the run waited to copy again");- assert_eq!(outcome, Outcome::Done);- assert_eq!(- count(host.tree.as_ref()).await,- 4,- "the late item was moved"- );- assert_eq!(count(host.legacy.as_ref()).await, 0);- let state = state::load(&config.workspace_dir).unwrap();- assert_eq!(- state.rechecks, 2,- "one forced recheck that moved the late item, one that moved nothing"- );- assert!(state.rechecked, "re-checking is over");- assert!(- crate::memory::import::listed_unconfirmed(&config.workspace_dir),- "the flag stays: later cleanups keep forgetting by id"- );- assert_eq!(- go(&config, &host, Trigger::Auto).await,- Outcome::Done,- "settled, not re-checked again"- );-}diff --git a/crates/openhuman-core/src/memory/layout_migration/map.rs b/crates/openhuman-core/src/memory/layout_migration/map.rsdeleted file mode 100644index b1446f7d38..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/map.rs+++ /dev/null@@ -1,104 +0,0 @@-//! Where an item from the legacy tree goes in the per-user tree.-//!-//! The rule: an item goes where today's write path would put it now, so a-//! later sync of the same item replays instead of storing a duplicate.-//!-//! - **Brain documents** at `source:<id>` go to W4's connector node:-//! [`legacy_brain_node`], then [`brain_node_with`] and [`file_into`]: the-//! same placement new syncs use (`pdf`, `markdown` and the other-//! per-format nodes become `files`; GitHub splits by repository when the-//! setting is on).-//! - **Conversations** are pooled at the chat node; the agent id stays in-//! the item's metadata.-//! - **Workflow items** (keyed memory and run digests, tagged `flow:<id>`)-//! stay with the root's learnings and documents for now, as they are read-//! today. [`FlowPlacement::InNode`] is the one switch that moves them into-//! each flow's own node, once flow memory is read from there.-//! - Everything else keeps its namespace; only the wire root changes.--use tinymemory_api::{ItemKind, Namespace, SegmentKind, StoreItem};-use tinymemory_tools::MemoryLayout;--use crate::memory::brain::{brain_node_with, file_into, legacy_brain_node};-use crate::memory::error::MemoryResult;--/// The tag every workflow item carries (`crate::flows::FLOWS_TAG`). Kept here-/// rather than imported: legacy items carry it whatever features this build-/// has, so placing them must not depend on the `flows` feature.-const FLOWS_TAG: &str = "flows";--/// Where workflow items go.-#[derive(Clone, Copy)]-pub enum FlowPlacement {- /// With the root's learnings and documents, as today.- WithRoot,- /// In each flow's own node: the flow id to its node.- InNode(fn(&str) -> MemoryResult<Namespace>),-}--/// Where items go in the per-user tree.-pub struct Placement {- /// The layout new items are written with.- pub layout: MemoryLayout,- /// Where conversations are pooled.- pub chat_node: Namespace,- /// Where workflow items go.- pub flows: FlowPlacement,- /// `[memory] split_github_by_repo`: GitHub documents go one collection- /// per repository, as a sync files them now.- pub split_github_by_repo: bool,-}--/// The flow a workflow item belongs to: its `flow:<id>` tag, when it also-/// carries the `flows` tag (keyed memory and run digests both do).-fn flow_of(item: &StoreItem) -> Option<&str> {- let tags = &item.meta().tags;- if !tags.iter().any(|tag| tag == FLOWS_TAG) {- return None;- }- tags.iter()- .filter_map(|tag| tag.strip_prefix("flow:"))- .find(|id| !id.contains(':'))-}--/// The id of the `source:` segment directly below `root`, if `namespace` is-/// a brain node of the legacy layout.-fn legacy_source<'a>(root: &Namespace, namespace: &'a Namespace) -> Option<&'a str> {- let (root, segments) = (root.segments(), namespace.segments());- let below = segments.get(root.len())?;- (segments.starts_with(root) && below.kind() == SegmentKind::Source).then(|| below.id())-}--impl Placement {- /// `item` as it is stored in the per-user tree.- ///- /// # Errors- ///- /// When a node cannot be built (an id the namespace grammar refuses).- pub fn place(&self, mut item: StoreItem) -> MemoryResult<StoreItem> {- if let Some(flow) = flow_of(&item) {- if let FlowPlacement::InNode(node) = self.flows {- item.meta_mut().namespace = node(flow)?;- }- return Ok(item);- }- if item.kind() == ItemKind::Conversation {- item.meta_mut().namespace = self.chat_node.clone();- return Ok(item);- }- if item.kind() == ItemKind::Document {- let namespace = item.meta().namespace.clone();- if let Some(id) = legacy_source(self.layout.root(), &namespace) {- let source = legacy_brain_node(id, &item);- let node =- brain_node_with(self.split_github_by_repo, &self.layout, &source, &item)?;- return Ok(file_into(node, item));- }- }- Ok(item)- }-}--#[cfg(test)]-#[path = "map_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/map_tests.rs b/crates/openhuman-core/src/memory/layout_migration/map_tests.rsdeleted file mode 100644index c39803a20b..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/map_tests.rs+++ /dev/null@@ -1,197 +0,0 @@-use super::*;-use tinymemory_api::{LearningKind, MemoryMeta, Role, SourceKind, SourceRef, Turn};-use tinymemory_tools::BrainSource;--use crate::memory::brain::files_source;--fn ns(path: &str) -> Namespace {- path.parse().unwrap()-}--fn placement(root: &str) -> Placement {- Placement {- layout: MemoryLayout::new(ns(root)).unwrap(),- chat_node: ns("ws:main"),- flows: FlowPlacement::WithRoot,- split_github_by_repo: false,- }-}--fn document(namespace: &str, kind: SourceKind, file_path: Option<&str>) -> StoreItem {- StoreItem::document(- "a body",- MemoryMeta {- namespace: ns(namespace),- source: SourceRef { kind, id: None },- file_path: file_path.map(str::to_string),- agent_id: Some("orchestrator".into()),- ..MemoryMeta::default()- },- )-}--fn flow_learning() -> StoreItem {- StoreItem::learning(- "already sent item 5531",- LearningKind::Fact,- 0.9,- MemoryMeta {- tags: vec![- "flow:nl".into(),- FLOWS_TAG.into(),- "flow:nl:key:sent".into(),- ],- ..MemoryMeta::default()- },- )-}--#[test]-fn a_per_format_document_moves_to_the_files_node() {- let placement = placement("root");- let placed = placement- .place(document(- "source:pdf",- SourceKind::File,- Some("handbook.pdf"),- ))- .unwrap();- assert_eq!(- placed.meta().namespace,- placement.layout.brain(&files_source()).unwrap()- );- assert_eq!(- placed.meta().agent_id,- None,- "the brain belongs to every agent"- );-}--#[test]-fn a_web_link_stays_web_and_an_uploaded_page_is_a_file() {- let placement = placement("root");- let link = placement- .place(document("source:web", SourceKind::Link, None))- .unwrap();- assert_eq!(- link.meta().namespace,- placement.layout.brain(&BrainSource::Web).unwrap()- );- let page = placement- .place(document("source:web", SourceKind::Link, Some("page.html")))- .unwrap();- assert_eq!(- page.meta().namespace,- placement.layout.brain(&files_source()).unwrap()- );-}--#[test]-fn a_connector_document_keeps_its_node() {- let placement = placement("root");- let placed = placement- .place(document("source:gmail", SourceKind::Import, None))- .unwrap();- assert_eq!(placed.meta().namespace, ns("source:gmail"));-}--#[test]-fn a_github_document_goes_to_its_repository_when_the_setting_splits_them() {- let mut item = document("source:github", SourceKind::Import, None);- item.meta_mut().repo = Some("Acme/Widgets".into());- let mut placement = placement("root");- assert_eq!(- placement.place(item.clone()).unwrap().meta().namespace,- ns("source:github")- );- placement.split_github_by_repo = true;- assert_eq!(- placement.place(item).unwrap().meta().namespace,- placement- .layout- .brain_collection(&BrainSource::Github, "acme--widgets")- .unwrap()- );-}--#[test]-fn a_conversation_is_pooled_at_the_chat_node_with_its_agent() {- let placement = placement("root");- let turn = StoreItem::Conversation {- turns: vec![Turn {- role: Role::User,- text: "hi".into(),- at: None,- tool_calls: Vec::new(),- }],- meta: MemoryMeta {- namespace: ns("agent:orchestrator"),- agent_id: Some("orchestrator".into()),- thread_id: Some("thread-1".into()),- ..MemoryMeta::default()- },- };- let placed = placement.place(turn).unwrap();- assert_eq!(placed.meta().namespace, ns("ws:main"));- assert_eq!(placed.meta().agent_id.as_deref(), Some("orchestrator"));- assert_eq!(placed.meta().thread_id.as_deref(), Some("thread-1"));-}--#[test]-fn workflow_items_stay_with_the_root_until_the_switch_moves_them() {- let item = flow_learning();- let placed = placement("root").place(item.clone()).unwrap();- assert_eq!(placed, item, "with the root's learnings, unchanged");-- fn flow_node(id: &str) -> MemoryResult<Namespace> {- Ok(format!("ws:main/service:{id}").parse().unwrap())- }- let mut moved = placement("root");- moved.flows = FlowPlacement::InNode(flow_node);- let placed = moved.place(item).unwrap();- assert_eq!(placed.meta().namespace, ns("ws:main/service:nl"));-}--#[test]-fn a_flow_digest_document_is_a_workflow_item_not_a_brain_document() {- let mut digest = document("root", SourceKind::Agent, None);- digest.meta_mut().tags = vec!["flow:nl".into(), FLOWS_TAG.into(), "flow_run_digest".into()];- let placed = placement("root").place(digest.clone()).unwrap();- assert_eq!(placed, digest);-}--#[test]-fn a_learning_keeps_its_namespace() {- let learning = StoreItem::learning(- "prefers short answers",- LearningKind::Preference,- 0.8,- MemoryMeta::default(),- );- assert_eq!(placement("root").place(learning.clone()).unwrap(), learning);-}--#[test]-fn a_hosts_root_is_kept_below_the_wire_root() {- let placement = placement("team:acme");- let placed = placement- .place(document(- "team:acme/source:markdown",- SourceKind::File,- None,- ))- .unwrap();- assert_eq!(placed.meta().namespace, ns("team:acme/source:files"));- let outside = document("source:pdf", SourceKind::File, None);- assert_eq!(- placement.place(outside.clone()).unwrap(),- outside,- "a node outside the host's root is not its brain"- );-}--#[cfg(feature = "flows")]-#[test]-fn the_workflow_tag_is_the_one_flows_writes() {- assert_eq!(FLOWS_TAG, crate::flows::FLOWS_TAG);-}diff --git a/crates/openhuman-core/src/memory/layout_migration/service_tests.rs b/crates/openhuman-core/src/memory/layout_migration/service_tests.rsdeleted file mode 100644index fa4bfaafec..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/service_tests.rs+++ /dev/null@@ -1,142 +0,0 @@-use std::sync::atomic::Ordering;-use std::sync::Arc;--use tinymemory_api::MemoryEngine;--use super::*;-use crate::memory::layout_migration::test_host::{count, fact, FakeHost};--fn never() -> Arc<dyn Fn() -> bool + Send + Sync> {- Arc::new(|| false)-}--/// Waits (by yielding, not by the clock) for the workspace's run to end.-async fn settle(config: &Config) {- for _ in 0..100_000 {- if !is_running(config) {- return;- }- tokio::task::yield_now().await;- }- panic!("the run did not end");-}--#[tokio::test]-async fn scan_finds_legacy_memory_and_nothing_after_the_move() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(3).await);- assert_eq!(- scan(&config, host.as_ref()).await.unwrap(),- ScanView {- needed: true,- shared: false- }- );- assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));- settle(&config).await;- assert!(!scan(&config, host.as_ref()).await.unwrap().needed);- assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);-}--#[tokio::test]-async fn nothing_to_move_shows_nothing() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = FakeHost::with(0).await;- assert!(!scan(&config, &host).await.unwrap().needed);-}--#[tokio::test]-async fn one_run_per_workspace_at_a_time() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(200).await);- assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));- assert!(- !start(config.clone(), host.clone(), Trigger::Auto, never()),- "a second start while one runs starts nothing"- );- settle(&config).await;- assert_eq!(count(host.tree.as_ref()).await, 200);-}--#[tokio::test]-async fn a_stopped_run_reads_as_interrupted_and_a_tick_resumes_it() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(120).await);- let mut stopped = state::load(&config.workspace_dir).unwrap();- stopped.phase = Phase::Copying;- state::save(&config.workspace_dir, &stopped).unwrap();- assert!(status(&config).unwrap().interrupted);-- assert!(tick(&config, host.clone(), never()));- settle(&config).await;- assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);- assert!(!tick(&config, host, never()), "nothing left to do");-}--#[tokio::test]-async fn nothing_starts_while_an_import_is_unfinished() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(3).await);- let path = config- .workspace_dir- .join("memory")- .join("import_state.json");- std::fs::create_dir_all(path.parent().unwrap()).unwrap();- std::fs::write(- &path,- r#"{"state":{"phase":"running","total":3,"imported":1}}"#,- )- .unwrap();- assert!(crate::memory::import::in_progress(&config));- assert!(!start(config.clone(), host.clone(), Trigger::Auto, never()));- assert!(!tick(&config, host.clone(), never()));- assert_eq!(count(host.tree.as_ref()).await, 0);-- std::fs::write(- &path,- r#"{"state":{"phase":"done","total":3,"imported":3}}"#,- )- .unwrap();- assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));- settle(&config).await;- assert_eq!(count(host.tree.as_ref()).await, 3);-}--#[tokio::test]-async fn a_tick_starts_nothing_while_background_work_is_paused() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(3).await);- assert!(!tick(&config, host.clone(), Arc::new(|| true)));- assert_eq!(count(host.tree.as_ref()).await, 0);-}--#[tokio::test]-async fn retry_puts_a_lost_copy_back_in_line() {- let tmp = tempfile::tempdir().unwrap();- let config = crate::memory::test_fixtures::config_in(&tmp);- let host = Arc::new(FakeHost::with(4).await);- host.free.store(true, Ordering::SeqCst);- assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));- settle(&config).await;- assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);-- // A legacy item the move did not reach (written after cleanup).- host.legacy.store(fact("late")).await.unwrap();- let state = retry(&config).unwrap();- assert!(!state.caught_up && !state.cleaning);- assert!(start(- config.clone(),- host.clone(),- Trigger::Manual { takeover: false },- never()- ));- settle(&config).await;- assert_eq!(count(host.tree.as_ref()).await, 5);- assert_eq!(count(host.legacy.as_ref()).await, 0);-}diff --git a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs b/crates/openhuman-core/src/memory/layout_migration/state_tests.rsdeleted file mode 100644index 427b238279..0000000000--- a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs+++ /dev/null@@ -1,41 +0,0 @@-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());-}