Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(admin): move-project does a lossless true-move for fresh destinations

Djalma Júniorc8a3c14af50a
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 4a116c9a..0548de93 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -96,11 +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).
+ /// Move a project into another workspace. A fresh destination is a
+ /// lossless TRUE MOVE (re-stamp workspace_id, keep project_id, rename the
+ /// dir) — sessions/observations/handoffs and history all survive. A
+ /// destination that already holds a same-named project MERGES via
+ /// copy+purge (only durable pages migrate, source purged). Either way the
+ /// operation is irreversible — requires `--confirm`.
MoveProject(MoveProjectArgs),
/// Remove ai-memory's wiring (hooks, MCP, instructions) from all
/// detected agents. Dry-run unless `--apply`.
@@ -360,8 +361,8 @@ pub struct MoveProjectArgs {
/// 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.
+ /// REQUIRED — the move re-stamps (true-move) or copies+purges (merge) the
+ /// source, both irreversible. Without this flag the CLI errors out.
#[arg(long)]
pub confirm: bool,
}
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index d15e2250..f53d78ef 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -20,7 +20,8 @@ struct MoveProjectRequest {
///
/// 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.
+/// request (a true-move re-stamp or a copy+purge merge, both irreversible),
+/// then prints the report.
///
/// # Errors
/// Returns an error when `--confirm` is absent, the server is unreachable,
@@ -54,35 +55,38 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
)
.await?;
- let copied = report["pages_copied"].as_u64().unwrap_or(0);
+ let pages = 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 {
+ let moved_via = report["moved_via"].as_str().unwrap_or("");
+ let skipped_count = report["pages_skipped"].as_array().map_or(0, |s| s.len());
+
+ if moved_via == "true-move" {
+ // Lossless: re-stamped in place, nothing copied or purged.
+ println!(
+ "Moved {}/{} → {}/{}: {pages} pages re-stamped (true move — \
+ sessions, observations and history preserved).",
+ args.from_workspace, project, args.to_workspace, project,
+ );
+ } else {
+ // copy-purge (merge into an existing same-named project).
+ let tail = if skipped_count > 0 {
+ ", SOURCE LEFT INTACT (some pages unreadable — fix and re-run)"
+ } 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()
+ "Moved {}/{} → {}/{}: {pages} pages copied (merged into existing \
+ project){tail}.",
+ args.from_workspace, project, args.to_workspace, project,
);
+ if skipped_count > 0 {
+ println!(
+ "Warning: {skipped_count} page(s) could not be read from the \
+ source and were skipped; the source was NOT purged. Fix and re-run.",
+ );
+ }
}
Ok(())
}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index d4f2f120..3cb68034 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1610,7 +1610,17 @@ pub struct MoveProjectReport {
/// `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.
+ /// How the move was performed:
+ /// - `"true-move"`: a lossless cross-workspace re-stamp (same `project_id`,
+ /// one SQL transaction + one dir rename). Used when the destination has
+ /// no same-named project. Sessions/observations/handoffs and the full
+ /// supersession history all survive; nothing is re-embedded.
+ /// - `"copy-purge"`: the destination already held a same-named project, so
+ /// the source's latest pages were copied in and merged, then the source
+ /// purged. Only durable pages move; episodic rows are dropped.
+ pub moved_via: &'static str,
+ /// Number of latest pages copied into the destination (copy-purge) or
+ /// re-stamped in place (true-move).
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.
@@ -1633,6 +1643,95 @@ pub struct MoveProjectReport {
pub files_failed: Vec<String>,
}
+/// Lossless cross-workspace move: re-stamp the source project's
+/// `workspace_id` across every domain table (one transaction, same
+/// `project_id`), then rename its on-disk dir to the destination workspace.
+/// The caller has already verified the destination has no same-named project.
+///
+/// Ordering matters: the SQL re-stamp commits FIRST, then the dir is renamed.
+/// When the rename fires filesystem events at the new path, the watcher
+/// re-derives `(workspace_id, project_id)` from the path — which now matches
+/// what the DB already holds — so the upsert is a sha256 no-op. Renaming
+/// before the commit would briefly expose new-path files whose derived
+/// workspace disagrees with the DB.
+async fn true_move_project(
+ state: &Arc<AdminState>,
+ req: &MoveProjectRequest,
+ src_ws: WorkspaceId,
+ src_proj: ProjectId,
+) -> (StatusCode, Json<serde_json::Value>) {
+ // Ensure the destination workspace ROW exists (FK target for the
+ // re-stamp) without creating a new project — the existing project_id is
+ // what we move.
+ let dst_ws = match state
+ .writer
+ .get_or_create_workspace(req.to_workspace.clone())
+ .await
+ {
+ Ok(ws) => ws,
+ Err(e) => return internal_err(e.to_string()),
+ };
+
+ let summary = match state
+ .writer
+ .move_project_workspace(src_proj, src_ws, dst_ws)
+ .await
+ {
+ Ok(s) => s,
+ Err(StoreError::NotFound(msg)) => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": msg })),
+ );
+ }
+ Err(e) => return internal_err(e.to_string()),
+ };
+
+ // Land the files where the re-stamped rows now point. The SQL is already
+ // committed; a rename failure leaves the DB ahead of disk (the one
+ // inconsistency window) and is an exceptional fs error, not a normal path.
+ if let Err(e) = state.wiki.rename_project_dir(src_proj, src_ws, dst_ws) {
+ let src_dir = state.wiki.project_root(src_ws, src_proj);
+ let dst_dir = state.wiki.project_root(dst_ws, src_proj);
+ warn!(
+ error = %e,
+ src = %src_dir.display(),
+ dst = %dst_dir.display(),
+ "true-move: SQL re-stamp committed but dir rename failed; \
+ move the directory manually to reconcile"
+ );
+ return internal_err(format!(
+ "project rows moved but on-disk dir rename failed: {e}; \
+ manually move {} -> {}",
+ src_dir.display(),
+ dst_dir.display()
+ ));
+ }
+
+ let report = MoveProjectReport {
+ from: format!("{}/{}", req.from_workspace, req.project),
+ to: format!("{}/{}", req.to_workspace, req.project),
+ merged_into_existing: false,
+ moved_via: "true-move",
+ pages_copied: summary.pages_moved,
+ pages_skipped: Vec::new(),
+ // Nothing is purged in a true move — the source rows ARE the
+ // destination rows, just re-stamped.
+ 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(),
+ };
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),
+ )
+}
+
async fn handle_move_project(
State(state): State<Arc<AdminState>>,
Json(req): Json<MoveProjectRequest>,
@@ -1677,8 +1776,21 @@ async fn handle_move_project(
Err(e) => return internal_err(e.to_string()),
};
- // Get-or-create the DESTINATION (new ProjectId unless merging). Also
- // auto-creates the destination workspace.
+ // FRESH destination (no same-named project there) → lossless TRUE MOVE.
+ // Re-stamp the source project's workspace_id across every domain table in
+ // one transaction (same project_id), then rename its on-disk dir. This
+ // keeps sessions/observations/handoffs and the full supersession history,
+ // and is O(1) instead of O(pages) — no per-page re-write, re-embed, or
+ // admission webhook. The copy+purge path below is reserved for the MERGE
+ // case, where two project_ids can't be re-stamped into one
+ // (UNIQUE(workspace_id, name) collision).
+ if !merged_into_existing {
+ return true_move_project(&state, &req, src_ws, src_proj).await;
+ }
+
+ // MERGE: the destination already holds a same-named project. Get-or-create
+ // it (auto-creating the destination workspace) and copy the source's
+ // latest pages into it, then purge the source.
let (dst_ws, dst_proj) = match resolve_ws_proj(&state, &req.to_workspace, &req.project).await {
Ok(ids) => ids,
Err(e) => return e,
@@ -1771,6 +1883,7 @@ async fn handle_move_project(
title: Some(s.title.clone()),
author_id: None,
actor: ai_memory_core::ActorContext::anonymous(),
+ admission_ctx: None,
})
.await
{
@@ -1806,6 +1919,7 @@ async fn handle_move_project(
from: format!("{}/{}", req.from_workspace, req.project),
to: format!("{}/{}", req.to_workspace, req.project),
merged_into_existing,
+ moved_via: "copy-purge",
pages_copied,
pages_skipped,
source_purged: false,
@@ -1849,6 +1963,7 @@ async fn handle_move_project(
from: label,
to: format!("{}/{}", req.to_workspace, req.project),
merged_into_existing,
+ moved_via: "copy-purge",
pages_copied,
pages_skipped: Vec::new(),
source_purged: true,
diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rs
index 388e0c64..a98a6088 100644
--- a/crates/ai-memory-mcp/tests/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/admin_move.rs
@@ -80,6 +80,7 @@ async fn seed_page(store: &Store, wiki: &Wiki, ws: &str, project: &str, path: &s
title: Some(path.into()),
author_id: None,
actor: ai_memory_core::ActorContext::anonymous(),
+ admission_ctx: None,
})
.await
.unwrap();
@@ -89,11 +90,12 @@ async fn seed_page(store: &Store, wiki: &Wiki, ws: &str, project: &str, path: &s
// 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.
+/// Happy path with a FRESH destination (no same-named project there): this is
+/// a lossless TRUE MOVE — the project_id is re-stamped into `dst`, nothing is
+/// purged, and the on-disk dir is renamed. Assert the pages now live under
+/// `dst/proj`, the source name no longer resolves, and the dir moved.
#[tokio::test]
-async fn move_project_copies_then_purges_source() {
+async fn move_project_true_move_into_fresh_dest() {
let tmp = TempDir::new().unwrap();
let (state, store) = make_state(&tmp).await;
@@ -142,9 +144,29 @@ async fn move_project_copies_then_purges_source() {
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["moved_via"], "true-move", "{body}");
+ // Nothing is purged in a true move — the rows are re-stamped, not copied.
+ assert_eq!(body["source_purged"], false, "{body}");
assert_eq!(body["merged_into_existing"], false, "{body}");
+ // project_id is preserved: the dst project IS the former src project.
+ let dst_ws_check = store
+ .reader
+ .find_workspace("dst".to_string())
+ .await
+ .unwrap()
+ .unwrap();
+ let dst_proj_check = store
+ .reader
+ .find_project(dst_ws_check, "proj".to_string())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ dst_proj_check, src_proj,
+ "true move keeps the same project_id"
+ );
+
// 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();
@@ -257,6 +279,9 @@ async fn move_project_merges_into_existing_dest() {
let body = body_json(resp).await;
assert_eq!(body["merged_into_existing"], true, "{body}");
+ // A same-named project in the dest forces copy+purge (can't re-stamp two
+ // project_ids into one).
+ assert_eq!(body["moved_via"], "copy-purge", "{body}");
assert_eq!(body["source_purged"], true, "{body}");
// Destination holds BOTH the pre-existing and the moved page.
@@ -424,3 +449,90 @@ async fn move_project_carries_source_embedding() {
);
}
}
+
+/// The whole point of the true move over copy+purge: a session and its
+/// observation — episodic rows that copy+purge would DROP — survive a move
+/// into a fresh destination, re-stamped to the new workspace.
+#[tokio::test]
+async fn move_project_true_move_preserves_sessions_and_observations() {
+ use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
+
+ 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 src_ws = store
+ .reader
+ .find_workspace("src".to_string())
+ .await
+ .unwrap()
+ .unwrap();
+ let src_proj = store
+ .reader
+ .find_project(src_ws, "proj".to_string())
+ .await
+ .unwrap()
+ .unwrap();
+
+ // Seed an episodic session + observation under src/proj.
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: src_ws,
+ project_id: src_proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(NewObservation {
+ session_id: sid,
+ workspace_id: src_ws,
+ project_id: src_proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "prompt".into(),
+ body: "do the thing".into(),
+ importance: 5,
+ })
+ .await
+ .unwrap();
+
+ 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["moved_via"], "true-move", "{body}");
+ assert_eq!(body["source_purged"], false, "{body}");
+
+ // The session followed the project to the new workspace (same session_id,
+ // same project_id, new workspace_id).
+ let dst_ws = store
+ .reader
+ .find_workspace("dst".to_string())
+ .await
+ .unwrap()
+ .unwrap();
+ let (sess_ws, sess_proj) = store
+ .reader
+ .session_project_ids(sid)
+ .await
+ .unwrap()
+ .expect("session must still exist after the move");
+ assert_eq!(sess_ws, dst_ws, "session re-stamped to dst workspace");
+ assert_eq!(sess_proj, src_proj, "session keeps its project_id");
+
+ // The observation survived and re-stamped too.
+ let obs = store.reader.observations_for_session(sid).await.unwrap();
+ assert_eq!(obs.len(), 1, "observation must survive the move");
+ assert_eq!(obs[0].workspace_id, dst_ws, "observation re-stamped to dst");
+}
diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rs
index a0c77011..bfd7f6c1 100644
--- a/crates/ai-memory-store/src/error.rs
+++ b/crates/ai-memory-store/src/error.rs
@@ -48,6 +48,12 @@ pub enum StoreError {
#[error("invalid project name: {0}")]
InvalidProjectName(String),
+ /// A lookup expected a row that was not present (e.g. moving a project
+ /// that no longer exists in the source workspace — typically a race or
+ /// caller-invariant violation).
+ #[error("not found: {0}")]
+ NotFound(String),
+
/// A UNIQUE constraint was violated by an insert (e.g. duplicate
/// `users.username` / `users.email`). The string carries a
/// human-readable explanation the CLI / admin endpoint surfaces
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index a4a55ba4..ad939ec9 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -997,6 +997,94 @@ pub fn purge_project(
})
}
+/// Summary returned by [`move_project_workspace`] and exposed via
+/// [`crate::writer::WriterHandle::move_project_workspace`].
+#[derive(Debug, Default, Clone)]
+pub struct MoveSummary {
+ /// `pages` rows re-stamped (all versions, not just latest).
+ pub pages_moved: u64,
+ /// `sessions` rows re-stamped.
+ pub sessions_moved: u64,
+ /// `observations` rows re-stamped.
+ pub observations_moved: u64,
+ /// `handoffs` rows re-stamped.
+ pub handoffs_moved: u64,
+ /// `audit_log` rows re-stamped.
+ pub audit_log_moved: u64,
+}
+
+/// Re-stamp a project's `workspace_id` across every domain table in ONE
+/// transaction, keeping the same `project_id`. This is a lossless "true move":
+/// pages, sessions, observations, handoffs and supersession history all stay
+/// attached to the project — unlike a copy+purge, which drops everything but
+/// the latest pages.
+///
+/// `page_embeddings` and `links` are keyed by `page_id` (not `workspace_id`),
+/// so they follow automatically with no re-stamp.
+///
+/// The destination workspace row MUST already exist (FK on
+/// `projects.workspace_id`); the caller get-or-creates it first. A same-named
+/// project already living in the destination workspace makes the `projects`
+/// UPDATE violate `UNIQUE (workspace_id, name)` and the whole transaction
+/// rolls back — the caller must detect that merge case and route it through
+/// copy+purge instead.
+pub fn move_project_workspace(
+ conn: &mut Connection,
+ project_id: &ProjectId,
+ from_workspace: &WorkspaceId,
+ to_workspace: &WorkspaceId,
+) -> StoreResult<MoveSummary> {
+ let tx = conn.transaction()?;
+
+ let pid = project_id.as_bytes();
+ let from = from_workspace.as_bytes();
+ let to = to_workspace.as_bytes();
+
+ // Re-stamp child tables first (they carry the denormalized workspace_id),
+ // then the project row last. Order is irrelevant inside the transaction,
+ // but doing projects last keeps the UNIQUE(workspace_id, name) failure —
+ // the merge-collision signal — as the final, cheapest check.
+ let pages_moved = tx.execute(
+ "UPDATE pages SET workspace_id = ?1 WHERE project_id = ?2",
+ params![&to[..], &pid[..]],
+ )? as u64;
+ let sessions_moved = tx.execute(
+ "UPDATE sessions SET workspace_id = ?1 WHERE project_id = ?2",
+ params![&to[..], &pid[..]],
+ )? as u64;
+ let observations_moved = tx.execute(
+ "UPDATE observations SET workspace_id = ?1 WHERE project_id = ?2",
+ params![&to[..], &pid[..]],
+ )? as u64;
+ let handoffs_moved = tx.execute(
+ "UPDATE handoffs SET workspace_id = ?1 WHERE project_id = ?2",
+ params![&to[..], &pid[..]],
+ )? as u64;
+ let audit_log_moved = tx.execute(
+ "UPDATE audit_log SET workspace_id = ?1 WHERE project_id = ?2 AND workspace_id = ?3",
+ params![&to[..], &pid[..], &from[..]],
+ )? as u64;
+
+ let projects_updated = tx.execute(
+ "UPDATE projects SET workspace_id = ?1 WHERE id = ?2 AND workspace_id = ?3",
+ params![&to[..], &pid[..], &from[..]],
+ )?;
+ if projects_updated != 1 {
+ return Err(StoreError::NotFound(format!(
+ "project {project_id} not found in source workspace {from_workspace}"
+ )));
+ }
+
+ tx.commit()?;
+ Ok(MoveSummary {
+ pages_moved,
+ sessions_moved,
+ observations_moved,
+ handoffs_moved,
+ audit_log_moved,
+ })
+}
+
/// Remove embedding rows in a workspace/project scope whose `(provider, model, dim)`
/// does not match the configured triple, plus rows tied to superseded pages.
pub fn delete_stale_page_embeddings(
@@ -1821,4 +1909,106 @@ mod tests {
"pages_fts_au must not fire on access_count/last_accessed_at updates: {sql}"
);
}
+
+ /// True move: re-stamping a project's workspace_id keeps the same
+ /// project_id and carries pages, sessions and observations along —
+ /// the whole point of the lossless move. The summary counts must
+ /// match what actually moved.
+ #[test]
+ fn move_project_workspace_restamps_all_domain_rows() {
+ use ai_memory_core::ObservationKind;
+
+ let (_tmp, mut conn, src_ws, proj) = fresh_db();
+ let dst_ws = get_or_create_workspace(&mut conn, "djalmajr").unwrap();
+
+ // Seed a page, a session and an observation under the source ws.
+ let page_id = upsert_page(&mut conn, &page(src_ws, proj, "notes/a.md", "body")).unwrap();
+ let sid = SessionId::new();
+ begin_session(
+ &mut conn,
+ &NewSession {
+ id: sid,
+ workspace_id: src_ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ },
+ )
+ .unwrap();
+ insert_observation(
+ &mut conn,
+ &NewObservation {
+ session_id: sid,
+ workspace_id: src_ws,
+ project_id: proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "t".into(),
+ body: "b".into(),
+ importance: 5,
+ },
+ )
+ .unwrap();
+
+ let summary = move_project_workspace(&mut conn, &proj, &src_ws, &dst_ws).unwrap();
+ assert_eq!(summary.pages_moved, 1);
+ assert_eq!(summary.sessions_moved, 1);
+ assert_eq!(summary.observations_moved, 1);
+
+ // The project_id is unchanged; every row now points at dst_ws.
+ // `projects` keys the project by `id`; child tables by `project_id`.
+ let count_in = |table: &str, ws: &ai_memory_core::WorkspaceId| -> i64 {
+ let id_col = if table == "projects" {
+ "id"
+ } else {
+ "project_id"
+ };
+ conn.query_row(
+ &format!("SELECT COUNT(*) FROM {table} WHERE {id_col} = ?1 AND workspace_id = ?2"),
+ params![&proj.as_bytes()[..], ws.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap()
+ };
+ for table in ["projects", "pages", "sessions", "observations"] {
+ assert_eq!(count_in(table, &dst_ws), 1, "{table} must move to dst ws");
+ assert_eq!(count_in(table, &src_ws), 0, "{table} must leave src ws");
+ }
+ // The page keeps its id (embeddings/links follow via page_id).
+ let still_there: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pages WHERE id = ?1 AND workspace_id = ?2",
+ params![&page_id.as_bytes()[..], dst_ws.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(still_there, 1);
+ }
+
+ /// A same-named project already in the destination workspace makes the
+ /// projects UPDATE collide with UNIQUE(workspace_id, name); the whole
+ /// transaction must roll back, leaving the source intact. The admin
+ /// layer detects this merge case up front and routes it to copy+purge.
+ #[test]
+ fn move_project_workspace_rolls_back_on_name_collision() {
+ let (_tmp, mut conn, src_ws, proj) = fresh_db();
+ let dst_ws = get_or_create_workspace(&mut conn, "djalmajr").unwrap();
+ // Destination already holds a project named "scratch".
+ get_or_create_project(&mut conn, &dst_ws, "scratch", None).unwrap();
+ upsert_page(&mut conn, &page(src_ws, proj, "notes/a.md", "body")).unwrap();
+
+ let err = move_project_workspace(&mut conn, &proj, &src_ws, &dst_ws);
+ assert!(err.is_err(), "name collision must fail the move");
+
+ // Source rows untouched after rollback.
+ let src_pages: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pages WHERE project_id = ?1 AND workspace_id = ?2",
+ params![&proj.as_bytes()[..], src_ws.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(src_pages, 1, "rollback must preserve source pages");
+ }
}
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 5da6dff3..e36b6b7c 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -18,7 +18,7 @@ use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
use crate::error::{StoreError, StoreResult};
-use crate::ops::{self, EmbeddingWrite, PurgeSummary, ReorgSummary};
+use crate::ops::{self, EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};
use crate::users::{self, TOKEN_HASH_LEN};
/// Commands accepted by the writer thread.
@@ -119,6 +119,16 @@ pub(crate) enum WriteCmd {
label: String,
reply: oneshot::Sender<StoreResult<PurgeSummary>>,
},
+ /// Re-stamp a project's `workspace_id` across every domain table in one
+ /// transaction, keeping the same `project_id` (a lossless cross-workspace
+ /// "true move"). The caller renames the on-disk dir and ensures the
+ /// destination workspace row exists first.
+ MoveProjectWorkspace {
+ project_id: ProjectId,
+ from_workspace: WorkspaceId,
+ to_workspace: WorkspaceId,
+ reply: oneshot::Sender<StoreResult<MoveSummary>>,
+ },
/// Rename a project's `name` column without moving any files (the wiki
/// is flat on disk). Fails with [`crate::error::StoreError::ProjectNameTaken`]
/// when `new_name` is already used in the same workspace.
@@ -438,6 +448,36 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Re-stamp a project's `workspace_id` to `to_workspace` across every
+ /// domain table in one transaction, keeping the same `project_id`. This is
+ /// the lossless cross-workspace move: pages, sessions, observations and
+ /// supersession history all follow. The destination workspace row must
+ /// already exist; the caller renames the on-disk dir afterwards.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down,
+ /// [`StoreError::NotFound`] if the project is absent from the source
+ /// workspace, or propagates the SQL error (e.g. a
+ /// `UNIQUE(workspace_id, name)` collision when the destination already
+ /// holds a same-named project — the caller routes that merge case to
+ /// copy+purge instead).
+ pub async fn move_project_workspace(
+ &self,
+ project_id: ProjectId,
+ from_workspace: WorkspaceId,
+ to_workspace: WorkspaceId,
+ ) -> StoreResult<MoveSummary> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::MoveProjectWorkspace {
+ project_id,
+ from_workspace,
+ to_workspace,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Rename a project within its workspace (column-only; no file moves).
///
/// # Errors
@@ -810,6 +850,20 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::purge_project(&mut conn, &workspace_id, &project_id, &label);
send_or_warn(reply, result, "purge_project");
}
+ WriteCmd::MoveProjectWorkspace {
+ project_id,
+ from_workspace,
+ to_workspace,
+ reply,
+ } => {
+ let result = ops::move_project_workspace(
+ &mut conn,
+ &project_id,
+ &from_workspace,
+ &to_workspace,
+ );
+ send_or_warn(reply, result, "move_project_workspace");
+ }
WriteCmd::RenameProject {
workspace_id,
project_id,
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index bd69b661..3a29a9ce 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -170,6 +170,41 @@ impl Wiki {
.join(project_id.to_string())
}
+ /// Move a project's on-disk directory from one workspace to another,
+ /// keeping the same `project_id` segment:
+ /// `<wiki_root>/<from_ws>/<proj>` → `<wiki_root>/<to_ws>/<proj>`.
+ ///
+ /// Both paths share the same `<wiki_root>`, so `fs::rename` is an atomic
+ /// metadata-only operation on every supported filesystem — no per-file
+ /// copy, no re-embed. The destination workspace directory is created
+ /// first. This pairs with
+ /// [`WriterHandle::move_project_workspace`](ai_memory_store) — callers
+ /// re-stamp SQLite first, then call this to land the files at the path the
+ /// re-stamped rows already point at, so the watcher's own-write
+ /// short-circuit absorbs the resulting events.
+ ///
+ /// # Errors
+ /// Propagates [`WikiError::Io`] if the destination already exists or the
+ /// rename fails (e.g. cross-device, which cannot happen within one root).
+ pub fn rename_project_dir(
+ &self,
+ project_id: ProjectId,
+ from_workspace: WorkspaceId,
+ to_workspace: WorkspaceId,
+ ) -> WikiResult<()> {
+ let src = self.project_root(from_workspace, project_id);
+ if !src.exists() {
+ // Nothing on disk to move (a project with zero written pages).
+ return Ok(());
+ }
+ let dst = self.project_root(to_workspace, project_id);
+ if let Some(parent) = dst.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(&src, &dst)?;
+ Ok(())
+ }
+
/// Absolute on-disk path for a page within a specific project.
#[must_use]
pub fn abs_path(
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 6e302db6..8d88dc71 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -10,7 +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. |
+| `move-project --confirm` | ✅ yes | source only in the merge case | no | Fresh destination → lossless **true move** (re-stamp `workspace_id`, keep `project_id`, rename the dir): sessions/observations/handoffs + history all survive. Destination with a same-named project → **copy+purge merge**: only latest pages 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). |
@@ -128,39 +128,67 @@ ai-memory move-project --from-workspace default --project my-project \
```
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:
+(a same-workspace column update), this crosses the workspace boundary.
+The destination decides which of two strategies runs — reported as
+`moved_via` in the response:
+
+**1. Fresh destination → `"true-move"` (lossless, the common case).**
+When the destination workspace has **no** same-named project, the move is
+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.
+3. Get-or-create the destination **workspace** row (not a new project).
+4. Re-stamp `workspace_id` across every domain table for the project in
+ **one transaction**, keeping the same `project_id`
+ (`projects`, `pages`, `sessions`, `observations`, `handoffs`,
+ `audit_log`). `page_embeddings` and `links` are keyed by `page_id`, so
+ they follow with no re-stamp.
+5. `fs::rename` the project dir
+ `<wiki>/<from_ws>/<proj>` → `<wiki>/<to_ws>/<proj>` (atomic within one
+ wiki root). SQL commits **before** the rename, so when the watcher sees
+ the new-path events it re-derives the same `(ws, proj)` the DB already
+ holds and the reindex is a sha256 no-op.
+
+This is O(1) (one transaction + one rename), re-embeds nothing, and
+**preserves everything** — sessions, observations, handoffs and the full
+supersession history all travel with the project.
+
+**2. Destination already has a same-named project → `"copy-purge"`
+(merge).** Two distinct `project_id`s can't be re-stamped into one (it
+would collide on `UNIQUE (workspace_id, name)`), so the source's latest
+pages are copied into the existing destination project via
+`Wiki::write_page` (sanitization, link re-resolution, FTS, and — on
+deploy — the admission/git-mirror webhooks all fire), source embeddings
+are carried over verbatim, and only then is the source purged
+(`merged_into_existing: true`, `source_purged: true`).
+
+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 (merge case only):** in the `copy-purge` path the
+source's `sessions`, `observations`, and `handoffs` (the raw episodic
+capture log) are dropped by the purge, and the moved pages start a fresh
+supersession chain (the real page history lives in the wiki's git
+mirror). The `true-move` path has no such loss.
+
+> **Operational caveat — moving the project the current session writes
+> to.** Lifecycle hooks stamp an observation on every tool call into the
+> session's project. If you move that very project mid-session, the next
+> hook re-creates the source (`scratch`-style) under the old workspace.
+> Before moving a live project, point the repo's `.ai-memory.toml` at the
+> **destination** workspace first, so new hook events already land there
+> and the move is a clean no-contention operation.
Failure modes:
- **Missing `--confirm`** → 400.
- **`from_workspace == to_workspace`** → 422 (use `rename-project`).
- **Source project not found** → 404.
+- **Re-stamp committed but dir rename failed** (true-move, exceptional fs
+ error) → 500 with the exact `mv <src> <dst>` to run to reconcile.
### `backup`