Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(admin): move-project — copy a project into another workspace
Djalma Júnior4a9fd1ff969f
diff --git a/README.md b/README.mdindex 9fadf264..23531e40 100644--- a/README.md+++ b/README.md@@ -79,7 +79,7 @@ priors are at the [bottom](#influences-and-prior-art).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)with bearer-token auth.- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `purge-project`,- `rename-project`, `lint`, `embed`, `forget-sweep`, `backup` are+ `rename-project`, `move-project`, `lint`, `embed`, `forget-sweep`, `backup` areall HTTP clients of the running server - never touch SQLite orwiki files directly. `status` also reports passive LLM/embeddingprovider health from the last real provider call. Server is thediff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex a611ac09..4a116c9a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -96,6 +96,12 @@ pub enum Command {/// Useful after renaming the project's directory on disk so the hook/// router keeps writing into the same logical project.RenameProject(RenameProjectArgs),+ /// Move a project into another workspace. Copies every latest page into+ /// the destination (a NEW project, or MERGES into an existing same-named+ /// one) through the normal write path, then PURGES the source. The+ /// source-side purge is irreversible — requires `--confirm`. Note:+ /// sessions/observations/handoffs do NOT migrate (only durable pages).+ MoveProject(MoveProjectArgs),/// Remove ai-memory's wiring (hooks, MCP, instructions) from all/// detected agents. Dry-run unless `--apply`.Uninstall(UninstallArgs),@@ -341,6 +347,25 @@ pub struct RenameProjectArgs {pub to: String,}+/// Arguments for `move-project`.+#[derive(Debug, Args)]+pub struct MoveProjectArgs {+ /// Source workspace. Defaults to `default`.+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]+ pub from_workspace: String,+ /// Project name to move. When omitted, auto-derived from the basename+ /// of the current git repo root (or CWD if no git repo).+ #[arg(long)]+ pub project: Option<String>,+ /// Destination workspace. Auto-created if it doesn't exist.+ #[arg(long)]+ pub to_workspace: String,+ /// REQUIRED — the move PURGES the source project after copying.+ /// Without this flag the CLI errors out.+ #[arg(long)]+ pub confirm: bool,+}+/// Arguments for `install-instructions`.#[derive(Debug, Args)]pub struct InstallInstructionsArgs {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex dd85d022..7199ee1b 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -19,6 +19,7 @@ pub mod install_instructions;pub mod install_mcp;pub mod lint;pub mod llm_test;+pub mod move_project;pub mod openclaw_plugin;pub mod purge_project;pub mod read_page;diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rsnew file mode 100644index 00000000..d15e2250--- /dev/null+++ b/crates/ai-memory-cli/src/commands/move_project.rs@@ -0,0 +1,88 @@+//! `ai-memory move-project` — thin HTTP client for cross-workspace project move.++use anyhow::{Result, bail};+use serde::Serialize;++use crate::cli::MoveProjectArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++/// Request sent to `POST /admin/move-project`.+#[derive(Serialize)]+struct MoveProjectRequest {+ from_workspace: String,+ project: String,+ to_workspace: String,+ confirm: bool,+}++/// Run the `move-project` subcommand.+///+/// Resolves the source project name (auto-derived from the git repo root+/// when `--project` is omitted), requires `--confirm` before sending the+/// request (it purges the source after copying), then prints the report.+///+/// # Errors+/// Returns an error when `--confirm` is absent, the server is unreachable,+/// or the server returns a non-2xx response.+pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {+ let project = super::resolve_project_name(config, args.project.as_deref())?;++ if !args.confirm {+ bail!(+ "move-project copies the project's pages into the destination \+ workspace, then PURGES the source.\n\+ Re-run with --confirm to proceed:\n\n \+ ai-memory move-project --from-workspace {} --project {} \+ --to-workspace {} --confirm",+ args.from_workspace,+ project,+ args.to_workspace,+ );+ }++ let endpoint = ServerEndpoint::from_config(config);+ let report: serde_json::Value = post_json(+ &endpoint,+ "/admin/move-project",+ &MoveProjectRequest {+ from_workspace: args.from_workspace.clone(),+ project: project.clone(),+ to_workspace: args.to_workspace.clone(),+ confirm: true,+ },+ )+ .await?;++ let copied = report["pages_copied"].as_u64().unwrap_or(0);+ let purged = report["source_purged"].as_bool().unwrap_or(false);+ let merged = report["merged_into_existing"].as_bool().unwrap_or(false);+ println!(+ "Moved {}/{} → {}/{}: {copied} pages copied{}{}.",+ args.from_workspace,+ project,+ args.to_workspace,+ project,+ if merged {+ " (merged into existing project)"+ } else {+ ""+ },+ if purged {+ ", source purged"+ } else {+ ", SOURCE LEFT INTACT (partial copy)"+ },+ );++ if let Some(skipped) = report["pages_skipped"].as_array()+ && !skipped.is_empty()+ {+ println!(+ "Warning: {} page(s) could not be read from the source and were \+ skipped; the source was NOT purged. Fix and re-run.",+ skipped.len()+ );+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 865e0fe2..acc1892f 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -63,6 +63,7 @@ async fn main() -> Result<()> {Command::Reorg(args) => commands::reorg::run(&config, args).await,Command::PurgeProject(args) => commands::purge_project::run(&config, args).await,Command::RenameProject(args) => commands::rename_project::run(&config, args).await,+ Command::MoveProject(args) => commands::move_project::run(&config, args).await,Command::Uninstall(args) => commands::uninstall::run(&config, args),Command::Auth(args) => commands::auth::run(&config, args).await,Command::User(args) => commands::user::run(&config, args).await,diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 888391ab..87fbfc3f 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -13,6 +13,8 @@//! - `POST /admin/commit` — stage + commit the wiki tree via git.//! - `POST /admin/purge-project` — delete a project and all its data.//! - `POST /admin/rename-project` — rename a project (column-only; no files move).+//! - `POST /admin/move-project` — move a project into another workspace+//! (copy latest pages via the write path, then purge the source).//! - `POST /admin/write-page` — write or update a wiki page atomically.//! - `GET /admin/read-page` — fetch the full body of a single wiki page by path.//!@@ -140,6 +142,7 @@ fn default_chunk_input_tokens() -> usize {/// - `POST /admin/commit`/// - `POST /admin/purge-project`/// - `POST /admin/rename-project`+/// - `POST /admin/move-project`/// - `POST /admin/write-page`pub fn admin_router(state: AdminState) -> Router {Router::new()@@ -155,6 +158,7 @@ pub fn admin_router(state: AdminState) -> Router {.route("/admin/commit", post(handle_commit)).route("/admin/purge-project", post(handle_purge_project)).route("/admin/rename-project", post(handle_rename_project))+ .route("/admin/move-project", post(handle_move_project)).route("/admin/write-page", post(handle_write_page)).route("/admin/users",@@ -1578,6 +1582,235 @@ async fn handle_rename_project()}+// ---------------------------------------------------------------------+// move-project+// ---------------------------------------------------------------------++/// JSON request body for `POST /admin/move-project`.+#[derive(Deserialize)]+struct MoveProjectRequest {+ /// Source workspace. Must already exist; we 404 if absent.+ from_workspace: String,+ /// Project name to move. Must already exist in `from_workspace`; 404 if absent.+ project: String,+ /// Destination workspace. Auto-created if absent.+ to_workspace: String,+ /// Mandatory confirmation flag. The move PURGES the source after+ /// copying, so without `confirm: true` the server returns 400.+ confirm: bool,+}++/// Wire-format report returned by `POST /admin/move-project`.+#[derive(Debug, Serialize)]+pub struct MoveProjectReport {+ /// `from_workspace/project` label.+ pub from: String,+ /// `to_workspace/project` label.+ pub to: String,+ /// `true` when the destination workspace already held a same-named+ /// project — the copy MERGED into it rather than creating a fresh one.+ pub merged_into_existing: bool,+ /// Number of latest pages copied into the destination.+ pub pages_copied: u64,+ /// Source paths whose on-disk file could not be read (copy skipped).+ /// When non-empty the source is NOT purged so a fixed re-run is safe.+ pub pages_skipped: Vec<String>,+ /// Whether the source project was purged (only when every page copied).+ pub source_purged: bool,+ /// Source `pages` rows deleted by the purge (all versions).+ pub source_pages_deleted: u64,+ /// Source `sessions` rows deleted by the purge.+ pub source_sessions_deleted: u64,+ /// Source `observations` rows deleted by the purge.+ pub source_observations_deleted: u64,+ /// Source `handoffs` rows deleted by the purge.+ pub source_handoffs_deleted: u64,+ /// Source `page_embeddings` rows deleted by the purge.+ pub source_embeddings_deleted: u64,+ /// Source on-disk dirs removed.+ pub files_deleted: Vec<String>,+ /// Source on-disk dirs that could not be removed (non-fatal).+ pub files_failed: Vec<String>,+}++async fn handle_move_project(+ State(state): State<Arc<AdminState>>,+ Json(req): Json<MoveProjectRequest>,+) -> impl IntoResponse {+ // Destructive: it purges the source after copying. Require confirm.+ if !req.confirm {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({+ "error": "destructive operation requires confirm=true"+ })),+ );+ }++ // A same-workspace "move" would get-or-create the SAME project as both+ // source and destination, copy it onto itself, then purge it — data+ // loss. Reject; in-workspace renames go through rename-project.+ if req.from_workspace == req.to_workspace {+ return (+ StatusCode::UNPROCESSABLE_ENTITY,+ Json(serde_json::json!({+ "error": "from_workspace and to_workspace are identical; use rename-project instead"+ })),+ );+ }++ // Resolve the SOURCE without auto-creating — 404 on a typo.+ let (src_ws, src_proj) =+ match lookup_ws_proj_no_create(&state, &req.from_workspace, &req.project).await {+ Ok(ids) => ids,+ Err(e) => return e,+ };++ // Detect MERGE: does the destination workspace already hold a same-named+ // project? (find_workspace may be None when the dest ws doesn't exist yet.)+ let merged_into_existing = match state.reader.find_workspace(req.to_workspace.clone()).await {+ Ok(Some(dst_ws)) => matches!(+ state.reader.find_project(dst_ws, req.project.clone()).await,+ Ok(Some(_))+ ),+ Ok(None) => false,+ Err(e) => return internal_err(e.to_string()),+ };++ // Get-or-create the DESTINATION (new ProjectId unless merging). Also+ // auto-creates the destination workspace.+ let (dst_ws, dst_proj) = match resolve_ws_proj(&state, &req.to_workspace, &req.project).await {+ Ok(ids) => ids,+ Err(e) => return e,+ };++ // Enumerate the source's latest pages (authoritative on is_latest).+ let summaries = match state+ .reader+ .list_pages(&req.from_workspace, &req.project)+ .await+ {+ Ok(s) => s,+ Err(e) => return internal_err(e.to_string()),+ };++ // COPY each page through the canonical write path so sanitization, link+ // re-resolution, FTS upsert (and admission/git-mirror on deploy) all fire.+ let mut pages_copied = 0u64;+ let mut pages_skipped: Vec<String> = Vec::new();+ for s in &summaries {+ let path = match PagePath::new(s.path.clone()) {+ Ok(p) => p,+ Err(_) => {+ pages_skipped.push(s.path.clone());+ continue;+ }+ };+ let tier: Tier = s.tier.parse().unwrap_or(Tier::Semantic);+ let pinned = matches!(+ state.reader.page_meta(&req.from_workspace, &req.project, &s.path).await,+ Ok(Some(ref m)) if m.pinned+ );+ let md = match state.wiki.read_page(src_ws, src_proj, &path) {+ Ok(md) => md,+ Err(e) => {+ warn!(path = %s.path, error = %e, "move-project: source read failed; skipping");+ pages_skipped.push(s.path.clone());+ continue;+ }+ };+ if let Err(e) = state+ .wiki+ .write_page(WritePageRequest {+ workspace_id: dst_ws,+ project_id: dst_proj,+ path: path.clone(),+ frontmatter: md.frontmatter,+ body: md.body,+ tier,+ pinned,+ // Preserve the stored title verbatim (PageSummary.title is+ // the DB-derived title), rather than re-deriving it.+ title: Some(s.title.clone()),+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ {+ // ANY copy failure aborts BEFORE the purge — the source survives.+ return internal_err(format!("copy of {} failed: {e}", s.path));+ }+ pages_copied += 1;+ }++ // Safety: a skipped (unreadable) source page blocks the purge — purging+ // now would destroy data we failed to copy. Report and let the operator+ // fix + re-run (re-running is idempotent: copied pages just supersede).+ if !pages_skipped.is_empty() {+ let report = MoveProjectReport {+ from: format!("{}/{}", req.from_workspace, req.project),+ to: format!("{}/{}", req.to_workspace, req.project),+ merged_into_existing,+ pages_copied,+ pages_skipped,+ source_purged: false,+ source_pages_deleted: 0,+ source_sessions_deleted: 0,+ source_observations_deleted: 0,+ source_handoffs_deleted: 0,+ source_embeddings_deleted: 0,+ files_deleted: Vec::new(),+ files_failed: Vec::new(),+ };+ return (+ StatusCode::OK,+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),+ );+ }++ // PURGE the source — only reached when every page copied successfully.+ let label = format!("{}/{}", req.from_workspace, req.project);+ let summary = match state.writer.purge_project(src_ws, src_proj, &label).await {+ Ok(s) => s,+ Err(e) => return internal_err(e.to_string()),+ };++ // Remove the source's on-disk dir (mirrors handle_purge_project). DB+ // cascade already deleted the rows; dir removal is best-effort.+ let proj_root = state.wiki.project_root(src_ws, src_proj);+ let proj_root_str = proj_root.display().to_string();+ let mut files_deleted: Vec<String> = Vec::new();+ let mut files_failed: Vec<String> = Vec::new();+ match std::fs::remove_dir_all(&proj_root) {+ Ok(()) => files_deleted.push(proj_root_str),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => {+ warn!(path = %proj_root_str, error = %e, "move-project: failed to remove source dir");+ files_failed.push(proj_root_str);+ }+ }++ let report = MoveProjectReport {+ from: label,+ to: format!("{}/{}", req.to_workspace, req.project),+ merged_into_existing,+ pages_copied,+ pages_skipped: Vec::new(),+ source_purged: true,+ source_pages_deleted: summary.pages_deleted,+ source_sessions_deleted: summary.sessions_deleted,+ source_observations_deleted: summary.observations_deleted,+ source_handoffs_deleted: summary.handoffs_deleted,+ source_embeddings_deleted: summary.embeddings_deleted,+ files_deleted,+ files_failed,+ };+ (+ StatusCode::OK,+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),+ )+}+// ---------------------------------------------------------------------// write-page// ---------------------------------------------------------------------diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsnew file mode 100644index 00000000..624557b1--- /dev/null+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -0,0 +1,305 @@+//! Integration tests for `POST /admin/move-project`.+//!+//! Follows the same pattern as `admin_rename.rs` / `admin_purge.rs`: build+//! a real [`AdminState`] over a tmpdir-backed store + wiki, drive the+//! router with `tower::ServiceExt::oneshot`.+//!+//! move-project copies every latest page of the source project into the+//! destination workspace through the normal write path, then purges the+//! source. Sessions/observations/handoffs are NOT migrated (only pages).++use ai_memory_core::{PagePath, Tier};+use ai_memory_mcp::{AdminState, admin_router};+use ai_memory_store::{DecayParams, Store};+use ai_memory_wiki::{Wiki, WritePageRequest};+use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::json;+use tempfile::TempDir;+use tower::ServiceExt;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++async fn make_state(tmp: &TempDir) -> (AdminState, Store) {+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let db_path = store.db_path().to_path_buf();+ let state = AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ embedder: None,+ provider_health: ai_memory_llm::ProviderHealth::default(),+ decay_params: DecayParams::default(),+ data_dir: tmp.path().to_path_buf(),+ db_path,+ bind: "127.0.0.1:0".to_string(),+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,+ };+ (state, store)+}++async fn body_json(resp: axum::response::Response) -> serde_json::Value {+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)+}++async fn post(state: AdminState, uri: &str, body: serde_json::Value) -> axum::response::Response {+ let router = admin_router(state);+ let req = Request::builder()+ .method("POST")+ .uri(uri)+ .header("content-type", "application/json")+ .body(Body::from(serde_json::to_vec(&body).unwrap()))+ .unwrap();+ router.oneshot(req).await.unwrap()+}++/// Seed `<ws>/<project>/<path>` with one page carrying `body`.+async fn seed_page(store: &Store, wiki: &Wiki, ws: &str, project: &str, path: &str, body: &str) {+ let ws_id = store.writer.get_or_create_workspace(ws).await.unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws_id, project, None)+ .await+ .unwrap();+ wiki.write_page(WritePageRequest {+ workspace_id: ws_id,+ project_id: proj,+ path: PagePath::new(path.to_string()).unwrap(),+ frontmatter: serde_json::json!({"title": path}),+ body: body.to_string(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some(path.into()),+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++/// Happy path: seed `src/proj` with two pages, move into `dst`, assert the+/// pages now live under `dst/proj`, the source project + on-disk dir are+/// gone, and the report counts add up.+#[tokio::test]+async fn move_project_copies_then_purges_source() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ seed_page(+ &store,+ &state.wiki,+ "src",+ "proj",+ "decisions/0001.md",+ "decision body",+ )+ .await;+ seed_page(+ &store,+ &state.wiki,+ "src",+ "proj",+ "gotchas/x.md",+ "see [[decisions/0001]] for the call",+ )+ .await;++ // Capture the source on-disk dir before `state` is consumed by `post`.+ let src_ws = store+ .reader+ .find_workspace("src".to_string())+ .await+ .unwrap()+ .expect("src workspace exists");+ let src_proj = store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap()+ .expect("src project exists");+ let src_dir = state.wiki.project_root(src_ws, src_proj);+ assert!(src_dir.exists(), "source dir must exist before move");++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK, "move must succeed");++ let body = body_json(resp).await;+ assert_eq!(body["pages_copied"].as_u64().unwrap_or(0), 2, "{body}");+ assert_eq!(body["source_purged"], true, "{body}");+ assert_eq!(body["merged_into_existing"], false, "{body}");++ // Both pages now belong to dst/proj (latest), content preserved.+ let dst_pages = store.reader.list_pages("dst", "proj").await.unwrap();+ let mut dst_paths: Vec<String> = dst_pages.into_iter().map(|p| p.path).collect();+ dst_paths.sort();+ assert_eq!(dst_paths, vec!["decisions/0001.md", "gotchas/x.md"]);++ let dst_ws = store+ .reader+ .find_workspace("dst".to_string())+ .await+ .unwrap()+ .expect("dst workspace exists");+ let dst_proj = store+ .reader+ .find_project(dst_ws, "proj".to_string())+ .await+ .unwrap()+ .expect("dst project exists");+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let read = wiki+ .read_page(+ dst_ws,+ dst_proj,+ &PagePath::new("decisions/0001.md".to_string()).unwrap(),+ )+ .unwrap();+ assert!(+ read.body.contains("decision body"),+ "moved body must round-trip; got {:?}",+ read.body+ );++ // Source project row and on-disk dir are gone.+ assert!(+ store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap()+ .is_none(),+ "source project row must be gone"+ );+ assert!(!src_dir.exists(), "source dir must be removed after move");+}++/// Without `confirm: true` the server returns 400 and leaves the source intact.+#[tokio::test]+async fn move_project_requires_confirm() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": false }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);++ // Source untouched.+ let src_ws = store+ .reader+ .find_workspace("src".to_string())+ .await+ .unwrap()+ .unwrap();+ assert!(+ store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap()+ .is_some(),+ "source project must still exist after a rejected move"+ );+}++/// A move from a nonexistent source project returns 404.+#[tokio::test]+async fn move_project_404_on_unknown_source() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_state(&tmp).await;++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "nope", "project": "ghost", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+}++/// Moving into a workspace that already has a same-named project MERGES:+/// the destination ends up with both the pre-existing and the moved pages.+#[tokio::test]+async fn move_project_merges_into_existing_dest() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;+ seed_page(&store, &state.wiki, "dst", "proj", "notes/b.md", "body b").await;++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);++ let body = body_json(resp).await;+ assert_eq!(body["merged_into_existing"], true, "{body}");+ assert_eq!(body["source_purged"], true, "{body}");++ // Destination holds BOTH the pre-existing and the moved page.+ let mut dst_paths: Vec<String> = store+ .reader+ .list_pages("dst", "proj")+ .await+ .unwrap()+ .into_iter()+ .map(|p| p.path)+ .collect();+ dst_paths.sort();+ assert_eq!(dst_paths, vec!["notes/a.md", "notes/b.md"]);++ // Source gone.+ let src_ws = store+ .reader+ .find_workspace("src".to_string())+ .await+ .unwrap()+ .unwrap();+ assert!(+ store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap()+ .is_none(),+ "source project must be purged after merge-move"+ );+}++/// A same-workspace move is rejected with 422 (use rename-project instead).+#[tokio::test]+async fn move_project_same_workspace_rejected() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_state(&tmp).await;++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "w", "project": "proj", "to_workspace": "w", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex fb7ee576..a6c8fe09 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -276,7 +276,8 @@ install-mcp commit llm-testforget-sweep lint embedgenerate-auth-token setup-agent bootstrapinstall-instructions reorg purge-project-rename-project uninstall auth+rename-project move-project uninstall+auth```Run `ai-memory --help` for the full tree.diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 29f683cb..6e302db6 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -10,6 +10,7 @@ on a homelab box where mistakes are harder to undo.|---|---|---|---|---|| `purge-project --confirm` | ✅ yes | the one project's data | no | Atomic `rm -rf <project_root>` on the namespaced disk path; sibling projects untouched. || `rename-project --from --to` | ✅ yes | no | yes (rename back) | Column-only update on `projects.name`. The on-disk dir is keyed by `project_id` (UUID), so the rename never moves a file. |+| `move-project --confirm` | ✅ yes | the source project (after copy) | no | Copies every latest page into the destination workspace via the write path, then purges the source. Sessions/observations/handoffs do **not** migrate. || `backup --output-path` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. || `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). || `reset --confirm` | ❌ **stop the server first** | yes, all data | no | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |@@ -119,6 +120,48 @@ Failure modes:- **`to` invalid (empty, slash, whitespace)** → 422.- **Source `from` not found** → 404.+### `move-project`++```bash+ai-memory move-project --from-workspace default --project my-project \+ --to-workspace other-workspace --confirm+```++Moves a project into a **different** workspace. Unlike `rename-project`+(a same-workspace column update), this crosses the workspace boundary,+so it is implemented as a copy-then-purge through the normal write path+rather than a low-level re-stamp:++1. Resolve the source `(from_workspace, project)`. 404 on miss.+2. Reject `from_workspace == to_workspace` (use `rename-project`) → 422.+3. Get-or-create `(to_workspace, project)`. If that workspace already+ holds a same-named project, the copy **merges** into it+ (`merged_into_existing: true` in the report); otherwise a fresh+ `project_id` is created (a true move).+4. For each latest page of the source, copy it into the destination via+ `Wiki::write_page` — so sanitization, link re-resolution, FTS, and+ (on deploy) the admission/git-mirror webhooks all fire naturally.+5. **Only after every page copied successfully**, purge the source+ project (cascade-delete its rows + remove its on-disk dir).++Safety: copy-before-purge means any copy failure aborts **before** the+purge, leaving the source intact. An unreadable source file is skipped+and also blocks the purge (`source_purged: false`) so a fixed re-run is+safe (re-running is idempotent — copied pages just supersede).++**What does NOT migrate:** only durable wiki pages move. The source's+`sessions`, `observations`, and `handoffs` (the raw episodic capture+log) are destroyed by the purge and are not recreated under the+destination. The page version history in SQLite resets (the moved pages+start a fresh supersession chain); the real page history lives in the+wiki's git mirror.++Failure modes:++- **Missing `--confirm`** → 400.+- **`from_workspace == to_workspace`** → 422 (use `rename-project`).+- **Source project not found** → 404.+### `backup````bash