Skip to content

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

feat(config): add migration helpers for config schema evolution

Steven Enamakel3bc6a3ded42b
diff --git a/crates/openhuman-core/src/config/migration_helpers/README.md b/crates/openhuman-core/src/config/migration_helpers/README.md
deleted file mode 100644
index b4032f3a9c..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# migration
-
-Data-migration helpers that import memory from other AI assistants' workspaces (OpenClaw, Hermes Agent) into the current OpenHuman workspace's memory backend. It scans a source workspace for SQLite (`brain.db`) and Markdown memory artifacts, normalizes them into `Memory` entries, backs up the target's existing memory, and writes the imported entries. It supports a `dry_run` plan-only mode and idempotent re-runs (unchanged entries are skipped, conflicts are renamed). It exposes two RPC controllers under the `migrate` namespace.
-
-> Not to be confused with `crate::config::migrations` (plural), which handles internal config **schema** version upgrades. This module migrates **user memory data** from foreign vendors.
-
-## Responsibilities
-
-- Resolve a source workspace path (explicit override, else vendor default: `~/.openclaw/workspace`, or `~/.hermes` / `%LOCALAPPDATA%\hermes` on Windows).
-- Refuse self-migration when source resolves to the current OpenHuman workspace.
-- OpenClaw: read memory entries from `memory/brain.db` (SQLite `memories` table, schema-tolerant column detection) plus `MEMORY.md` and `memory/*.md`.
-- Hermes: read a fixed file mapping, `MEMORY.md` to core, `USER.md` to `Custom("user_profile")`, `SOUL.md` to `Custom("persona")`.
-- Normalize keys (non-alphanumeric → `_`), parse/map categories, de-dup exact duplicates for deterministic re-runs.
-- Back up the target workspace's existing memory (`MEMORY.md`, `brain.db`, `memory/*.md` → `memory_backup/`) before applying.
-- Import into the target memory backend: skip entries whose content is unchanged, rename key on content conflict (`key_1`, `key_2`, …).
-- Produce a `MigrationReport` (source/target paths, dry-run flag, `MigrationStats`, warnings).
-
-## Key files
-
-| File | Role |
-| --- | --- |
-| `crates/openhuman-core/src/config/migration_helpers/mod.rs` | Export-only: declares `core`/`ops`/`schemas`, re-exports `core::*` and `ops::*`, aliases `ops as rpc`, and exports the `all_migration_controller_schemas` / `all_migration_registered_controllers` pair. |
-| `crates/openhuman-core/src/config/migration_helpers/core.rs` | Host seam. `migrate_openclaw_memory` / `migrate_hermes_memory` call `tinymemory-import` (which owns `MigrationStats`/`MigrationReport`, the SQLite + Markdown source readers, workspace resolution, key/category normalization, backup and conflict-rename helpers) with the target workspace and `target_memory_backend`, the closure that binds the driver and refuses the null one. |
-| `crates/openhuman-core/src/config/migration_helpers/ops.rs` | JSON-RPC/CLI adapter (the canonical handler file, re-exported as `rpc`). `migrate_openclaw` / `migrate_hermes` wrap the core fns, map `anyhow::Error` → `String`, and return `Outcome<MigrationReport>` with a `"migration completed"` log. Tests cover dry-run, apply, missing-source, and self-migration. |
-| `crates/openhuman-core/src/config/migration_helpers/schemas.rs` | Controller schemas + handlers. Defines `MigrateOpenClawParams` / `MigrateHermesParams`, `all_controller_schemas`, `all_registered_controllers`, `schemas(function)`, and `handle_migrate_openclaw` / `handle_migrate_hermes` which load config and delegate to `migration_helpers::rpc::*`. |
-
-## Public surface
-
-From `mod.rs` re-exports (`core::*` + `ops::*`):
-
-- Types: `MigrationReport`, `MigrationStats`.
-- Core fns: `migrate_openclaw_memory(config, source_workspace, dry_run) -> Result<MigrationReport>`, `migrate_hermes_memory(...)`.
-- RPC fns (via `ops` / alias `rpc`): `migrate_openclaw(...) -> Result<Outcome<MigrationReport>, String>`, `migrate_hermes(...)`.
-- Controller registry exports: `all_migration_controller_schemas`, `all_migration_registered_controllers`.
-
-(The importers' internals are private to `tinymemory-import`; `target_memory_backend` is private to `core.rs`.)
-
-## RPC / controllers
-
-Two controllers in the `migrate` namespace (registered via `all_registered_controllers`):
-
-| Method | Description | Inputs | Output |
-| --- | --- | --- | --- |
-| `migrate.openclaw` | Migrate OpenClaw memory into current workspace. | `source_workspace?: String`, `dry_run?: bool` | `report: MigrationReport` |
-| `migrate.hermes` | Migrate Hermes Agent memory into current workspace. | `source_workspace?: String`, `dry_run?: bool` | `report: MigrationReport` |
-
-Both inputs are optional; `dry_run` **defaults to `true`** when omitted (`handle_*` use `unwrap_or(true)`). Handlers load config via `config_rpc::load_config_with_timeout()`. Unknown function names yield an `"unknown"` placeholder schema with an `error` output.
-
-## Agent tools
-
-None. This module owns no `tools.rs`.
-
-## Events
-
-None. No `bus.rs` / event-bus subscribers or publishers.
-
-## Persistence
-
-No own store. It writes imported entries through the **target memory backend** obtained from `memory_store::create_memory_for_migration(&config.memory, &config.workspace_dir)`, using `Memory::store` / `Memory::get`. Before applying (non-dry-run), it copies the target's existing memory artifacts into `<workspace_dir>/memory_backup/`.
-
-## Dependencies
-
-- `crate::config::Config`: source of `workspace_dir` and `memory` config; `config::rpc::load_config_with_timeout` in handlers.
-- `crate::memory` (`Memory`, `MemoryCategory`): target backend trait plus the category enum entries are mapped into.
-- `crate::memory::store`: `create_memory_for_migration` constructs the target memory backend.
-- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller registry/schema types.
-- `crate::core::Outcome`: RPC response envelope.
-- Vendored: `tinymemory-import` (the importers; it carries `rusqlite` and `directories`). External crates here: `anyhow`.
-
-## Used by
-
-- `crates/openhuman-core/src/core/all.rs` registers `all_migration_registered_controllers()` (line ~165) and `all_migration_controller_schemas()` (line ~319) into the global controller/schema registry, exposing both methods over CLI and JSON-RPC.
-
-## Notes / gotchas
-
-- `dry_run` default is `true` at the RPC boundary. Callers must explicitly pass `dry_run: false` to actually apply a migration.
-- OpenClaw SQLite reading is **schema-tolerant**: it inspects `PRAGMA table_info(memories)` and picks key/content/category columns from candidate name lists (`key`/`id`/`name`, `content`/`value`/`text`/`memory`, `category`/`kind`/`type`), bailing only if no content-like column exists. DB is opened read-only.
-- Idempotency: exact-duplicate source entries are de-duped; unchanged target entries are skipped (`skipped_unchanged`); content conflicts get a renamed key (`renamed_conflicts`).
-- `migrate_openclaw_apply_imports_markdown_entries` in `ops.rs` documents a regression (#1440): the apply path previously bailed in `create_memory_for_migration` under the unified-namespace memory core; that hard-disable was removed.
-- Memory entries are stored under the empty namespace (`""`).
diff --git a/crates/openhuman-core/src/config/migration_helpers/core.rs b/crates/openhuman-core/src/config/migration_helpers/core.rs
deleted file mode 100644
index 19a51c7d3d..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/core.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-use crate::config::Config;
-use crate::memory::Memory;
-use anyhow::Result;
-use std::path::PathBuf;
-use std::sync::Arc;
-
-pub use tinymemory_import::{MigrationReport, MigrationStats};
-
-/// Import an OpenClaw workspace into this host's memory.
-///
-/// The importer is `tinymemory-import`'s; the host supplies the target
-/// workspace and [`target_memory_backend`], which it opens only once there is
-/// something to write.
-pub async fn migrate_openclaw_memory(
- config: &Config,
- source_workspace: Option<PathBuf>,
- dry_run: bool,
-) -> Result<MigrationReport> {
- tinymemory_import::migrate_openclaw_memory(
- &config.workspace_dir,
- source_workspace,
- dry_run,
- || target_memory_backend(config),
- )
- .await
-}
-
-/// Import a Hermes workspace into this host's memory. See
-/// [`migrate_openclaw_memory`].
-pub async fn migrate_hermes_memory(
- config: &Config,
- source_workspace: Option<PathBuf>,
- dry_run: bool,
-) -> Result<MigrationReport> {
- tinymemory_import::migrate_hermes_memory(
- &config.workspace_dir,
- source_workspace,
- dry_run,
- || target_memory_backend(config),
- )
- .await
-}
-
-/// The memory the import writes into.
-///
-/// The bound driver, through [`DriverMemory`] — the same store the engine
-/// constructor this replaced opened. That equivalence is checked rather than
-/// assumed: `create_memory_for_migration` bottoms out in
-/// `create_memory_full(..., workspace_dir, "memory")`, and
-/// `binding::for_workspace` resolves `for_subtree(workspace_dir, "memory")`.
-/// Same workspace, same subtree.
-///
-/// # Why the capture budget does not bite here
-///
-/// This note used to say the contract had no door for an import, because
-/// `MemoryCore::store` is reached through `MemoryGuard`, which applies
-/// `MemoryHooksConfig::capture_max_chars` to every body — and an imported
-/// `MEMORY.md` entry is routinely longer than that, so routing an import
-/// through the guard would silently truncate the user's own memories.
-///
-/// The budget is real, and it is enforced host-side in
-/// `memory::guard::policy`. What the note missed is that `DriverMemory` does
-/// not go through the guard at all: it wraps `binding.provider()`, which is the
-/// **unguarded** driver — the binding keeps the guarded one separately behind
-/// `binding.guard()`. So an import writes full bodies here exactly as the
-/// engine constructor did, and no policy has to be special-cased to allow it.
-///
-/// # A null driver is refused, not imported into
-///
-/// `binding` answers the null driver in three situations: `[subsystems.memory]
-/// driver = "null"` is configured; a configured driver failed to bind and fell
-/// back; and — the one this note used to miss — a driver was *admitted* as a
-/// module but this build has no module to bind, so `binding::module_provider`
-/// substituted the null provider under `#[cfg(not(feature = "modules"))]`.
-/// In all three, every write below is discarded. An import that reports
-/// "migrated N entries" having written none is silent data loss of the worst
-/// kind — the source workspace may be deleted on the strength of that report,
-/// and the user only discovers it later, with nothing left to re-run against.
-/// So this refuses up front and names which of the three it was.
-///
-/// Telling the third case apart needs what was *admitted*, not what was bound.
-/// `admit` is pure config and never saw the feature flag, so it answers
-/// `Module` for the configured `tinycortex`; `module_provider` then binds the
-/// null provider, and the binding reports `class = Null` with **no**
-/// `fallback`, since nothing refused. So `admitted != bound` is the signal, and
-/// it is the only one that works: `driver_id` alone does not separate this from
-/// a driver deliberately given `class = "null"`, because `admit` accepts a
-/// non-built-in id with that class (the `built_in_class` check is skipped for
-/// ids that are not built in) and returns it verbatim. Keying on the id would
-/// tell a user with a working modules build that their `modules` feature was
-/// off — the same class of misdirection this whole note exists to prevent.
-///
-/// Keying on the class alone was the original bug: it put the modules-off case
-/// in the configured-null arm and told a user whose config says `driver =
-/// "tinycortex"` that they had set it to `"null"`, sending them to edit a line
-/// that already said the opposite.
-fn target_memory_backend(config: &Config) -> Result<Arc<dyn Memory>> {
- let binding = crate::memory::binding::for_config(config)
- .map_err(|e| anyhow::anyhow!("bind memory for migration import: {e}"))?;
- if binding.class() == crate::core::subsystem::DriverClass::Null {
- let admitted = crate::memory::binding::admit(&config.subsystems.memory).ok();
- let because = match (binding.fallback(), admitted) {
- (Some(fallback), _) => format!(
- "driver '{}' refused to bind: {}",
- fallback.configured_driver, fallback.reason
- ),
- // Admitted as the null driver: the user asked for no memory.
- (None, Some((id, crate::core::subsystem::DriverClass::Null)))
- if id == tinymemory_api::null::NULL_DRIVER_ID =>
- {
- "memory is disabled by configuration ([subsystems.memory] driver = \"null\")"
- .to_string()
- }
- (None, Some((id, crate::core::subsystem::DriverClass::Null))) => format!(
- "driver '{id}' is configured with class \"null\" under \
- [subsystems.memory.drivers.{id}], so every write is discarded"
- ),
- // Admitted as something that can hold data, bound to the null
- // provider anyway — the module substitution.
- (None, Some((id, _))) => format!(
- "driver '{id}' is configured, but this build has no memory module \
- compiled in (the 'modules' feature is off), so nothing can be written"
- ),
- // `admit` refused: `build` records that as a fallback, so this is
- // unreachable. Named rather than merged into an arm that would
- // state a cause this branch cannot actually establish.
- (None, None) => format!(
- "driver '{}' bound the null provider and the reason was not recorded",
- binding.driver_id()
- ),
- };
- anyhow::bail!(
- "refusing to import memory into the null driver — {because}. \
- Nothing was imported; the source workspace is untouched."
- );
- }
- crate::agent::experience::ops::DriverMemory::for_config(config)
- .map_err(|e| anyhow::anyhow!("bind memory for migration import: {e}"))
-}
diff --git a/crates/openhuman-core/src/config/migration_helpers/mod.rs b/crates/openhuman-core/src/config/migration_helpers/mod.rs
deleted file mode 100644
index baf655919b..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/mod.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-//! Data migration helpers for OpenHuman.
-
-mod core;
-pub mod ops;
-mod schemas;
-
-pub use core::*;
-pub use ops as rpc;
-pub use ops::*;
-pub use schemas::{
- all_controller_schemas as all_migration_controller_schemas,
- all_registered_controllers as all_migration_registered_controllers,
-};
diff --git a/crates/openhuman-core/src/config/migration_helpers/ops.rs b/crates/openhuman-core/src/config/migration_helpers/ops.rs
deleted file mode 100644
index 1ae18dd4d7..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/ops.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-//! JSON-RPC / CLI controller surface for data migration.
-
-use std::path::PathBuf;
-
-use crate::config::migration_helpers::{self, MigrationReport};
-use crate::config::Config;
-use crate::core::Outcome;
-
-pub async fn migrate_openclaw(
- config: &Config,
- source_workspace: Option<PathBuf>,
- dry_run: bool,
-) -> Result<Outcome<MigrationReport>, String> {
- let report = migration_helpers::migrate_openclaw_memory(config, source_workspace, dry_run)
- .await
- .map_err(|e| e.to_string())?;
- Ok(Outcome::single_log(report, "migration completed"))
-}
-
-pub async fn migrate_hermes(
- config: &Config,
- source_workspace: Option<PathBuf>,
- dry_run: bool,
-) -> Result<Outcome<MigrationReport>, String> {
- let report = migration_helpers::migrate_hermes_memory(config, source_workspace, dry_run)
- .await
- .map_err(|e| e.to_string())?;
- Ok(Outcome::single_log(report, "migration completed"))
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/config/migration_helpers/ops_tests.rs b/crates/openhuman-core/src/config/migration_helpers/ops_tests.rs
deleted file mode 100644
index 808e305972..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/ops_tests.rs
+++ /dev/null
@@ -1,334 +0,0 @@
-use super::*;
-use tempfile::TempDir;
-
-fn test_config(tmp: &TempDir) -> Config {
- // Apply-mode migrations create unified-memory entries. The memory
- // engine's host seams are explicit, so install the test wiring before
- // constructing a configuration that can exercise that path.
- Config {
- workspace_dir: tmp.path().join("workspace"),
- action_dir: tmp.path().join("workspace"),
- config_path: tmp.path().join("config.toml"),
- ..Config::default()
- }
-}
-
-#[tokio::test]
-async fn migrate_openclaw_dry_run_on_empty_source_returns_report() {
- // A fresh temp workspace contains nothing to migrate. The
- // underlying migration helper should still return a report
- // rather than erroring, and the wrapper should attach the
- // canonical completion log.
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- let result = migrate_openclaw(&config, Some(tmp.path().to_path_buf()), true).await;
- match result {
- Ok(outcome) => {
- assert!(
- outcome
- .logs
- .iter()
- .any(|l| l.contains("migration completed")),
- "expected 'migration completed' log, got logs: {:?}",
- outcome.logs
- );
- }
- Err(e) => panic!("dry_run on empty source should not error: {e}"),
- }
-}
-
-// Apply writes into the bound memory driver, which only exists when a
-// memory module is compiled in. With `--no-default-features`,
-// `binding::module_provider` substitutes the null provider, and
-// `target_memory_backend` then refuses the import rather than reporting
-// entries it discarded — correct behaviour, and the opposite of what this
-// case asserts. Gated rather than made tolerant of both answers: a test
-// that passes on either outcome would stop witnessing the import at all.
-// The gates-off half of the same seam is
-// `apply_refuses_and_names_the_build_when_no_memory_module_is_compiled_in`
-// below.
-#[cfg(feature = "modules")]
-#[tokio::test]
-async fn migrate_openclaw_apply_imports_markdown_entries_into_target_workspace() {
- // Apply writes through the memory module: wait out its load first (see
- // `migrate_hermes_apply_imports_markdown_entries`).
- crate::memory::test_support::settle_memory_module().await;
- // Regression for #1440: prior to this PR the Apply path
- // (`dry_run = false`) bailed at `create_memory_for_migration`
- // because the unified namespace memory core hard-disabled it.
- // With the disable removed, Apply must actually move markdown
- // entries from the OpenClaw source workspace into the target.
- // The apply path does real memory work, so it needs the embedding host
- // seam installed. In the default build another test installs the
- // process-global host first; under `--no-default-features` those tests
- // are gated out, so this test must install it itself (idempotent).
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- // Fake OpenClaw workspace with two markdown entries — no
- // brain.db needed; the migration path reads MEMORY.md + any
- // memory/*.md files.
- let source = tmp.path().join("openclaw-src");
- std::fs::create_dir_all(source.join("memory")).unwrap();
- std::fs::write(source.join("MEMORY.md"), "# Top-level note\nimport me").unwrap();
- std::fs::write(
- source.join("memory").join("sprint.md"),
- "# Sprint plan\nweek one design",
- )
- .unwrap();
-
- let outcome = migrate_openclaw(&config, Some(source), false)
- .await
- .expect("apply path should succeed on the unified core after #1440");
- let report = outcome.value;
- assert!(!report.dry_run, "apply must produce a non-dry-run report");
- assert!(
- report.stats.imported >= 1,
- "apply must import at least one entry; stats={:?}",
- report.stats
- );
-}
-
-/// With no memory module compiled in, apply must refuse — and the refusal
-/// must name the build, not the user's config.
-///
-/// `admit` is pure config and never sees the feature flag, so it admits the
-/// configured `tinycortex`; `module_provider` then substitutes the null
-/// provider because there is no module to bind. The binding that comes back
-/// therefore reports `class = Null` with `driver_id = "tinymemory"` and no
-/// `fallback` — nothing refused, so there is nothing to fall back from.
-///
-/// Keyed on the class alone, that landed in the configured-null arm and told
-/// a user whose `config.toml` says `driver = "tinycortex"` that memory was
-/// "disabled by configuration ([subsystems.memory] driver = \"null\")",
-/// pointing them at a line that says the opposite. This asserts both halves:
-/// the import is still refused (silent data loss stays impossible), and the
-/// reason given is the missing module.
-#[cfg(not(feature = "modules"))]
-#[tokio::test]
-async fn apply_refuses_and_names_the_build_when_no_memory_module_is_compiled_in() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- let source = tmp.path().join("openclaw-src");
- std::fs::create_dir_all(&source).unwrap();
- let entry = source.join("MEMORY.md");
- let original = "# Note\nwould be lost";
- std::fs::write(&entry, original).unwrap();
-
- let err = migrate_openclaw(&config, Some(source), false)
- .await
- .expect_err("apply must refuse with no memory module compiled in");
-
- assert!(
- err.contains("this build has no memory module compiled in"),
- "refusal must name the missing module as the cause; got: {err}"
- );
- assert!(
- !err.contains("[subsystems.memory] driver = \"null\""),
- "refusal must not blame a config line the user did not write; got: {err}"
- );
- assert!(
- err.contains("the source workspace is untouched"),
- "refusal must still promise the source survived; got: {err}"
- );
- // The promise, checked rather than taken on trust: a refusal that moved
- // or truncated the source would be the very loss it claims to prevent.
- assert_eq!(
- std::fs::read_to_string(&entry).expect("source entry must still be readable"),
- original,
- "the refused import must leave the source workspace byte-identical"
- );
-}
-
-/// A driver deliberately given `class = "null"` is not a modules-off build.
-///
-/// Codex raised this against the first version of the fix above, and it was
-/// right. `admit` skips its `built_in_class` check for an id that is not
-/// built in, so `[subsystems.memory] driver = "mynull"` with
-/// `class = "null"` is admitted verbatim: `class = Null`, no `fallback`, and
-/// a `driver_id` that is not `"null"`. Keyed on the id, that landed in the
-/// modules-off arm and told a user with a perfectly good modules build that
-/// their `modules` feature was off.
-///
-/// Keying on what `admit` *answered* separates them: here it answers `Null`,
-/// where the modules-off case answers `Module` and is then bound to the null
-/// provider. This runs in **every** feature configuration, because the
-/// confusion it guards against is one a modules-enabled build can hit.
-#[tokio::test]
-async fn apply_names_a_deliberately_null_classed_driver_rather_than_the_build() {
- use crate::config::schema::{MemoryDriverConfig, MemorySubsystemConfig};
-
- let tmp = TempDir::new().unwrap();
- let mut config = test_config(&tmp);
- let mut drivers = std::collections::BTreeMap::new();
- drivers.insert(
- "mynull".to_string(),
- MemoryDriverConfig {
- class: Some("null".to_string()),
- ..Default::default()
- },
- );
- config.subsystems.memory = MemorySubsystemConfig {
- driver: "mynull".to_string(),
- drivers,
- ..Default::default()
- };
-
- let source = tmp.path().join("openclaw-src");
- std::fs::create_dir_all(&source).unwrap();
- std::fs::write(source.join("MEMORY.md"), "# Note\nkeep me").unwrap();
-
- let err = migrate_openclaw(&config, Some(source), false)
- .await
- .expect_err("apply must refuse a null-classed driver");
-
- assert!(
- err.contains("mynull") && err.contains("class"),
- "refusal must name the driver and its configured class; got: {err}"
- );
- assert!(
- !err.contains("no memory module compiled in"),
- "a deliberately null-classed driver must not be reported as a \
- modules-off build; got: {err}"
- );
-}
-
-#[tokio::test]
-async fn migrate_openclaw_returns_error_for_missing_source_workspace() {
- // Pointing at a non-existent source directory must surface as
- // an Err from the wrapper (the underlying `migrate_openclaw_memory`
- // bails with "OpenClaw workspace not found at ..."), so the
- // JSON-RPC adapter can return the error to the caller.
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- let missing = tmp.path().join("does-not-exist").join("nested");
- let err = migrate_openclaw(&config, Some(missing), false)
- .await
- .expect_err("missing source workspace must surface as Err");
- assert!(
- !err.is_empty(),
- "error string must be non-empty so the RPC caller sees a reason"
- );
-}
-
-// ── Hermes migration tests ──────────────────────────────────────
-
-#[tokio::test]
-async fn migrate_hermes_dry_run_on_empty_source_returns_report() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- let result = migrate_hermes(&config, Some(tmp.path().to_path_buf()), true).await;
- match result {
- Ok(outcome) => {
- assert!(
- outcome
- .logs
- .iter()
- .any(|l| l.contains("migration completed")),
- "expected 'migration completed' log, got logs: {:?}",
- outcome.logs
- );
- }
- Err(e) => panic!("dry_run on empty source should not error: {e}"),
- }
-}
-
-// Apply writes into the bound memory driver, which only exists when a
-// memory module is compiled in. With `--no-default-features`,
-// `binding::module_provider` substitutes the null provider, and
-// `target_memory_backend` then refuses the import rather than reporting
-// entries it discarded — correct behaviour, and the opposite of what this
-// case asserts. Gated rather than made tolerant of both answers: a test
-// that passes on either outcome would stop witnessing the import at all.
-// The gates-off half of the same seam is
-// `apply_refuses_and_names_the_build_when_no_memory_module_is_compiled_in`
-// below.
-#[cfg(feature = "modules")]
-#[tokio::test]
-async fn migrate_hermes_apply_imports_markdown_entries() {
- // Apply does real memory work: wait out the memory module's load first,
- // or the import races it and answers "memory is still starting". A test
- // that runs in its own process (cargo nextest) always hits that window;
- // one sharing a process with earlier memory tests usually misses it.
- crate::memory::test_support::settle_memory_module().await;
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- let source = tmp.path().join("hermes-src");
- std::fs::create_dir_all(&source).unwrap();
- // Cover the full Hermes file mapping (MEMORY.md / USER.md / SOUL.md)
- // so the apply path is exercised for every category — including the
- // `Custom("persona")` SOUL.md branch which @graycyrus called out as
- // untested in the original review on this PR.
- std::fs::write(source.join("MEMORY.md"), "# Agent memory\nremember this").unwrap();
- std::fs::write(
- source.join("USER.md"),
- "# User profile\nprefers concise answers",
- )
- .unwrap();
- std::fs::write(source.join("SOUL.md"), "# Persona\ncalm and curious").unwrap();
-
- let outcome = migrate_hermes(&config, Some(source), false)
- .await
- .expect("apply path should succeed");
- let report = outcome.value;
- assert!(!report.dry_run);
- assert!(
- report.stats.imported >= 3,
- "apply must import all 3 entries; stats={:?}",
- report.stats
- );
- assert_eq!(report.stats.from_markdown, 3);
-}
-
-#[tokio::test]
-async fn migrate_hermes_skips_missing_optional_files() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- let source = tmp.path().join("hermes-src");
- std::fs::create_dir_all(&source).unwrap();
- std::fs::write(source.join("MEMORY.md"), "# Memory\nonly memory").unwrap();
-
- let outcome = migrate_hermes(&config, Some(source), true)
- .await
- .expect("should succeed with partial files");
- let report = outcome.value;
- assert_eq!(report.stats.from_markdown, 1);
- assert!(
- report.warnings.iter().any(|w| w.contains("USER.md")),
- "warnings should mention missing USER.md: {:?}",
- report.warnings
- );
- assert!(
- report.warnings.iter().any(|w| w.contains("SOUL.md")),
- "warnings should mention missing SOUL.md: {:?}",
- report.warnings
- );
-}
-
-#[tokio::test]
-async fn migrate_hermes_returns_error_for_missing_source() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- let missing = tmp.path().join("does-not-exist");
- let err = migrate_hermes(&config, Some(missing), false)
- .await
- .expect_err("missing source must surface as Err");
- assert!(!err.is_empty());
-}
-
-#[tokio::test]
-async fn migrate_hermes_refuses_self_migration() {
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- std::fs::create_dir_all(&config.workspace_dir).unwrap();
- let err = migrate_hermes(&config, Some(config.workspace_dir.clone()), false)
- .await
- .expect_err("self-migration must be refused");
- assert!(
- err.contains("self-migration"),
- "error should mention self-migration: {err}"
- );
-}
diff --git a/crates/openhuman-core/src/config/migration_helpers/schemas.rs b/crates/openhuman-core/src/config/migration_helpers/schemas.rs
deleted file mode 100644
index 88ecb7e498..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/schemas.rs
+++ /dev/null
@@ -1,145 +0,0 @@
-use serde::Deserialize;
-use serde_json::{Map, Value};
-
-use crate::config::rpc as config_rpc;
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::Outcome;
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-
-#[derive(Debug, Deserialize)]
-struct MigrateOpenClawParams {
- source_workspace: Option<String>,
- dry_run: Option<bool>,
-}
-
-#[derive(Debug, Deserialize)]
-struct MigrateHermesParams {
- source_workspace: Option<String>,
- dry_run: Option<bool>,
-}
-
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![schemas("openclaw"), schemas("hermes")]
-}
-
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schemas("openclaw"),
- handler: handle_migrate_openclaw,
- },
- RegisteredController {
- schema: schemas("hermes"),
- handler: handle_migrate_hermes,
- },
- ]
-}
-
-pub fn schemas(function: &str) -> ControllerSchema {
- match function {
- "openclaw" => ControllerSchema {
- namespace: "migrate",
- function: "openclaw",
- description: "Migrate OpenClaw memory into current workspace.",
- inputs: vec![
- FieldSchema {
- name: "source_workspace",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional source workspace path override.",
- required: false,
- },
- FieldSchema {
- name: "dry_run",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "When true, report migration plan only.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "report",
- ty: TypeSchema::Ref("MigrationReport"),
- comment: "Migration report and stats.",
- required: true,
- }],
- },
- "hermes" => ControllerSchema {
- namespace: "migrate",
- function: "hermes",
- description: "Migrate Hermes Agent memory into current workspace.",
- inputs: vec![
- FieldSchema {
- name: "source_workspace",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional source workspace path override.",
- required: false,
- },
- FieldSchema {
- name: "dry_run",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "When true, report migration plan only.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "report",
- ty: TypeSchema::Ref("MigrationReport"),
- comment: "Migration report and stats.",
- required: true,
- }],
- },
- _ => ControllerSchema {
- namespace: "migrate",
- function: "unknown",
- description: "Unknown migration controller function.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
- }
-}
-
-fn handle_migrate_openclaw(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let payload: MigrateOpenClawParams = serde_json::from_value(Value::Object(params))
- .map_err(|e| format!("invalid params: {e}"))?;
- let source = payload.source_workspace.map(std::path::PathBuf::from);
- to_json(
- crate::config::migration_helpers::rpc::migrate_openclaw(
- &config,
- source,
- payload.dry_run.unwrap_or(true),
- )
- .await?,
- )
- })
-}
-
-fn handle_migrate_hermes(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let payload: MigrateHermesParams = serde_json::from_value(Value::Object(params))
- .map_err(|e| format!("invalid params: {e}"))?;
- let source = payload.source_workspace.map(std::path::PathBuf::from);
- to_json(
- crate::config::migration_helpers::rpc::migrate_hermes(
- &config,
- source,
- payload.dry_run.unwrap_or(true),
- )
- .await?,
- )
- })
-}
-
-fn to_json<T: serde::Serialize>(outcome: Outcome<T>) -> Result<Value, String> {
- outcome.into_cli_compatible_json()
-}
-
-#[cfg(test)]
-#[path = "schemas_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs b/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs
deleted file mode 100644
index 4c4699458b..0000000000
--- a/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn all_controller_schemas_advertises_both_vendors() {
- let names: Vec<_> = all_controller_schemas()
- .into_iter()
- .map(|s| s.function)
- .collect();
- assert_eq!(names, vec!["openclaw", "hermes"]);
-}
-
-#[test]
-fn all_registered_controllers_has_two_handlers() {
- let ctrl = all_registered_controllers();
- assert_eq!(ctrl.len(), 2);
- assert_eq!(ctrl[0].schema.function, "openclaw");
- assert_eq!(ctrl[1].schema.function, "hermes");
-}
-
-#[test]
-fn openclaw_schema_describes_optional_source_and_dry_run() {
- let s = schemas("openclaw");
- assert_eq!(s.namespace, "migrate");
- assert_eq!(s.function, "openclaw");
- let names: Vec<_> = s.inputs.iter().map(|f| f.name).collect();
- assert!(names.contains(&"source_workspace"));
- assert!(names.contains(&"dry_run"));
- for f in &s.inputs {
- assert!(!f.required, "input `{}` must be optional", f.name);
- }
- assert_eq!(s.outputs[0].name, "report");
-}
-
-#[test]
-fn migrate_openclaw_params_tolerates_empty_object() {
- let params: MigrateOpenClawParams = serde_json::from_value(json!({})).unwrap();
- assert!(params.source_workspace.is_none());
- assert!(params.dry_run.is_none());
-}
-
-#[test]
-fn migrate_openclaw_params_parses_both_fields() {
- let params: MigrateOpenClawParams = serde_json::from_value(json!({
- "source_workspace": "/tmp/old",
- "dry_run": false
- }))
- .unwrap();
- assert_eq!(params.source_workspace.as_deref(), Some("/tmp/old"));
- assert_eq!(params.dry_run, Some(false));
-}
-
-#[test]
-fn to_json_wraps_rpc_outcome_result_envelope() {
- let v = to_json(Outcome::single_log(json!({"done": true}), "done")).unwrap();
- assert!(v.get("logs").is_some() || v.get("result").is_some());
-}
-
-// ── Hermes schema tests ─────────────────────────────────────────
-
-#[test]
-fn hermes_schema_describes_optional_source_and_dry_run() {
- let s = schemas("hermes");
- assert_eq!(s.namespace, "migrate");
- assert_eq!(s.function, "hermes");
- let names: Vec<_> = s.inputs.iter().map(|f| f.name).collect();
- assert!(names.contains(&"source_workspace"));
- assert!(names.contains(&"dry_run"));
- for f in &s.inputs {
- assert!(!f.required, "input `{}` must be optional", f.name);
- }
- assert_eq!(s.outputs[0].name, "report");
-}
-
-#[test]
-fn migrate_hermes_params_tolerates_empty_object() {
- let params: MigrateHermesParams = serde_json::from_value(json!({})).unwrap();
- assert!(params.source_workspace.is_none());
- assert!(params.dry_run.is_none());
-}
-
-#[test]
-fn migrate_hermes_params_parses_both_fields() {
- let params: MigrateHermesParams = serde_json::from_value(json!({
- "source_workspace": "/home/u/.hermes",
- "dry_run": false
- }))
- .unwrap();
- assert_eq!(params.source_workspace.as_deref(), Some("/home/u/.hermes"));
- assert_eq!(params.dry_run, Some(false));
-}
diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs
index bbddb49a56..1132c9a5db 100644
--- a/crates/openhuman-core/src/config/mod.rs
+++ b/crates/openhuman-core/src/config/mod.rs
@@ -9,7 +9,6 @@
pub mod app_env;
pub mod daemon;
-pub mod migration_helpers;
pub mod migrations;
pub mod ops;
pub mod schema;