Skip to content

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

feat(memory): copy the legacy CortexDB tree into the per-user tree

M3gA-Minddadde9f06555
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 825293598d..3bd32d3900 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -132,7 +132,7 @@ where
/// credit balance (an `Engine` error), an unreachable or overloaded engine
/// (`Unavailable`). Skipping those would advance the checkpoint past items
/// that were never stored and finish `Done` with nothing imported.
-fn skips_item(error: &tinymemory_api::Error) -> bool {
+pub(super) fn skips_item(error: &tinymemory_api::Error) -> bool {
use tinymemory_api::Error as E;
matches!(
error,
diff --git a/crates/openhuman-core/src/memory/layout_migration/copy.rs b/crates/openhuman-core/src/memory/layout_migration/copy.rs
new file mode 100644
index 0000000000..21f49a7dec
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/copy.rs
@@ -0,0 +1,178 @@
+//! 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(
+ workspace_dir: &Path,
+ engines: &Engines,
+ placement: &Placement,
+ state: &mut MigrationState,
+ paused: impl Fn() -> bool,
+) -> MemoryResult<()> {
+ state.phase = Phase::Copying;
+ state.error = None;
+ state::save(workspace_dir, state)?;
+ loop {
+ if paused() {
+ 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);
+ }
+ };
+ state
+ .incomplete
+ .extend(page.incomplete.into_iter().map(|id| 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) => state.failures.push(Failure {
+ id: exported.id.0,
+ reason: error.code().to_string(),
+ }),
+ }
+ }
+ 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)?;
+ }
+}
+
+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) => state.failures.push(Failure {
+ id: legacy,
+ reason: MemoryError::from(error).code().to_string(),
+ }),
+ }
+ }
+ }
+ }
+ 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 {
+ state.failures.push(Failure {
+ id: legacy,
+ reason: "not_readable_after_store".to_string(),
+ });
+ }
+ }
+ 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.rs
new file mode 100644
index 0000000000..acc474b4fd
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
@@ -0,0 +1,194 @@
+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,
+ }
+}
+
+/// 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, || 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, || {
+ pages.fetch_add(1, Ordering::SeqCst) >= 1
+ })
+ .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, || 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, || false)
+ .await
+ .unwrap();
+ let mut again = MigrationState::default();
+ copy(tmp.path(), &engines, &placement(), &mut again, || 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 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, || 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, || false)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Paused);
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/map.rs b/crates/openhuman-core/src/memory/layout_migration/map.rs
new file mode 100644
index 0000000000..7ec6fbc68a
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/map.rs
@@ -0,0 +1,93 @@
+//! 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 [`file_into`], the same placement new syncs
+//! use (`pdf`, `markdown` and the other per-format nodes become `files`).
+//! - **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::flows::FLOWS_TAG;
+use crate::memory::brain::{file_into, legacy_brain_node};
+use crate::memory::error::MemoryResult;
+
+/// 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,
+}
+
+/// 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);
+ return file_into(&self.layout, &source, 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.rs
new file mode 100644
index 0000000000..b91e3d90ab
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/map_tests.rs
@@ -0,0 +1,171 @@
+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,
+ }
+}
+
+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::Composio, None))
+ .unwrap();
+ assert_eq!(placed.meta().namespace, ns("source:gmail"));
+}
+
+#[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"
+ );
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
new file mode 100644
index 0000000000..a910f11d9c
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -0,0 +1,21 @@
+//! 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 `user:<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.
+//!
+//! 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.
+
+pub mod copy;
+pub mod map;
+pub mod state;
+
+pub use copy::{copy, legacy_present, Engines};
+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.rs
new file mode 100644
index 0000000000..2065ff07ff
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs
@@ -0,0 +1,110 @@
+//! The migration's state on disk, `<workspace>/memory/layout_migration.json`.
+//!
+//! 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.
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+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,
+}
+
+/// 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'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>,
+}
+
+/// The state file of `workspace_dir`.
+#[must_use]
+pub fn path(workspace_dir: &Path) -> PathBuf {
+ workspace_dir.join("memory").join("layout_migration.json")
+}
+
+/// The saved state, or a fresh one when none was saved.
+///
+/// # Errors
+///
+/// A state file that cannot be read or parsed: the migration must not start
+/// over and copy everything again on a damaged file.
+pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {
+ let file = path(workspace_dir);
+ match std::fs::read(&file) {
+ Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
+ MemoryError::Engine(format!("layout migration state unreadable: {error}"))
+ }),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(MigrationState::default()),
+ Err(error) => Err(MemoryError::Engine(format!(
+ "layout migration state unreadable: {error}"
+ ))),
+ }
+}
+
+/// Saves `state` whole: a temporary file, synced, then renamed over the old.
+///
+/// # Errors
+///
+/// When the file cannot be written.
+pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {
+ let file = path(workspace_dir);
+ let write = || -> std::io::Result<()> {
+ if let Some(dir) = file.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let temp = file.with_extension("json.tmp");
+ let bytes = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;
+ let mut out = std::fs::File::create(&temp)?;
+ std::io::Write::write_all(&mut out, &bytes)?;
+ out.sync_all()?;
+ std::fs::rename(&temp, &file)
+ };
+ write()
+ .map_err(|error| MemoryError::Engine(format!("layout migration state not saved: {error}")))
+}
+
+#[cfg(test)]
+#[path = "state_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs
new file mode 100644
index 0000000000..03723144cb
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs
@@ -0,0 +1,35 @@
+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()),
+ };
+ 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());
+}
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index 0a9cad0311..4136945175 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -30,6 +30,7 @@ pub mod error;
pub mod explore;
pub mod guard;
pub mod import;
+pub mod layout_migration;
pub mod lifecycle;
pub mod ops;
pub mod schemas;